Skip to content

Instantly share code, notes, and snippets.

@stark525
Last active November 18, 2019 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stark525/34d579c1d03b9cfdfb36fdd083efc853 to your computer and use it in GitHub Desktop.
Save stark525/34d579c1d03b9cfdfb36fdd083efc853 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import boto3
import json
import base64
def headers_to_go_style(headers):
retval = {}
for k, v in headers.items():
retval[k] = [v]
return retval
def generate_vault_request(role_name=""):
session = boto3.session.Session()
# if you have credentials from non-default sources, call
# session.set_credentials here, before calling session.create_client
client = session.client('sts')
endpoint = client._endpoint
operation_model = client._service_model.operation_model('GetCallerIdentity')
request_dict = client._convert_to_request_dict({}, operation_model)
awsIamServerId = 'vault.example.com'
request_dict['headers']['X-Vault-awsiam-Server-Id'] = awsIamServerId
request = endpoint.create_request(request_dict, operation_model)
# It's now signed...
return {
'iam_http_request_method': request.method,
'iam_request_url': base64.b64encode(request.url.encode('ascii')),
'iam_request_body': base64.b64encode(request.body.encode('ascii')),
'iam_request_headers': base64.b64encode(json.dumps(headers_to_go_style(dict(request.headers)))), # It's a CaseInsensitiveDict, which is not JSON-serializable
'role': role_name,
}
if __name__ == "__main__":
print(json.dumps(generate_vault_request('TestRole')))
@stark525
Copy link
Author

stark525 commented Jun 5, 2017

Line 9: iteritems -> items (2to3)
Line 36: print -> print() (2to3)

Line 31: TypeError: Object of type 'bytes' is not JSON serializable
This works for python2 but doesn't for python3 - is this why you had written the original program in python2? Is there a way to do this in python3?
Sorry as this is no longer about Vault but I'm not a very experienced programmer ☹️

@arunp2k
Copy link

arunp2k commented Jan 22, 2019

Anyone made it work with Python3? If so, how you get rid of "Line 31: TypeError: Object of type 'bytes' is not JSON serializable" error?

@xxxVxxx
Copy link

xxxVxxx commented Nov 18, 2019

b64encode needs it in byte format , so you need to encode it into that format from str, but then we need it back in str format so we need to later decode it. So we can overcome this problem by changing:
'iam_request_headers': base64.b64encode(json.dumps(headers_to_go_style(dict(request.headers)))),
to:
'iam_request_headers': base64.b64encode(json.dumps(headers_to_go_style(dict(request.headers))).encode()).decode(),

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment