Search code examples
pythonamazon-web-servicesboto3amazon-cloudfrontpre-signed-url

Cloudfront URL never expires


Scenerio: I am trying to generate cloudfront signed urls to objects in s3.

STEPS:
1. created an object in s3 bucket and made it public.
2. created a cloudfront distribution pointing to that s3 bucket.
3. generated the signed url using the code below

The following is the code to generate cloudfront signed urls from their docs.

import datetime

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from botocore.signers import CloudFrontSigner


def rsa_signer(message):
    with open('path/to/key.pem', 'rb') as key_file:
        private_key = serialization.load_pem_private_key(
        key_file.read(),
        password=None,
        backend=default_backend()
       )
    return private_key.sign(message, padding.PKCS1v15(), hashes.SHA1())

key_id = 'AKIAIOSFODNN7EXAMPLE'
url = 'https://d2949o5mkkp72v.cloudfront.net/hello.txt'
expire_date = datetime.datetime(2017, 1, 1)

cloudfront_signer = CloudFrontSigner(key_id, rsa_signer)

# Create a signed url that will be valid until the specfic expiry date
# provided using a canned policy.
signed_url = cloudfront_signer.generate_presigned_url(url, date_less_than=expire_date)
print(signed_url)

output:

https://d2949o5mkkp72v.cloudfront.net/hello.txt?Expires=1483228800&Signature=some_signature&Key-Pair-Id=AKIAIOSFODNN7EXAMPLE

The above url is pointing to a date back in time but I am still able to access the object via this URL. Also I can access the object by truncating the Signature and Key-Pair-Id query params.

What could have gone wrong here?


Solution

  • I found the solution to the problem. The error was actually not in the code but in the configuration of cloudfront distribution.

    The following configuration was missing: cloudfront signed url config option

    Hopefully it helps :)

    If editing the configuration for an already existing distribution, you'll find this "Restrict Viewer Access" setting within the edit settings of a behavior record within the "behaviors" tab.
    enter image description here