Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST file to AWS Mediastore with Python 3 without SDK, without CLI

I would like to POST a mp4 file to AWS MediaStore using Python and the Signature v4. I am trying to use the PutObject action from MediaStore. For this job, I cannot use the SDK or the CLI.

I can make GET requests to MediaStore with Python without the SDK or the CLI, but regarding POST requests, I didn't understand how I should handle the payload. I got the following error :

<InvalidSignatureException>
  <Message>The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.</Message>
</InvalidSignatureException>

Non working POST code


# NON WORKING CODE

import sys, os, base64, datetime, hashlib, hmac 
import requests # pip install requests

method = 'PUT'
service = 'mediastore'
host = 'qwerty123.data.mediastore.ap-northeast-1.amazonaws.com'
region = 'ap-northeast-1'
endpoint = 'https://qwerty123.data.mediastore.ap-northeast-1.amazonaws.com'
request_parameters = 'Action=PutObject&Path=dummyfile.mp4&Version=2017-09-01'

cwd = os.getcwd()

def sign(key, msg):
    return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()

def getSignatureKey(key, dateStamp, regionName, serviceName):
    kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)
    kRegion = sign(kDate, regionName)
    kService = sign(kRegion, serviceName)
    kSigning = sign(kService, 'aws4_request')
    return kSigning


access_key = "AXXXXXXXXXXXA" 
secret_key = "UXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXD"  
if access_key is None or secret_key is None:
    print('No access key is available.')
    sys.exit()


t = datetime.datetime.utcnow()
amzdate = t.strftime('%Y%m%dT%H%M%SZ')
datestamp = t.strftime('%Y%m%d') 

canonical_uri = '/' 

canonical_querystring = request_parameters

payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()

canonical_headers = 'content-type:video/mp4' + '\n' +'host:' + host + '\n' + 'x-amz-content-sha256:'+payload_hash  + '\n' + 'x-amz-date:' + amzdate + '\n' +  'x-amz-storage-class:'+ "TEMPORAL" + '\n'

signed_headers = 'content-type;host;x-amz-content-sha256;x-amz-storage-class;x-amz-date'

canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash

algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
string_to_sign = algorithm + '\n' +  amzdate + '\n' +  credential_scope + '\n' +  hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()

signing_key = getSignatureKey(secret_key, datestamp, region, service)

signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()

authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' +  'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature

headers = {'Content-Type':'video/mp4','x-amz-date':amzdate,'X-Amz-Content-Sha256':payload_hash, 'X-Amz-Storage-Class':'TEMPORAL', 'Authorization':authorization_header}

request_url = endpoint + '?' + canonical_querystring

print('\n * * * * * * * * * * * * BEGIN REQUEST * * * * * * * * * * * * ')
print('Request URL = ' + request_url)
files = {'file': open(cwd + "/" + "dummyfile.mp4", 'rb')}
r = requests.post(request_url, headers=headers, files=files)

print('\n* * * * * * * * * * *  * * * RESPONSE * * * * * * * * * * * * *')
print('Response code: %d\n' % r.status_code)
print(r.text)

From the doc :

POST premium/canada/mlaw.avi
Host: aaabbbcccdddee.files.mediastore-us-west-2.com
x-amz-Date: 20170323T120000Z
Authorization: AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20141123/us-west-2/mediastore/aws4_request,SignedHeaders=host;x-amz-date;x-amz-mediastore-version,Signature=9257c16da6b25a715ce900a5b45b03da0447acf430195dcb540091b12966f2a2
Content-Length: 0
x-amz-mediastore-version: 2016-07-11

Working GET code


# WORKING CODE
 # NB Apparently the x-amz-content-sha256 header is not necessary

import sys, os, base64, datetime, hashlib, hmac 
import requests # pip install requests

method = 'GET'
service = 'mediastore'
host = 'qwerty123.data.mediastore.ap-northeast-1.amazonaws.com'
region = 'ap-northeast-1'
endpoint = 'https://qwerty123.data.mediastore.ap-northeast-1.amazonaws.com'
request_parameters = 'Action=ListItems&Version=2017-09-01'


def sign(key, msg):
    return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()

def getSignatureKey(key, dateStamp, regionName, serviceName):
    kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)
    kRegion = sign(kDate, regionName)
    kService = sign(kRegion, serviceName)
    kSigning = sign(kService, 'aws4_request')
    return kSigning


