Skip to content

Instantly share code, notes, and snippets.

@benjaminjbachman
Created March 16, 2021 17:25
Show Gist options
  • Save benjaminjbachman/99ba2de785be5a047977b4a0b4252062 to your computer and use it in GitHub Desktop.
Save benjaminjbachman/99ba2de785be5a047977b4a0b4252062 to your computer and use it in GitHub Desktop.
Generates a shorter, older-style s3 presigned url. Can only be used in older regions.
import base64, hmac, os, hashlib, sys, time, urllib
def get_shorter_presigned_url(bucket, key, seconds_alive=600, aws_access_key_id = os.environ.get("AWS_ACCESS_KEY_ID"), aws_secret_access_key=os.environ.get("AWS_SECRET_ACCESS_KEY"), aws_region = os.environ.get("AWS_DEFAULT_REGION")):
"""
based on https://gist.github.com/mdwhatcott/df9bf33cf044b7352e18
but updated some outdate libraries and added functionality for other regions
no leading '/' on key
eg get_shorter_presigned_url("my-bucket", "some/file.txt")
"""
assert aws_access_key_id
assert aws_secret_access_key
assert aws_region
resource = urllib.parse.quote(f"/{bucket}/{key}")
expires = int(time.time()) + seconds_alive
# see https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationStringToSign
raw_value = "GET\n\n\n{0}\n{1}".format(expires, resource).encode("ascii")
signature = base64.b64encode(hmac.new(aws_secret_access_key, raw_value, hashlib.sha1).digest())
return "https://s3.{0}.amazonaws.com{1}?AWSAccessKeyId={2}&Expires={3}&Signature={4}".format(aws_region,
resource, urllib.parse.quote(aws_access_key_id), expires, urllib.parse.quote(signature))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment