Restrict access to an AWS Lambda function URL origin
CloudFront provides origin access control (OAC) for restricting access to a Lambda function URL origin.
Create a new OAC
Complete the steps described in the following topics to set up a new OAC in CloudFront.
Note
If you use PUT
or POST
methods with your Lambda function
URL, your users must include the payload hash value in the x-amz-content-sha256
header when sending the request to CloudFront. Lambda doesn't support unsigned
payloads.
Prerequisites
Before you create and set up OAC, you must have a CloudFront distribution with a Lambda function URL as the origin. For more information, see Use a Lambda function URL.
Give the OAC permission to access the Lambda function URL
Before you create an OAC or set it up in a CloudFront distribution, make sure the OAC has permission to access the Lambda function URL. Do this after you create a CloudFront distribution, but before you add the OAC to the Lambda function URL in the distribution configuration.
Note
To update the IAM policy for the Lambda function URL, you must use the AWS Command Line Interface (AWS CLI). Editing the IAM policy in the Lambda console isn't supported at this time.
The following AWS CLI command grants the CloudFront service principal
(cloudfront.amazonaws.com
) access to your Lambda function URL. The
Condition
element in the policy allows CloudFront to access Lambda
only when the request is on behalf of the CloudFront distribution
that contains the Lambda function URL.
Example : AWS CLI command to update a policy to allow read-only access to a CloudFront OAC
The following AWS CLI command allows the CloudFront distribution
(
) access your
Lambda E1PDK09ESKHJWT
.FUNCTION_URL_NAME
aws lambda add-permission \ --statement-id "AllowCloudFrontServicePrincipal" \ --action "lambda:InvokeFunctionUrl" \ --principal "cloudfront.amazonaws.com" \ --source-arn "arn:aws:cloudfront::
123456789012
:distribution/E1PDK09ESKHJWT
" \ --function-nameFUNCTION_URL_NAME
Note
If you create a distribution and it doesn't have permission to your Lambda function URL, you can choose Copy CLI command from the CloudFront console, and then enter this command from your command line terminal. For more information, see Granting function access to AWS services in the AWS Lambda Developer Guide.
Create the OAC
To create an OAC, you can use the AWS Management Console, AWS CloudFormation, the AWS CLI, or the CloudFront API.
Advanced settings for origin access control
The CloudFront OAC feature includes advanced settings that are intended only for specific use cases. Use the recommended settings unless you have a specific need for the advanced settings.
OAC contains a setting named Signing behavior (in the console), or
SigningBehavior
(in the API, CLI, and AWS CloudFormation). This setting provides the
following options:
- Always sign origin requests (recommended setting)
-
We recommend using this setting, named Sign requests (recommended) in the console, or
always
in the API, CLI, and AWS CloudFormation. With this setting, CloudFront always signs all requests that it sends to the Lambda function URL. - Never sign origin requests
-
This setting is named Do not sign requests in the console, or
never
in the API, CLI, and AWS CloudFormation. Use this setting to turn off OAC for all origins in all distributions that use this OAC. This can save time and effort compared to removing an OAC from all origins and distributions that use it, one by one. With this setting, CloudFront doesn't sign any requests that it sends to the Lambda function URL.Warning
To use this setting, the Lambda function URL must be publicly accessible. If you use this setting with a Lambda function URL that's not publicly accessible, CloudFront can't access the origin. The Lambda function URL returns errors to CloudFront and CloudFront passes those errors on to viewers. For more information, see Security and auth model for Lambda function URLs in the AWS Lambda User Guide.
- Don't override the viewer (client)
Authorization
header -
This setting is named Do not override authorization header in the console, or
no-override
in the API, CLI, and AWS CloudFormation. Use this setting when you want CloudFront to sign origin requests only when the corresponding viewer request does not include anAuthorization
header. With this setting, CloudFront passes on theAuthorization
header from the viewer request when one is present, but signs the origin request (adding its ownAuthorization
header) when the viewer request doesn't include anAuthorization
header.Warning
-
If you use this setting, you must specify the Signature Version 4 signing for the Lambda function URL instead of your CloudFront distribution's name or CNAME. When CloudFront forwards the
Authorization
header from the viewer request to the Lambda function URL, Lambda will validate the signature against the host of the Lambda URL domain. If the signature isn't based on the Lambda URL domain, the host in the signature won't match the host used by the Lambda URL origin. This means the request will fail, resulting in a signature validation error.
-
To pass along the
Authorization
header from the viewer request, you must add theAuthorization
header to a cache policy for all cache behaviors that use Lambda function URLs associated with this origin access control.
-
Example template code
If your CloudFront origin is a Lambda function URL that's associated with an OAC, you can use
the following Python script to upload files to the Lambda function with the
POST
method.
This code assumes that you configured the OAC with the default signing behavior set to Always sign origin requests and that you didn't select the Do not override authorization header setting.
This configuration allows the OAC to manage SigV4 authorization correctly with Lambda
by using the Lambda hostname. The payload is signed by using SigV4 from the IAM
identity that's authorized for the Lambda function URL, which is designated as the
IAM_AUTH
type.
The template demonstrates how to handle signed payload hash values in the
x-amz-content-sha256 header for POST
requests from the
client side. Specifically, this template is designed to manage form data payloads. The
template enables secure file uploads to a Lambda function URL through CloudFront, and uses
AWS authentication mechanisms to ensure that only authorized requests can access the
Lambda function.
The code includes the following functionality:
-
Meets the requirement for including the payload hash in the x-amz-content-sha256 header
-
Uses SigV4 authentication for secure AWS service access
-
Supports file uploads by using multipart form data
-
Includes error handling for request exceptions
import boto3 from botocore.auth import SigV4Auth from botocore.awsrequest import AWSRequest import requests import hashlib import os def calculate_body_hash(body): return hashlib.sha256(body).hexdigest() def sign_request(request, credentials, region, service): sigv4 = SigV4Auth(credentials, service, region) sigv4.add_auth(request) def upload_file_to_lambda(cloudfront_url, file_path, region): # AWS credentials session = boto3.Session() credentials = session.get_credentials() # Prepare the multipart form-data boundary = "------------------------boundary" # Read file content with open(file_path, 'rb') as file: file_content = file.read() # Get the filename from the path filename = os.path.basename(file_path) # Prepare the multipart body body = ( f'--{boundary}\r\n' f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n' f'Content-Type: application/octet-stream\r\n\r\n' ).encode('utf-8') body += file_content body += f'\r\n--{boundary}--\r\n'.encode('utf-8') # Calculate SHA256 hash of the entire body body_hash = calculate_body_hash(body) # Prepare headers headers = { 'Content-Type': f'multipart/form-data; boundary={boundary}', 'x-amz-content-sha256': body_hash } # Create the request request = AWSRequest( method='POST', url=cloudfront_url, data=body, headers=headers ) # Sign the request sign_request(request, credentials, region, 'lambda') # Get the signed headers signed_headers = dict(request.headers) # Print request headers before sending print("Request Headers:") for header, value in signed_headers.items(): print(f"{header}: {value}") try: # Send POST request with signed headers response = requests.post( cloudfront_url, data=body, headers=signed_headers ) # Print response status and content print(f"\nStatus code: {response.status_code}") print("Response:", response.text) # Print response headers print("\nResponse Headers:") for header, value in response.headers.items(): print(f"{header}: {value}") except requests.exceptions.RequestException as e: print(f"An error occurred: {e}") # Usage cloudfront_url = "https://d111111abcdef8.cloudfront.net" file_path = r"filepath" region = "us-east-1" # example: "us-west-2" upload_file_to_lambda(cloudfront_url, file_path, region)