access_key = "AXXXXXXXXXXXXXXA" 
secret_key = "UXXXXXXXXXXXXXXXXXXXXXXXXXXXXD"  
if access_key is None or secret_key is None:
    print('No access key is available.')
    sys.exit()


t = datetime.datetime.utcnow()
amzdate = t.strftime('%Y%m%dT%H%M%SZ')
datestamp = t.strftime('%Y%m%d') 

canonical_uri = '/' 

canonical_querystring = request_parameters


payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()

canonical_headers = 'content-type:application/x-www-form-urlencoded; charset=utf-8' + '\n' +'host:' + host + '\n' +  'x-amz-date:' + amzdate + '\n' #+ 'x-amz-content-sha256:'+payload_hash  + '\n'


signed_headers = 'content-type;host;x-amz-date' #x-amz-content-sha256;

canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash

algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
string_to_sign = algorithm + '\n' +  amzdate + '\n' +  credential_scope + '\n' +  hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()


signing_key = getSignatureKey(secret_key, datestamp, region, service)


signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()


authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' +  'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature

headers = {'Content-Type':'application/x-www-form-urlencoded; charset=utf-8','x-amz-date':amzdate, 'Authorization':authorization_header} #'X-Amz-Content-Sha256':payload_hash,

request_url = endpoint + '?' + canonical_querystring

print('\n * * * * * * * * * * * * BEGIN REQUEST * * * * * * * * * * * * ')
print('Request URL = ' + request_url)
r = requests.get(request_url, headers=headers)

print('\n* * * * * * * * * * *  * * * RESPONSE * * * * * * * * * * * * *')
print('Response code: %d\n' % r.status_code)
print(r.text)
 

Any help would be highly appreciated.

EDIT

I removed the x-amz-content-sha256 header from the GET request, the request is still working. I tried to do the same thing with the POST request, without success.

like image 223
mehdi.r Avatar asked May 15 '19 06:05

mehdi.r


2 Answers

did you try to change the method from method = 'PUT' to method = 'POST' ? I think that will help you since the method used in the DOCs is POST

use this code for SHA Key Signing:

def sign(key, msg):
    return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()

def getSignatureKey(key, dateStamp, regionName, serviceName):
    kDate = sign(("AWS4" + key).encode("utf-8"), dateStamp)
    kRegion = sign(kDate, regionName)
    kService = sign(kRegion, serviceName)
    kSigning = sign(kService, "aws4_request")
    return kSigning

Source AWS

and Troubleshooting

Regular Upload Request : Source: AWS-PDF

POST premium/canada/mlaw.avi
Host: aaabbbcccdddee.files.mediastore-us-west-2.com
x-amz-Date: 20170323T120000Z
Authorization: AWS4-HMAC-SHA256  Credential=AKIAIOSFODNN7EXAMPLE/20141123/us-
west-2/mediastore/aws4_request,SignedHeaders=host;x-amz-date;x-amz-mediastore-version,Signature=9257c16da6b25a715ce900a5b45b03da0447acf430195dcb540091b12966f2a2
Content-Length: 0
x-amz-mediastore-version: 2016-07-11
like image 107
LinPy Avatar answered Oct 18 '22 21:10

LinPy


The following things were wrong in my script :

The canonical_uri must be set to : /filename.mp4

The following headers are necessary : host,contentlength,x-amz-content-sha256,x-amz-date

The payload_hash must be set to UNSIGNED-PAYLOAD

Here is the working curl request (with Ruby variables) :

`curl -v -X PUT -T #{target_file} \\
  -H "Content-Lenght: #{file_size}" \\
  -H "host: #{host}" \\
  -H "X-Amz-Content-Sha256: #{payload_hash}" \\
  -H "X-Amz-Date: #{timestamp}" \\
  -H "Authorization: AWS4-HMAC-SHA256 Credential=#{access_key_id + '/' + credential_scope}, SignedHeaders=#{headers_lst}, Signature=#{signature}" \\
  "https://qwerty123.data.mediastore.ap-northeast-1.amazonaws.com#{canonical_uri}?#{request_parameters}"`

@TonyJafar : thanks for your help

like image 44
mehdi.r Avatar answered Oct 18 '22 21:10

mehdi.r