id
stringlengths
8
78
source
stringclasses
743 values
chunk_id
int64
1
5.05k
text
stringlengths
593
49.7k
AmazonCloudFront_DevGuide-150
AmazonCloudFront_DevGuide.pdf
150
origin 386 Amazon CloudFront Developer Guide OpenSSL and s2n use different names for ciphers than the TLS standards use (RFC 2246, RFC 4346, RFC 5246, and RFC 8446). The following table includes the OpenSSL and s2n name, and the RFC name, for each cipher. For ciphers with elliptic curve key exchange algorithms, CloudFront supports the following elliptic curves: • prime256v1 • secp384r1 • X25519 OpenSSL and s2n cipher name RFC cipher name Supported ECDSA ciphers ECDHE-ECDSA-AES256-GCM-SHA384 TLS_ECDHE_ECDSA_WITH_AES_25 6_GCM_SHA384 ECDHE-ECDSA-AES256-SHA384 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 384 ECDHE-ECDSA-AES256-SHA TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA ECDHE-ECDSA-AES128-GCM-SHA256 TLS_ECDHE_ECDSA_WITH_AES_12 8_GCM_SHA256 ECDHE-ECDSA-AES128-SHA256 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 256 ECDHE-ECDSA-AES128-SHA TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA Supported RSA ciphers ECDHE-RSA-AES256-GCM-SHA384 TLS_ECDHE_RSA_WITH_AES_256_ GCM_SHA384 ECDHE-RSA-AES256-SHA384 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA38 4 Supported protocols and ciphers between CloudFront and the origin 387 Amazon CloudFront Developer Guide OpenSSL and s2n cipher name RFC cipher name ECDHE-RSA-AES256-SHA TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA ECDHE-RSA-AES128-GCM-SHA256 TLS_ECDHE_RSA_WITH_AES_128_ GCM_SHA256 ECDHE-RSA-AES128-SHA256 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA25 6 ECDHE-RSA-AES128-SHA TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA AES256-SHA AES128-SHA DES-CBC3-SHA RC4-MD5 TLS_RSA_WITH_AES_256_CBC_SHA TLS_RSA_WITH_AES_128_CBC_SHA TLS_RSA_WITH_3DES_EDE_CBC_SHA TLS_RSA_WITH_RC4_128_MD5 Supported signature schemes between CloudFront and the origin CloudFront supports the following signature schemes for connections between CloudFront and the origin. • TLS_SIGNATURE_SCHEME_RSA_PKCS1_SHA256 • TLS_SIGNATURE_SCHEME_RSA_PKCS1_SHA384 • TLS_SIGNATURE_SCHEME_RSA_PKCS1_SHA512 • TLS_SIGNATURE_SCHEME_RSA_PKCS1_SHA224 • TLS_SIGNATURE_SCHEME_ECDSA_SHA256 • TLS_SIGNATURE_SCHEME_ECDSA_SHA384 • TLS_SIGNATURE_SCHEME_ECDSA_SHA512 • TLS_SIGNATURE_SCHEME_ECDSA_SHA224 • TLS_SIGNATURE_SCHEME_RSA_PKCS1_SHA1 • TLS_SIGNATURE_SCHEME_ECDSA_SHA1 Supported protocols and ciphers between CloudFront and the origin 388 Amazon CloudFront Developer Guide Use alternate domain names and HTTPS If you want to use your own domain name in the URLs for your files (for example, https:// www.example.com/image.jpg) and you want your viewers to use HTTPS, you must complete the steps in the following topics. (If you use the default CloudFront distribution domain name in your URLs, for example, https://d111111abcdef8.cloudfront.net/image.jpg, follow the guidance in the following topic instead: Require HTTPS for communication between viewers and CloudFront.) Important When you add a certificate to your distribution, CloudFront immediately propagates the certificate to all of its edge locations. As new edge locations become available, CloudFront propagates the certificate to those locations, too. You can't restrict the edge locations that CloudFront propagates the certificates to. Topics • Choose how CloudFront serves HTTPS requests • Requirements for using SSL/TLS certificates with CloudFront • Quotas on using SSL/TLS certificates with CloudFront (HTTPS between viewers and CloudFront only) • Configure alternate domain names and HTTPS • Determine the size of the public key in an SSL/TLS RSA certificate • Increase the quotas for SSL/TLS certificates • Rotate SSL/TLS certificates • Revert from a custom SSL/TLS certificate to the default CloudFront certificate • Switch from a custom SSL/TLS certificate with dedicated IP addresses to SNI Choose how CloudFront serves HTTPS requests If you want your viewers to use HTTPS and to use alternate domain names for your files, choose one of the following options for how CloudFront serves HTTPS requests: • Use Server Name Indication (SNI) – Recommended Use alternate domain names and HTTPS 389 Amazon CloudFront Developer Guide • Use a dedicated IP address in each edge location This section explains how each option works. Use SNI to serve HTTPS requests (works for most clients) Server Name Indication (SNI) is an extension to the TLS protocol that is supported by browsers and clients released after 2010. If you configure CloudFront to serve HTTPS requests using SNI, CloudFront associates your alternate domain name with an IP address for each edge location. When a viewer submits an HTTPS request for your content, DNS routes the request to the IP address for the correct edge location. The IP address to your domain name is determined during the SSL/TLS handshake negotiation; the IP address isn't dedicated to your distribution. The SSL/TLS negotiation occurs early in the process of establishing an HTTPS connection. If CloudFront can't immediately determine which domain the request is for, it drops the connection. When a viewer that supports SNI submits an HTTPS request for your content, here's what happens: 1. The viewer automatically gets the domain name from the request URL and adds it to the SNI extension of the TLS client hello message. 2. When CloudFront receives the TLS client hello, it uses the domain name in the SNI extension to find the matching CloudFront distribution and sends back the associated TLS certificate. 3. The viewer and CloudFront perform SSL/TLS negotiation. 4. CloudFront returns the requested content to the viewer. For a current list of the browsers that support SNI, see the Wikipedia entry Server Name Indication. If you want to use SNI but some of your users' browsers don't support SNI, you have several options: • Configure CloudFront to serve HTTPS requests by using dedicated IP addresses instead of SNI. For more information, see Use a dedicated IP address to serve HTTPS requests (works for all clients). • Use the CloudFront SSL/TLS certificate instead of a custom certificate. This requires that you use the CloudFront domain name for your distribution in the URLs for your files, for example, https://d111111abcdef8.cloudfront.net/logo.png. If you use the default CloudFront certificate, viewers must support the SSL protocol
AmazonCloudFront_DevGuide-151
AmazonCloudFront_DevGuide.pdf
151
entry Server Name Indication. If you want to use SNI but some of your users' browsers don't support SNI, you have several options: • Configure CloudFront to serve HTTPS requests by using dedicated IP addresses instead of SNI. For more information, see Use a dedicated IP address to serve HTTPS requests (works for all clients). • Use the CloudFront SSL/TLS certificate instead of a custom certificate. This requires that you use the CloudFront domain name for your distribution in the URLs for your files, for example, https://d111111abcdef8.cloudfront.net/logo.png. If you use the default CloudFront certificate, viewers must support the SSL protocol TLSv1 or later. CloudFront doesn't support SSLv3 with the default CloudFront certificate. Choose how CloudFront serves HTTPS requests 390 Amazon CloudFront Developer Guide You also must change the SSL/TLS certificate that CloudFront is using from a custom certificate to the default CloudFront certificate: • If you haven't used your distribution to distribute your content, you can just change the configuration. For more information, see Update a distribution. • If you have used your distribution to distribute your content, you must create a new CloudFront distribution and change the URLs for your files to reduce or eliminate the amount of time that your content is unavailable. For more information, see Revert from a custom SSL/ TLS certificate to the default CloudFront certificate. • If you can control which browser your users use, have them upgrade their browser to one that supports SNI. • Use HTTP instead of HTTPS. Use a dedicated IP address to serve HTTPS requests (works for all clients) Server Name Indication (SNI) is one way to associate a request with a domain. Another way is to use a dedicated IP address. If you have users who can't upgrade to a browser or client released after 2010, you can use a dedicated IP address to serve HTTPS requests. For a current list of the browsers that support SNI, see the Wikipedia entry Server Name Indication. Important If you configure CloudFront to serve HTTPS requests using dedicated IP addresses, you incur an additional monthly charge. The charge begins when you associate your SSL/ TLS certificate with a distribution and you enable the distribution. For more information about CloudFront pricing, see Amazon CloudFront Pricing. In addition, see Using the Same Certificate for Multiple CloudFront Distributions. When you configure CloudFront to serve HTTPS requests by using dedicated IP addresses, CloudFront associates your certificate with a dedicated IP address in each CloudFront edge location. When a viewer submits an HTTPS request for your content, here's what happens: 1. DNS routes the request to the IP address for your distribution in the applicable edge location. 2. If a client request provides the SNI extension in the ClientHello message, CloudFront searches for a distribution that is associated with that SNI. Choose how CloudFront serves HTTPS requests 391 Amazon CloudFront Developer Guide • If there's a match, CloudFront responds to the request with the SSL/TLS certificate. • If there's no match, CloudFront uses the IP address instead to identify your distribution and to determine which SSL/TLS certificate to return to the viewer. 3. The viewer and CloudFront perform SSL/TLS negotiation using your SSL/TLS certificate. 4. CloudFront returns the requested content to the viewer. This method works for every HTTPS request, regardless of the browser or other viewer that the user is using. Note Dedicated IPs are not static IPs and can change over time. The IP address that is returned for the edge location is allocated dynamically from the IP address ranges of the CloudFront edge servers list. The IP address ranges for CloudFront edge servers are subject to change. To be notified of IP address changes, subscribe to AWS Public IP Address Changes via Amazon SNS. Request permission to use three or more dedicated IP SSL/TLS certificates If you need permission to permanently associate three or more SSL/TLS dedicated IP certificates with CloudFront, perform the following procedure. For more details about HTTPS requests, see Choose how CloudFront serves HTTPS requests. Note This procedure is for using three or more dedicated IP certificates across your CloudFront distributions. The default value is 2. Keep in mind you cannot bind more than one SSL certificate to a distribution. You can only associate a single SSL/TLS certificate to a CloudFront distribution at a time. This number is for the total number of dedicated IP SSL certificates you can use across all of your CloudFront distributions. To request permission to use three or more certificates with a CloudFront distribution 1. Go to the Support Center and create a case. Choose how CloudFront serves HTTPS requests 392 Amazon CloudFront Developer Guide 2. Indicate how many certificates you need permission to use, and describe the circumstances in your request. We'll update your account as soon as possible. 3. Continue with the next
AmazonCloudFront_DevGuide-152
AmazonCloudFront_DevGuide.pdf
152
You can only associate a single SSL/TLS certificate to a CloudFront distribution at a time. This number is for the total number of dedicated IP SSL certificates you can use across all of your CloudFront distributions. To request permission to use three or more certificates with a CloudFront distribution 1. Go to the Support Center and create a case. Choose how CloudFront serves HTTPS requests 392 Amazon CloudFront Developer Guide 2. Indicate how many certificates you need permission to use, and describe the circumstances in your request. We'll update your account as soon as possible. 3. Continue with the next procedure. Requirements for using SSL/TLS certificates with CloudFront The requirements for SSL/TLS certificates are described in this topic. They apply to both of the following, except as noted: • Certificates for using HTTPS between viewers and CloudFront • Certificates for using HTTPS between CloudFront and your origin Topics • Certificate issuer • AWS Region for AWS Certificate Manager • Certificate format • Intermediate certificates • Key type • Private key • Permissions • Size of the certificate key • Supported types of certificates • Certificate expiration date and renewal • Domain names in the CloudFront distribution and in the certificate • Minimum SSL/TLS protocol version • Supported HTTP versions Certificate issuer We recommend that you use a public certificate issued by AWS Certificate Manager (ACM). For information about getting a certificate from ACM, see the AWS Certificate Manager User Guide. To use an ACM certificate with CloudFront, make sure you request (or import) the certificate in the US East (N. Virginia) Region (us-east-1). Requirements for using SSL/TLS certificates with CloudFront 393 Amazon CloudFront Developer Guide CloudFront supports the same certificate authorities (CAs) as Mozilla, so if you don’t use ACM, use a certificate issued by a CA on the Mozilla Included CA Certificate List. For more information about getting and installing a certificate, refer to the documentation for your HTTP server software and to the documentation for the CA. AWS Region for AWS Certificate Manager To use a certificate in AWS Certificate Manager (ACM) to require HTTPS between viewers and CloudFront, make sure you request (or import) the certificate in the US East (N. Virginia) Region (us-east-1). If you want to require HTTPS between CloudFront and your origin, and you’re using a load balancer in Elastic Load Balancing as your origin, you can request or import the certificate in any AWS Region. Certificate format The certificate must be in X.509 PEM format. This is the default format if you’re using AWS Certificate Manager. Intermediate certificates If you’re using a third-party certificate authority (CA), list all of the intermediate certificates in the certificate chain that’s in the .pem file, beginning with one for the CA that signed the certificate for your domain. Typically, you’ll find a file on the CA website that lists intermediate and root certificates in the proper chained order. Important Do not include the following: the root certificate, intermediate certificates that are not in the trust path, or your CA’s public key certificate. Here’s an example: -----BEGIN CERTIFICATE----- Intermediate certificate 2 -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- Intermediate certificate 1 Requirements for using SSL/TLS certificates with CloudFront 394 Amazon CloudFront -----END CERTIFICATE----- Key type Developer Guide CloudFront supports RSA and ECDSA public–private key pairs. CloudFront supports HTTPS connections to both viewers and origins using RSA and ECDSA certificates. With AWS Certificate Manager (ACM), you can request and import RSA or ECDSA certificates and then associate them with your CloudFront distribution. For lists of the RSA and ECDSA ciphers supported by CloudFront that you can negotiate in HTTPS connections, see the section called “Supported protocols and ciphers between viewers and CloudFront” and the section called “Supported protocols and ciphers between CloudFront and the origin”. Private key If you're using a certificate from a third-party certificate authority (CA), note the following: • The private key must match the public key that is in the certificate. • The private key must be in PEM format. • The private key cannot be encrypted with a password. If AWS Certificate Manager (ACM) provided the certificate, ACM doesn’t release the private key. The private key is stored in ACM for use by AWS services that are integrated with ACM. Permissions You must have permission to use and import the SSL/TLS certificate. If you’re using AWS Certificate Manager (ACM), we recommend that you use AWS Identity and Access Management permissions to restrict access to the certificates. For more information, see Identity and access management in the AWS Certificate Manager User Guide. Size of the certificate key The certificate key size that CloudFront supports depends on the type of key and certificate. For RSA certificates: CloudFront supports 1024-bit, 2048-bit, and 3072-bit, and 4096-bit RSA keys. The maximum key length for an RSA certificate that you use with CloudFront
AmazonCloudFront_DevGuide-153
AmazonCloudFront_DevGuide.pdf
153
integrated with ACM. Permissions You must have permission to use and import the SSL/TLS certificate. If you’re using AWS Certificate Manager (ACM), we recommend that you use AWS Identity and Access Management permissions to restrict access to the certificates. For more information, see Identity and access management in the AWS Certificate Manager User Guide. Size of the certificate key The certificate key size that CloudFront supports depends on the type of key and certificate. For RSA certificates: CloudFront supports 1024-bit, 2048-bit, and 3072-bit, and 4096-bit RSA keys. The maximum key length for an RSA certificate that you use with CloudFront is 4096 bits. Requirements for using SSL/TLS certificates with CloudFront 395 Amazon CloudFront Developer Guide Note that ACM issues RSA certificates with up to 2048-bit keys. To use a 3072-bit or 4096-bit RSA certificate, you need to obtain the certificate externally and import it into ACM, after which it will be available for you to use with CloudFront. For information about how to determine the size of an RSA key, see Determine the size of the public key in an SSL/TLS RSA certificate. For ECDSA certificates: CloudFront supports 256-bit keys. To use an ECDSA certificate in ACM to require HTTPS between viewers and CloudFront, use the prime256v1 elliptic curve. Supported types of certificates CloudFront supports all types of certificates issued by a trusted certificate authority. Certificate expiration date and renewal If you’re using certificates that you get from a third-party certificate authority (CA), you must monitor certificate expiration dates and renew the certificates that you import into AWS Certificate Manager (ACM) or upload to the AWS Identity and Access Management certificate store before they expire. Important To avoid certificate expiration issues, renew or reimport your certificate at least 24 hours before the NotAfter value of your current certificate. If your certificate expires within 24 hours, request a new certificate from ACM or import a new certificate to ACM. Next, associate the new certificate to the CloudFront distribution. CloudFront might continue to use the previous certificate while your certificate renewal or reimport is in progress. This is an asynchronous process that can take up to 24 hours before CloudFront shows your changes. If you’re using ACM provided certificates, ACM manages certificate renewals for you. For more information, see Managed renewal in the AWS Certificate Manager User Guide. Requirements for using SSL/TLS certificates with CloudFront 396 Amazon CloudFront Developer Guide Domain names in the CloudFront distribution and in the certificate When you’re using a custom origin, the SSL/TLS certificate on your origin includes a domain name in the Common Name field, and possibly several more in the Subject Alternative Names field. (CloudFront supports wildcard characters in certificate domain names.) One of the domain names in the certificate must match the domain name that you specify for Origin Domain Name. If no domain name matches, CloudFront returns HTTP status code 502 (Bad Gateway) to the viewer. Important When you add an alternate domain name to a distribution, CloudFront checks that the alternate domain name is covered by the certificate that you’ve attached. The certificate must cover the alternate domain name in the subject alternate name (SAN) field of the certificate. This means the SAN field must contain an exact match for the alternate domain name, or contain a wildcard at the same level of the alternate domain name that you’re adding. For more information, see Requirements for using alternate domain names. Minimum SSL/TLS protocol version If you’re using dedicated IP addresses, set the minimum SSL/TLS protocol version for the connection between viewers and CloudFront by choosing a security policy. For more information, see Security policy (minimum SSL/TLS version) in the topic Distribution settings reference. Supported HTTP versions If you associate one certificate with more than one CloudFront distribution, all the distributions associated with the certificate must use the same option for Supported HTTP versions. You specify this option when you create or update a CloudFront distribution. Quotas on using SSL/TLS certificates with CloudFront (HTTPS between viewers and CloudFront only) Note the following quotas on using SSL/TLS certificates with CloudFront. These quotas apply only to the SSL/TLS certificates that you provision by using AWS Certificate Manager (ACM), that you Quotas on using SSL/TLS certificates with CloudFront (HTTPS between viewers and CloudFront only) 397 Amazon CloudFront Developer Guide import into ACM, or upload to the IAM certificate store for HTTPS communication between viewers and CloudFront. For more information, see Increase the quotas for SSL/TLS certificates. Maximum number of certificates per CloudFront distribution You can associate a maximum of one SSL/TLS certificate with each CloudFront distribution. Maximum number of certificates that you can import into ACM or upload to the IAM certificate store If you obtained your SSL/TLS certificates from a third-party CA, you must store the certificates in one of the following locations: • AWS
AmazonCloudFront_DevGuide-154
AmazonCloudFront_DevGuide.pdf
154
with CloudFront (HTTPS between viewers and CloudFront only) 397 Amazon CloudFront Developer Guide import into ACM, or upload to the IAM certificate store for HTTPS communication between viewers and CloudFront. For more information, see Increase the quotas for SSL/TLS certificates. Maximum number of certificates per CloudFront distribution You can associate a maximum of one SSL/TLS certificate with each CloudFront distribution. Maximum number of certificates that you can import into ACM or upload to the IAM certificate store If you obtained your SSL/TLS certificates from a third-party CA, you must store the certificates in one of the following locations: • AWS Certificate Manager – For the current quota on the number of ACM certificates, see Quotas in the AWS Certificate Manager User Guide. The listed quota is a total that includes certificates that you provision by using ACM and certificates that you import into ACM. • IAM certificate store – For the current quota (formerly known as limit) on the number of certificates that you can upload to the IAM certificate store for an AWS account, see IAM and STS Limits in the IAM User Guide. You can request a higher quota in the Service Quotas console. Maximum number of certificates per AWS account (dedicated IP addresses only) If you want to serve HTTPS requests by using dedicated IP addresses, note the following: • By default, CloudFront gives you permission to use two certificates with your AWS account, one for everyday use and one for when you need to rotate certificates for multiple distributions. • If you need more than two custom SSL/TLS certificates for your AWS account, you can request a higher quota in the Service Quotas console. Use the same certificate for CloudFront distributions that were created by using different AWS accounts If you're using a third-party CA and you want to use the same certificate with multiple CloudFront distributions that were created by using different AWS accounts, you must import the certificate into ACM or upload it to the IAM certificate store once for each AWS account. If you're using certificates provided by ACM, you can't configure CloudFront to use certificates that were created by a different AWS account. Quotas on using SSL/TLS certificates with CloudFront (HTTPS between viewers and CloudFront only) 398 Amazon CloudFront Developer Guide Use the same certificate for CloudFront and for other AWS services If you bought a certificate from a trusted certificate authority such as Comodo, DigiCert, or Symantec, you can use the same certificate for CloudFront and for other AWS services. If you're importing the certificate into ACM, you need to import it only once to use it for multiple AWS services. If you're using certificates provided by ACM, the certificates are stored in ACM. Use the same certificate for multiple CloudFront distributions You can use the same certificate for any or all of the CloudFront distributions that you're using to serve HTTPS requests. Note the following: • You can use the same certificate both for serving requests using dedicated IP addresses and for serving requests using SNI. • You can associate only one certificate with each distribution. • Each distribution must include one or more alternate domain names that also appear in the Common Name field or the Subject Alternative Names field in the certificate. • If you're serving HTTPS requests using dedicated IP addresses and you created all of your distributions by using the same AWS account, you can significantly reduce your cost by using the same certificate for all distributions. CloudFront charges for each certificate, not for each distribution. For example, suppose you create three distributions by using the same AWS account, and you use the same certificate for all three distributions. You would be charged only one fee for using dedicated IP addresses. However, if you're serving HTTPS requests using dedicated IP addresses and using the same certificate to create CloudFront distributions in different AWS accounts, each account is charged the fee for using dedicated IP addresses. For example, if you create three distributions by using three different AWS accounts and you use the same certificate for all three distributions, each account is charged the full fee for using dedicated IP addresses. Configure alternate domain names and HTTPS To use alternate domain names in the URLs for your files and to use HTTPS between viewers and CloudFront, perform the applicable procedures. Topics Configure alternate domain names and HTTPS 399 Amazon CloudFront • Get an SSL/TLS certificate • Import an SSL/TLS certificate • Update your CloudFront distribution Get an SSL/TLS certificate Developer Guide Get an SSL/TLS certificate if you don’t already have one. For more information, see the applicable documentation: • To use a certificate provided by AWS Certificate Manager (ACM), see the AWS Certificate Manager User Guide. Then skip to Update your CloudFront distribution. Note We recommend that
AmazonCloudFront_DevGuide-155
AmazonCloudFront_DevGuide.pdf
155
To use alternate domain names in the URLs for your files and to use HTTPS between viewers and CloudFront, perform the applicable procedures. Topics Configure alternate domain names and HTTPS 399 Amazon CloudFront • Get an SSL/TLS certificate • Import an SSL/TLS certificate • Update your CloudFront distribution Get an SSL/TLS certificate Developer Guide Get an SSL/TLS certificate if you don’t already have one. For more information, see the applicable documentation: • To use a certificate provided by AWS Certificate Manager (ACM), see the AWS Certificate Manager User Guide. Then skip to Update your CloudFront distribution. Note We recommend that you use ACM to provision, manage, and deploy SSL/TLS certificates on AWS managed resources. You must request an ACM certificate in the US East (N. Virginia) Region. • To get a certificate from a third-party certificate authority (CA), see the documentation provided by the certificate authority. When you have the certificate, continue with the next procedure. Import an SSL/TLS certificate If you got your certificate from a third-party CA, import the certificate into ACM or upload it to the IAM certificate store: ACM (recommended) ACM lets you import third-party certificates from the ACM console, as well as programmatically. For information about importing a certificate to ACM, see Importing Certificates into AWS Certificate Manager in the AWS Certificate Manager User Guide. You must import the certificate in the US East (N. Virginia) Region. IAM certificate store (Not recommended) Use the following AWS CLI command to upload your third-party certificate to the IAM certificate store. aws iam upload-server-certificate \ Configure alternate domain names and HTTPS 400 Amazon CloudFront Developer Guide --server-certificate-name CertificateName \ --certificate-body file://public_key_certificate_file \ --private-key file://privatekey.pem \ --certificate-chain file://certificate_chain_file \ --path /cloudfront/path/ Note the following: • AWS account – You must upload the certificate to the IAM certificate store using the same AWS account that you used to create your CloudFront distribution. • --path parameter – When you upload the certificate to IAM, the value of the --path parameter (certificate path) must start with /cloudfront/, for example, /cloudfront/ production/ or /cloudfront/test/. The path must end with a /. • Existing certificates – You must specify values for the --server-certificate-name and --path parameters that are different from the values that are associated with existing certificates. • Using the CloudFront console – The value that you specify for the --server- certificate-name parameter in the AWS CLI, for example, myServerCertificate, appears in the SSL Certificate list in the CloudFront console. • Using the CloudFront API – Make note of the alphanumeric string that the AWS CLI returns, for example, AS1A2M3P4L5E67SIIXR3J. This is the value that you will specify in the IAMCertificateId element. You don't need the IAM ARN, which is also returned by the CLI. For more information about the AWS CLI, see the AWS Command Line Interface User Guide and the AWS CLI Command Reference. Update your CloudFront distribution To update settings for your distribution, perform the following procedure: To configure your CloudFront distribution for alternate domain names 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Choose the ID for the distribution that you want to update. 3. On the General tab, choose Edit. 4. Update the following values: Configure alternate domain names and HTTPS 401 Amazon CloudFront Developer Guide Alternate domain name (CNAME) Choose Add item to add the applicable alternate domain names. Separate domain names with commas, or type each domain name on a new line. Custom SSL certificate Select a certificate from the dropdown list. Up to 100 certificates are listed here. If you have more than 100 certificates and you don't see the certificate that you want to add, you can type a certificate ARN in the field to choose it. If you uploaded a certificate to the IAM certificate store but it's not listed, and you can't choose it by typing the name in the field, review the procedure Import an SSL/TLS certificate to confirm that you correctly uploaded the certificate. Important After you associate your SSL/TLS certificate with your CloudFront distribution, do not delete the certificate from ACM or the IAM certificate store until you remove the certificate from all distributions and all the distributions are deployed. 5. Choose Save changes. 6. Configure CloudFront to require HTTPS between viewers and CloudFront: a. On the Behaviors tab, choose the cache behavior that you want to update, and choose Edit. b. Specify one of the following values for Viewer Protocol Policy: Redirect HTTP to HTTPS Viewers can use both protocols, but HTTP requests are automatically redirected to HTTPS requests. CloudFront returns HTTP status code 301 (Moved Permanently) along with the new HTTPS URL. The viewer then resubmits the request to CloudFront using the HTTPS URL. Configure alternate domain names and HTTPS 402 Amazon CloudFront Developer Guide Important CloudFront doesn't
AmazonCloudFront_DevGuide-156
AmazonCloudFront_DevGuide.pdf
156
5. Choose Save changes. 6. Configure CloudFront to require HTTPS between viewers and CloudFront: a. On the Behaviors tab, choose the cache behavior that you want to update, and choose Edit. b. Specify one of the following values for Viewer Protocol Policy: Redirect HTTP to HTTPS Viewers can use both protocols, but HTTP requests are automatically redirected to HTTPS requests. CloudFront returns HTTP status code 301 (Moved Permanently) along with the new HTTPS URL. The viewer then resubmits the request to CloudFront using the HTTPS URL. Configure alternate domain names and HTTPS 402 Amazon CloudFront Developer Guide Important CloudFront doesn't redirect DELETE, OPTIONS, PATCH, POST, or PUT requests from HTTP to HTTPS. If you configure a cache behavior to redirect to HTTPS, CloudFront responds to HTTP DELETE, OPTIONS, PATCH, POST, or PUT requests for that cache behavior with HTTP status code 403 (Forbidden). When a viewer makes an HTTP request that is redirected to an HTTPS request, CloudFront charges for both requests. For the HTTP request, the charge is only for the request and for the headers that CloudFront returns to the viewer. For the HTTPS request, the charge is for the request, and for the headers and the file returned by your origin. HTTPS Only Viewers can access your content only if they're using HTTPS. If a viewer sends an HTTP request instead of an HTTPS request, CloudFront returns HTTP status code 403 (Forbidden) and does not return the file. c. Choose Yes, Edit. d. Repeat steps a through c for each additional cache behavior that you want to require HTTPS for between viewers and CloudFront. 7. Confirm the following before you use the updated configuration in a production environment: • The path pattern in each cache behavior applies only to the requests that you want viewers to use HTTPS for. • The cache behaviors are listed in the order that you want CloudFront to evaluate them in. For more information, see Path pattern. • The cache behaviors are routing requests to the correct origins. Determine the size of the public key in an SSL/TLS RSA certificate When you’re using CloudFront alternate domain names and HTTPS, the maximum size of the public key in an SSL/TLS RSA certificate is 4096 bits. (This is the key size, not the number of characters in the public key.) If you use AWS Certificate Manager for your certificates, although ACM supports larger RSA keys, you cannot use the larger keys with CloudFront. Determine the size of the public key in an SSL/TLS RSA certificate 403 Amazon CloudFront Developer Guide You can determine the size of the RSA public key by running the following OpenSSL command: openssl x509 -in path and filename of SSL/TLS certificate -text -noout Where: • -in specifies the path and file name of your SSL/TLS RSA certificate. • -text causes OpenSSL to display the length of the RSA public key in bits. • -noout prevents OpenSSL from displaying the public key. Example output: Public-Key: (2048 bit) Increase the quotas for SSL/TLS certificates There are quotas on the number of SSL/TLS certificates that you can import into AWS Certificate Manager (ACM) or upload to AWS Identity and Access Management (IAM). There also is a quota on the number of SSL/TLS certificates that you can use with an AWS account when you configure CloudFront to serve HTTPS requests by using dedicated IP addresses. However, you can request higher quotas. Topics • Increase quota on certificates imported into ACM • Increase quota on certificates uploaded to IAM • Increase quota on certificates used with dedicated IP addresses Increase quota on certificates imported into ACM For the quota on the number of certificates that you can import into ACM, see Quotas in the AWS Certificate Manager User Guide. To request a higher quota, use the Service Quotas console. For more information, see Requesting a quota increase in the Service Quotas User Guide. Increase the quotas for SSL/TLS certificates 404 Amazon CloudFront Developer Guide Increase quota on certificates uploaded to IAM For the quota (formerly known as limit) on the number of certificates that you can upload to IAM, see IAM and STS Limits in the IAM User Guide. To request a higher quota, use the Service Quotas console. For more information, see Requesting a quota increase in the Service Quotas User Guide. Increase quota on certificates used with dedicated IP addresses For the quota on the number of SSL certificates that you can use for each AWS account when serving HTTPS requests using dedicated IP addresses, see Quotas on SSL certificates. To request a higher quota, use the Service Quotas console. For more information, see Requesting a quota increase in the Service Quotas User Guide. Rotate SSL/TLS certificates When your SSL/TLS certificates are near expiration, you need to rotate them to ensure the security
AmazonCloudFront_DevGuide-157
AmazonCloudFront_DevGuide.pdf
157
the Service Quotas console. For more information, see Requesting a quota increase in the Service Quotas User Guide. Increase quota on certificates used with dedicated IP addresses For the quota on the number of SSL certificates that you can use for each AWS account when serving HTTPS requests using dedicated IP addresses, see Quotas on SSL certificates. To request a higher quota, use the Service Quotas console. For more information, see Requesting a quota increase in the Service Quotas User Guide. Rotate SSL/TLS certificates When your SSL/TLS certificates are near expiration, you need to rotate them to ensure the security for your distribution and avoid service disruption for your viewers. You can rotate them in the following ways: • For SSL/TLS certificates provided by AWS Certificate Manager (ACM), you don't need to rotate them. ACM automatically manages certificate renewals for you. For more information, see Managed certificate renewal in the AWS Certificate Manager User Guide. • If you're using a third-party certificate authority and you imported the certificates into ACM (recommended) or uploaded them to the IAM certificate store, you must occasionally replace one certificate with another. Important • ACM doesn't manage certificate renewals for certificates that you acquire from third- party certificate authorities and import into ACM. • If you configured CloudFront to serve HTTPS requests by using dedicated IP addresses, you might incur an additional, pro-rated charge for using one or more additional certificates while you're rotating certificates. We recommend that you update your distributions to minimize the additional charge. Rotate SSL/TLS certificates 405 Amazon CloudFront Developer Guide Rotate SSL/TLS certificates To rotate your certificates, perform the following procedure. Viewers can continue to access your content while you rotate certificates as well as after the process is complete. To rotate SSL/TLS certificates 1. Increase the quotas for SSL/TLS certificates to determine whether you need permission to use more SSL certificates. If so, request permission and wait until permission is granted before you continue with step 2. 2. Import the new certificate into ACM or upload it to IAM. For more information, see Importing an SSL/TLS Certificate in the Amazon CloudFront Developer Guide. 3. (For IAM certificates only) Update your distributions one at a time to use the new certificate. For more information, see Update a distribution. 4. (Optional) Delete the previous certificate from ACM or IAM. Important Don't delete an SSL/TLS certificate until you remove it from all distributions and until the status of the distributions that you have updated has changed to Deployed. Revert from a custom SSL/TLS certificate to the default CloudFront certificate If you configured CloudFront to use HTTPS between viewers and CloudFront, and you configured CloudFront to use a custom SSL/TLS certificate, you can change your configuration to use the default CloudFront SSL/TLS certificate. The process depends on whether you've used your distribution to distribute your content: • If you have not used your distribution to distribute your content, you can just change the configuration. For more information, see Update a distribution. • If you have used your distribution to distribute your content, you must create a new CloudFront distribution and change the URLs for your files to reduce or eliminate the amount of time that your content is unavailable. To do that, perform the following procedure. Revert from a custom SSL/TLS certificate to the default CloudFront certificate 406 Amazon CloudFront Developer Guide Revert to default CloudFront certificate The following procedure shows you how to revert from a custom SSL/TLS certificate to the default CloudFront certificate. To revert to the default CloudFront certificate 1. Create a new CloudFront distribution with the desired configuration. For SSL Certificate, choose Default CloudFront Certificate (*.cloudfront.net). For more information, see Create a distribution. 2. For files that you're distributing using CloudFront, update the URLs in your application to use the domain name that CloudFront assigned to the new distribution. For example, change https://www.example.com/images/logo.png to https:// d111111abcdef8.cloudfront.net/images/logo.png. 3. Either delete the distribution that is associated with a custom SSL/TLS certificate, or update the distribution to change the value of SSL Certificate to Default CloudFront Certificate (*.cloudfront.net). For more information, see Update a distribution. Important Until you complete this step, AWS continues to charge you for using a custom SSL/TLS certificate. 4. (Optional) Delete your custom SSL/TLS certificate. a. Run the AWS CLI command list-server-certificates to get the certificate ID of the certificate that you want to delete. For more information, see list-server-certificates in the AWS CLI Command Reference. b. Run the AWS CLI command delete-server-certificate to delete the certificate. For more information, see delete-server-certificate in the AWS CLI Command Reference. Revert from a custom SSL/TLS certificate to the default CloudFront certificate 407 Amazon CloudFront Developer Guide Switch from a custom SSL/TLS certificate with dedicated IP addresses to SNI If you configured CloudFront to use a custom SSL/TLS certificate with dedicated
AmazonCloudFront_DevGuide-158
AmazonCloudFront_DevGuide.pdf
158
4. (Optional) Delete your custom SSL/TLS certificate. a. Run the AWS CLI command list-server-certificates to get the certificate ID of the certificate that you want to delete. For more information, see list-server-certificates in the AWS CLI Command Reference. b. Run the AWS CLI command delete-server-certificate to delete the certificate. For more information, see delete-server-certificate in the AWS CLI Command Reference. Revert from a custom SSL/TLS certificate to the default CloudFront certificate 407 Amazon CloudFront Developer Guide Switch from a custom SSL/TLS certificate with dedicated IP addresses to SNI If you configured CloudFront to use a custom SSL/TLS certificate with dedicated IP addresses, you can switch to using a custom SSL/TLS certificate with SNI instead and eliminate the charge that is associated with dedicated IP addresses. Important This update to your CloudFront configuration has no effect on viewers that support SNI. Viewers can access your content before and after the change, as well as while the change is propagating to CloudFront edge locations. Viewers that don't support SNI can't access your content after the change. For more information, see Choose how CloudFront serves HTTPS requests. Switch from a custom certificate to SNI The following procedure shows you how to switch from a custom SSL/TLS certificate with dedicated IP addresses to SNI. To switch from a custom SSL/TLS certificate with dedicated IP addresses to SNI 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Choose the ID of the distribution that you want to view or update. 3. Choose Distribution Settings. 4. On the General tab, choose Edit. 5. Under Custom SSL certification – optional, deselect Legacy clients support. 6. Choose Yes, Edit. Serve private content with signed URLs and signed cookies Many companies that distribute content over the internet want to restrict access to documents, business data, media streams, or content that is intended for selected users, for example, users Switch from a custom SSL/TLS certificate with dedicated IP addresses to SNI 408 Amazon CloudFront Developer Guide who have paid a fee. To securely serve this private content by using CloudFront, you can do the following: • Require that your users access your private content by using special CloudFront signed URLs or signed cookies. • Require that your users access your content by using CloudFront URLs, not URLs that access content directly on the origin server (for example, Amazon S3 or a private HTTP server). Requiring CloudFront URLs isn't necessary, but we recommend it to prevent users from bypassing the restrictions that you specify in signed URLs or signed cookies. For more information, see Restrict access to files. How to serve private content To configure CloudFront to serve private content, do the following tasks: 1. (Optional but recommended) Require your users to access your content only through CloudFront. The method that you use depends on whether you're using Amazon S3 or custom origins: • Amazon S3 – See the section called “Restrict access to an Amazon S3 origin”. • Custom origin – See Restrict access to files on custom origins. Custom origins include Amazon EC2, Amazon S3 buckets configured as website endpoints, Elastic Load Balancing, and your own HTTP web servers. 2. Specify the trusted key groups or trusted signers that you want to use to create signed URLs or signed cookies. We recommend that you use trusted key groups. For more information, see Specify signers that can create signed URLs and signed cookies. 3. Write your application to respond to requests from authorized users either with signed URLs or with Set-Cookie headers that set signed cookies. Follow the steps in one of the following topics: • Use signed URLs • Use signed cookies If you're not sure which method to use, see Decide to use signed URLs or signed cookies. How to serve private content 409 Developer Guide Amazon CloudFront Topics • Restrict access to files • Specify signers that can create signed URLs and signed cookies • Decide to use signed URLs or signed cookies • Use signed URLs • Use signed cookies • Linux commands and OpenSSL for base64 encoding and encryption • Code examples for creating a signature for a signed URL Restrict access to files You can control user access to your private content in two ways: • Restrict access to files in CloudFront caches. • Restrict access to files in your origin by doing one of the following: • Set up an origin access control (OAC) for your Amazon S3 bucket. • Configure custom headers for a private HTTP server (a custom origin). Restrict access to files in CloudFront caches You can configure CloudFront to require that users access your files using either signed URLs or signed cookies. You then develop your application either to create and distribute signed URLs to authenticated users or to send Set-Cookie
AmazonCloudFront_DevGuide-159
AmazonCloudFront_DevGuide.pdf
159
user access to your private content in two ways: • Restrict access to files in CloudFront caches. • Restrict access to files in your origin by doing one of the following: • Set up an origin access control (OAC) for your Amazon S3 bucket. • Configure custom headers for a private HTTP server (a custom origin). Restrict access to files in CloudFront caches You can configure CloudFront to require that users access your files using either signed URLs or signed cookies. You then develop your application either to create and distribute signed URLs to authenticated users or to send Set-Cookie headers that set signed cookies for authenticated users. (To give a few users long-term access to a small number of files, you can also create signed URLs manually.) When you create signed URLs or signed cookies to control access to your files, you can specify the following restrictions: • An ending date and time, after which the URL is no longer valid. • (Optional) The date and time that the URL becomes valid. • (Optional) The IP address or range of addresses of the computers that can be used to access your content. Restrict access to files 410 Amazon CloudFront Developer Guide One part of a signed URL or a signed cookie is hashed and signed using the private key from a public–private key pair. When someone uses a signed URL or signed cookie to access a file, CloudFront compares the signed and unsigned portions of the URL or cookie. If they don't match, CloudFront doesn't serve the file. You must use RSA-SHA1 for signing URLs or cookies. CloudFront doesn't accept other algorithms. Restrict access to files in Amazon S3 buckets You can optionally secure the content in your Amazon S3 bucket so that users can access it through the specified CloudFront distribution but cannot access it directly by using Amazon S3 URLs. This prevents someone from bypassing CloudFront and using the Amazon S3 URL to get content that you want to restrict access to. This step isn't required to use signed URLs, but we recommend it. To require that users access your content through CloudFront URLs, you do the following tasks: • Give a CloudFront origin access control permission to read the files in the S3 bucket. • Create the origin access control and associate it with your CloudFront distribution. • Remove permission for anyone else to use Amazon S3 URLs to read the files. For more information, see the section called “Restrict access to an Amazon S3 origin”. Restrict access to files on custom origins If you use a custom origin, you can optionally set up custom headers to restrict access. For CloudFront to get your files from a custom origin, the files must be accessible by CloudFront using a standard HTTP (or HTTPS) request. But by using custom headers, you can further restrict access to your content so that users can access it only through CloudFront, not directly. This step isn't required to use signed URLs, but we recommend it. To require that users access content through CloudFront, change the following settings in your CloudFront distributions: Origin Custom Headers Configure CloudFront to forward custom headers to your origin. See Configure CloudFront to add custom headers to origin requests. Restrict access to files 411 Amazon CloudFront Viewer Protocol Policy Developer Guide Configure your distribution to require viewers to use HTTPS to access CloudFront. See Viewer protocol policy. Origin Protocol Policy Configure your distribution to require CloudFront to use the same protocol as viewers to forward requests to the origin. See Protocol (custom origins only). After you've made these changes, update your application on your custom origin to only accept requests that include the custom headers that you’ve configured CloudFront to send. The combination of Viewer Protocol Policy and Origin Protocol Policy ensure that the custom headers are encrypted in transit. However, we recommend that you periodically do the following to rotate the custom headers that CloudFront forwards to your origin: 1. Update your CloudFront distribution to begin forwarding a new header to your custom origin. 2. Update your application to accept the new header as confirmation that the request is coming from CloudFront. 3. When requests no longer include the header that you're replacing, update your application to no longer accept the old header as confirmation that the request is coming from CloudFront. Specify signers that can create signed URLs and signed cookies Topics • Choose between trusted key groups (recommended) and AWS accounts • Create key pairs for your signers • Reformat the private key (.NET and Java only) • Add a signer to a distribution • Rotating key pairs To create signed URLs or signed cookies, you need a signer. A signer is either a trusted key group that you create in CloudFront, or an AWS
AmazonCloudFront_DevGuide-160
AmazonCloudFront_DevGuide.pdf
160
include the header that you're replacing, update your application to no longer accept the old header as confirmation that the request is coming from CloudFront. Specify signers that can create signed URLs and signed cookies Topics • Choose between trusted key groups (recommended) and AWS accounts • Create key pairs for your signers • Reformat the private key (.NET and Java only) • Add a signer to a distribution • Rotating key pairs To create signed URLs or signed cookies, you need a signer. A signer is either a trusted key group that you create in CloudFront, or an AWS account that contains a CloudFront key pair. We recommend that you use trusted key groups with signed URLs and signed cookies. For more information, see Choose between trusted key groups (recommended) and AWS accounts. Specify trusted signers 412 Amazon CloudFront The signer has two purposes: Developer Guide • As soon as you add the signer to your distribution, CloudFront starts to require that viewers use signed URLs or signed cookies to access your files. • When you create signed URLs or signed cookies, you use the private key from the signer’s key pair to sign a portion of the URL or the cookie. When someone requests a restricted file, CloudFront compares the signature in the URL or cookie with the unsigned URL or cookie, to verify that it hasn’t been tampered with. CloudFront also verifies that the URL or cookie is valid, meaning, for example, that the expiration date and time hasn’t passed. When you specify a signer, you also indirectly specify the files that require signed URLs or signed cookies by adding the signer to a cache behavior. If your distribution has only one cache behavior, viewers must use signed URLs or signed cookies to access any file in the distribution. If you create multiple cache behaviors and add signers to some cache behaviors and not to others, you can require that viewers use signed URLs or signed cookies to access some files and not others. To specify the signers (the private keys) that are allowed to create signed URLs or signed cookies, and to add the signers to your CloudFront distribution, do the following tasks: 1. Decide whether to use a trusted key group or an AWS account as the signer. We recommend using a trusted key group. For more information, see Choose between trusted key groups (recommended) and AWS accounts. 2. For the signer that you chose in step 1, create a public–private key pair. For more information, see Create key pairs for your signers. 3. If you’re using .NET or Java to create signed URLs or signed cookies, reformat the private key. For more information, see Reformat the private key (.NET and Java only). 4. In the distribution for which you’re creating signed URLs or signed cookies, specify the signer. For more information, see Add a signer to a distribution. Choose between trusted key groups (recommended) and AWS accounts To use signed URLs or signed cookies, you need a signer. A signer is either a trusted key group that you create in CloudFront, or an AWS account that contains a CloudFront key pair. We recommend that you use trusted key groups, for the following reasons: Specify trusted signers 413 Amazon CloudFront Developer Guide • With CloudFront key groups, you don’t need to use the AWS account root user to manage the public keys for CloudFront signed URLs and signed cookies. AWS best practices recommend that you don’t use the root user when you don’t have to. • With CloudFront key groups, you can manage public keys, key groups, and trusted signers using the CloudFront API. You can use the API to automate key creation and key rotation. When you use the AWS root user, you have to use the AWS Management Console to manage CloudFront key pairs, so you can’t automate the process. • Because you can manage key groups with the CloudFront API, you can also use AWS Identity and Access Management (IAM) permissions policies to limit what different users are allowed to do. For example, you can allow users to upload public keys, but not delete them. Or you can allow users to delete public keys, but only when certain conditions are met, such as using multi-factor authentication, sending the request from a particular network, or sending the request within a particular date and time range. • With CloudFront key groups, you can associate a higher number of public keys with your CloudFront distribution, giving you more flexibility in how you use and manage the public keys. By default, you can associate up to four key groups with a single distribution, and you can have up to five public keys in a key group. When you use the AWS account root user to manage
AmazonCloudFront_DevGuide-161
AmazonCloudFront_DevGuide.pdf
161
public keys, but only when certain conditions are met, such as using multi-factor authentication, sending the request from a particular network, or sending the request within a particular date and time range. • With CloudFront key groups, you can associate a higher number of public keys with your CloudFront distribution, giving you more flexibility in how you use and manage the public keys. By default, you can associate up to four key groups with a single distribution, and you can have up to five public keys in a key group. When you use the AWS account root user to manage CloudFront key pairs, you can only have up to two active CloudFront key pairs per AWS account. Create key pairs for your signers Each signer that you use to create CloudFront signed URLs or signed cookies must have a public– private key pair. The signer uses its private key to sign the URL or cookies, and CloudFront uses the public key to verify the signature. The way that you create a key pair depends on whether you use a trusted key group as the signer (recommended), or a CloudFront key pair. For more information, see the following sections. The key pair that you create must meet the following requirements: • It must be an SSH-2 RSA key pair. • It must be in base64-encoded PEM format. • It must be a 2048-bit key pair. Specify trusted signers 414 Amazon CloudFront Developer Guide To help secure your applications, we recommend that you rotate key pairs periodically. For more information, see Rotating key pairs. Create a key pair for a trusted key group (recommended) To create a key pair for a trusted key group, perform the following steps: 1. Create the public–private key pair. 2. Upload the public key to CloudFront. 3. Add the public key to a CloudFront key group. For more information, see the following procedures. To create a key pair Note The following steps use OpenSSL as an example of one way to create a key pair. There are many other ways to create an RSA key pair. 1. The following example command uses OpenSSL to generate an RSA key pair with a length of 2048 bits and save to the file named private_key.pem. openssl genrsa -out private_key.pem 2048 2. The resulting file contains both the public and the private key. The following example command extracts the public key from the file named private_key.pem. openssl rsa -pubout -in private_key.pem -out public_key.pem You upload the public key (in the public_key.pem file) later, in the following procedure. To upload the public key to CloudFront 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. Specify trusted signers 415 Amazon CloudFront Developer Guide 2. In the navigation menu, choose Public keys. 3. Choose Create public key. 4. In the Create public key window, do the following: a. b. For Key name, type a name to identify the public key. For Key value, paste the public key. If you followed the steps in the preceding procedure, the public key is in the file named public_key.pem. To copy and paste the contents of the public key, you can: • Use the cat command on the macOS or Linux command line, like this: cat public_key.pem Copy the output of that command, then paste it into the Key value field. • Open the public_key.pem file with a plaintext editor like Notepad (on Windows) or TextEdit (on macOS). Copy the contents of the file, then paste it into the Key value field. c. (Optional) For Comment, add a comment to describe the public key. When finished, choose Add. 5. Record the public key ID. You use it later when you create signed URLs or signed cookies, as the value of the Key-Pair-Id field. To add the public key to a key group 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation menu, choose Key groups. 3. Choose Add key group. 4. On the Create key group page, do the following: a. b. c. For Key group name, type a name to identify the key group. (Optional) For Comment, type a comment to describe the key group. For Public keys, select the public key to add to the key group, then choose Add. Repeat this step for each public key that you want to add to the key group. Specify trusted signers 416 Amazon CloudFront 5. Choose Create key group. Developer Guide 6. Record the key group name. You use it later to associate the key group with a cache behavior in a CloudFront distribution. (In the CloudFront API, you use the key group ID to associate the key group with a cache behavior.) Create a CloudFront key pair (not recommended, requires the AWS account root user) Important We recommend
AmazonCloudFront_DevGuide-162
AmazonCloudFront_DevGuide.pdf
162
select the public key to add to the key group, then choose Add. Repeat this step for each public key that you want to add to the key group. Specify trusted signers 416 Amazon CloudFront 5. Choose Create key group. Developer Guide 6. Record the key group name. You use it later to associate the key group with a cache behavior in a CloudFront distribution. (In the CloudFront API, you use the key group ID to associate the key group with a cache behavior.) Create a CloudFront key pair (not recommended, requires the AWS account root user) Important We recommend that you create a public key for a trusted key group instead of following these steps. For the recommended way to create public keys for signed URLs and signed cookies, see Create a key pair for a trusted key group (recommended). You can create a CloudFront key pair in the following ways: • Create a key pair in the AWS Management Console and download the private key. See the following procedure. • Create an RSA key pair by using an application such as OpenSSL, and then upload the public key to the AWS Management Console. For more information about creating an RSA key pair, see Create a key pair for a trusted key group (recommended). To create CloudFront key pairs in the AWS Management Console 1. Sign in to the AWS Management Console using the credentials of the AWS account root user. Important IAM users can’t create CloudFront key pairs. You must sign in using root user credentials to create key pairs. 2. Choose your account name, then choose My Security Credentials. 3. Choose CloudFront key pairs. 4. Confirm that you have no more than one active key pair. You can’t create a key pair if you already have two active key pairs. 5. Choose Create New Key Pair. Specify trusted signers 417 Amazon CloudFront Note Developer Guide You can also choose to create your own key pair and upload the public key. CloudFront key pairs support 1024, 2048, or 4096-bit keys. 6. In the Create Key Pair dialog box, choose Download Private Key File, and then save the file on your computer. Important Save the private key for your CloudFront key pair in a secure location, and set permissions on the file so that only the desired administrators can read it. If someone gets your private key, they can generate valid signed URLs and signed cookies and download your content. You cannot get the private key again, so if you lose or delete it, you must create a new CloudFront key pair. 7. Record the key pair ID for your key pair. (In the AWS Management Console, this is called the Access Key ID.) You’ll use it when you create signed URLs or signed cookies. Reformat the private key (.NET and Java only) If you’re using .NET or Java to create signed URLs or signed cookies, you cannot use the private key from your key pair in the default PEM format to create the signature. Instead, do the following: • .NET framework – Convert the private key to the XML format that the .NET framework uses. Several tools are available. • Java – Convert the private key to DER format. One way to do this is with the following OpenSSL command. In the following command, private_key.pem is the name of the file that contains the PEM-formatted private key, and private_key.der is the name of the file that contains the DER-formatted private key after you run the command. openssl pkcs8 -topk8 -nocrypt -in private_key.pem -inform PEM -out private_key.der - outform DER To ensure that the encoder works correctly, add the JAR for the Bouncy Castle Java cryptography APIs to your project and then add the Bouncy Castle provider. Specify trusted signers 418 Amazon CloudFront Developer Guide Add a signer to a distribution A signer is the trusted key group (recommended) or CloudFront key pair that can create signed URLs and signed cookies for a distribution. To use signed URLs or signed cookies with a CloudFront distribution, you must specify a signer. Signers are associated with cache behaviors. This allows you to require signed URLs or signed cookies for some files and not for others in the same distribution. A distribution requires signed URLs or cookies only for files that are associated with the corresponding cache behaviors. Similarly, a signer can only sign URLs or cookies for files that are associated with the corresponding cache behaviors. For example, if you have one signer for one cache behavior and a different signer for a different cache behavior, neither signer can create signed URLs or cookies for files that are associated with the other cache behavior. Important Before you add a signer to your distribution, do the following: • Define the path patterns
AmazonCloudFront_DevGuide-163
AmazonCloudFront_DevGuide.pdf
163
and not for others in the same distribution. A distribution requires signed URLs or cookies only for files that are associated with the corresponding cache behaviors. Similarly, a signer can only sign URLs or cookies for files that are associated with the corresponding cache behaviors. For example, if you have one signer for one cache behavior and a different signer for a different cache behavior, neither signer can create signed URLs or cookies for files that are associated with the other cache behavior. Important Before you add a signer to your distribution, do the following: • Define the path patterns in cache behaviors and the sequence of cache behaviors carefully so you don’t give users unintended access to your content or prevent them from accessing content that you want to be available to everyone. For example, suppose a request matches the path pattern for two cache behaviors. The first cache behavior does not require signed URLs or signed cookies and the second cache behavior does. Users will be able to access the files without using signed URLs or signed cookies because CloudFront processes the cache behavior that is associated with the first match. For more information about path patterns, see Path pattern. • For a distribution that you’re already using to distribute content, make sure you’re ready to start generating signed URLs and signed cookies before you add a signer. When you add a signer, CloudFront rejects requests that don’t include a valid signed URL or signed cookie. You can add signers to your distribution using either the CloudFront console or the CloudFront API. Specify trusted signers 419 Amazon CloudFront Console Developer Guide The following steps show how to add a trusted key group as a signer. You can also add an AWS account as a trusted signer, but it’s not recommended. To add a signer to a distribution using the console 1. Record the key group ID of the key group that you want to use as a trusted signer. For more information, see Create a key pair for a trusted key group (recommended). 2. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 3. Choose the distribution whose files you want to protect with signed URLs or signed cookies. Note To add a signer to a new distribution, you specify the same settings that are described in step 6 when you create the distribution. 4. Choose the Behaviors tab. 5. Select the cache behavior whose path pattern matches the files that you want to protect with signed URLs or signed cookies, and then choose Edit. 6. On the Edit Behavior page, do the following: a. b. c. For Restrict Viewer Access (Use Signed URLs or Signed Cookies), choose Yes. For Trusted Key Groups or Trusted Signer, choose Trusted Key Groups. For Trusted Key Groups, choose the key group to add, and then choose Add. Repeat if you want to add more than one key group. 7. Choose Yes, Edit to update the cache behavior. API You can use the CloudFront API to add a trusted key group as a signer. You can add a signer to an existing distribution or to a new distribution. In either case, specify the values in the TrustedKeyGroups element. You can also add an AWS account as a trusted signer, but it’s not recommended. See the following topics in the Amazon CloudFront API Reference: Specify trusted signers 420 Amazon CloudFront Developer Guide • Update an existing distribution – UpdateDistribution • Create a new distribution – CreateDistribution Rotating key pairs We recommend that you periodically rotate (change) your key pairs for signed URLs and signed cookies. To rotate key pairs that you’re using to create signed URLs or signed cookies without invalidating URLs or cookies that haven’t expired yet, do the following tasks: 1. Create a new key pair, and add the public key to a key group. For more information, see Create a key pair for a trusted key group (recommended). 2. If you created a new key group in the previous step, add the key group to the distribution as a signer. Important Don’t remove any existing public keys from the key group, or any key groups from the distribution yet. Only add the new ones. 3. Update your application to create signatures using the private key from the new key pair. Confirm that the signed URLs or cookies that are signed with the new private keys are working. 4. Wait until the expiration date has passed in URLs or cookies that were signed using the previous private key. Then remove the old public key from the key group. If you created a new key group in step 2, remove the old key group from your distribution. Decide to use signed URLs or signed cookies CloudFront signed URLs and signed cookies provide the same basic
AmazonCloudFront_DevGuide-164
AmazonCloudFront_DevGuide.pdf
164
ones. 3. Update your application to create signatures using the private key from the new key pair. Confirm that the signed URLs or cookies that are signed with the new private keys are working. 4. Wait until the expiration date has passed in URLs or cookies that were signed using the previous private key. Then remove the old public key from the key group. If you created a new key group in step 2, remove the old key group from your distribution. Decide to use signed URLs or signed cookies CloudFront signed URLs and signed cookies provide the same basic functionality: they allow you to control who can access your content. If you want to serve private content through CloudFront and you're trying to decide whether to use signed URLs or signed cookies, consider the following. Use signed URLs in the following cases: • You want to restrict access to individual files, for example, an installation download for your application. • Your users are using a client (for example, a custom HTTP client) that doesn't support cookies. Decide to use signed URLs or signed cookies 421 Amazon CloudFront Developer Guide Use signed cookies in the following cases: • You want to provide access to multiple restricted files, for example, all of the files for a video in HLS format or all of the files in the subscribers' area of website. • You don't want to change your current URLs. If you are not currently using signed URLs, and if your (unsigned) URLs contain any of the following query string parameters, you cannot use either signed URLs or signed cookies: • Expires • Policy • Signature • Key-Pair-Id CloudFront assumes that URLs that contain any of those query string parameters are signed URLs, and therefore won't look at signed cookies. Use both signed URLs and signed cookies Signed URLs take precedence over signed cookies. If you use both signed URLs and signed cookies to control access to the same files and a viewer uses a signed URL to request a file, CloudFront determines whether to return the file to the viewer based only on the signed URL. Use signed URLs A signed URL includes additional information, for example, an expiration date and time, that gives you more control over access to your content. This additional information appears in a policy statement, which is based on either a canned policy or a custom policy. The differences between canned and custom policies are explained in the next two sections. Note You can create some signed URLs using canned policies and create some signed URLs using custom policies for the same distribution. Topics Use signed URLs 422 Amazon CloudFront Developer Guide • Decide to use canned or custom policies for signed URLs • How signed URLs work • Decide how long signed URLs are valid • When CloudFront checks expiration date and time in a signed URL • Example code and third-party tools • Create a signed URL using a canned policy • Create a signed URL using a custom policy Decide to use canned or custom policies for signed URLs When you create a signed URL, you write a policy statement in JSON format that specifies the restrictions on the signed URL, for example, how long the URL is valid. You can use either a canned policy or a custom policy. Here's how canned and custom policies compare: Description Canned policy Custom policy You can reuse the policy statement for multiple files. To reuse the policy statement, you must use No Yes wildcard characters in the Resource object. For more information, see Values that you specify in the policy statement for a signed URL that uses a custom policy.) You can specify the date and time that users can begin to access your content. You can specify the date and time that users can no longer access your content. You can specify the IP address or range of IP addresses of the users who can access your content. The signed URL includes a base64-encoded version of the policy, which results in a longer URL. No Yes No No Yes (optional) Yes Yes (optional) Yes Use signed URLs 423 Amazon CloudFront Developer Guide For information about creating signed URLs using a canned policy, see Create a signed URL using a canned policy. For information about creating signed URLs using a custom policy, see Create a signed URL using a custom policy. How signed URLs work Here's an overview of how you configure CloudFront and Amazon S3 for signed URLs and how CloudFront responds when a user uses a signed URL to request a file. 1. In your CloudFront distribution, specify one or more trusted key groups, which contain the public keys that CloudFront can use to verify the URL signature. You use the corresponding
AmazonCloudFront_DevGuide-165
AmazonCloudFront_DevGuide.pdf
165
information about creating signed URLs using a canned policy, see Create a signed URL using a canned policy. For information about creating signed URLs using a custom policy, see Create a signed URL using a custom policy. How signed URLs work Here's an overview of how you configure CloudFront and Amazon S3 for signed URLs and how CloudFront responds when a user uses a signed URL to request a file. 1. In your CloudFront distribution, specify one or more trusted key groups, which contain the public keys that CloudFront can use to verify the URL signature. You use the corresponding private keys to sign the URLs. For more information, see Specify signers that can create signed URLs and signed cookies. 2. Develop your application to determine whether a user should have access to your content and to create signed URLs for the files or parts of your application that you want to restrict access to. For more information, see the following topics: • Create a signed URL using a canned policy • Create a signed URL using a custom policy 3. A user requests a file for which you want to require signed URLs. 4. Your application verifies that the user is entitled to access the file: they've signed in, they've paid for access to the content, or they've met some other requirement for access. 5. Your application creates and returns a signed URL to the user. 6. The signed URL allows the user to download or stream the content. This step is automatic; the user usually doesn't have to do anything additional to access the content. For example, if a user is accessing your content in a web browser, your application returns the signed URL to the browser. The browser immediately uses the signed URL to access the file in the CloudFront edge cache without any intervention from the user. 7. CloudFront uses the public key to validate the signature and confirm that the URL hasn't been tampered with. If the signature is invalid, the request is rejected. If the signature is valid, CloudFront looks at the policy statement in the URL (or constructs one if you're using a canned policy) to confirm that the request is still valid. For example, if you Use signed URLs 424 Amazon CloudFront Developer Guide specified a beginning and ending date and time for the URL, CloudFront confirms that the user is trying to access your content during the time period that you want to allow access. If the request meets the requirements in the policy statement, CloudFront does the standard operations: determines whether the file is already in the edge cache, forwards the request to the origin if necessary, and returns the file to the user. Note If an unsigned URL contains query string parameters, make sure you include them in the portion of the URL that you sign. If you add a query string to a signed URL after signing it, the URL returns an HTTP 403 status. Decide how long signed URLs are valid You can distribute private content using a signed URL that is valid for only a short time—possibly for as little as a few minutes. Signed URLs that are valid for such a short period are good for distributing content on-the-fly to a user for a specific purpose, such as distributing movie rentals or music downloads to customers on demand. If your signed URLs will be valid for just a short period, you'll probably want to generate them automatically using an application that you develop. When the user starts to download a file or starts to play a media file, CloudFront compares the expiration time in the URL with the current time to determine whether the URL is still valid. You can also distribute private content using a signed URL that is valid for a longer time, possibly for years. Signed URLs that are valid for a longer period are useful for distributing private content to known users, such as distributing a business plan to investors or distributing training materials to employees. You can develop an application to generate these longer-term signed URLs for you. When CloudFront checks expiration date and time in a signed URL CloudFront checks the expiration date and time in a signed URL at the time of the HTTP request. If a client begins to download a large file immediately before the expiration time, the download should complete even if the expiration time passes during the download. If the TCP connection drops and the client tries to restart the download after the expiration time passes, the download will fail. Use signed URLs 425 Amazon CloudFront Developer Guide If a client uses Range GETs to get a file in smaller pieces, any GET request that occurs after the expiration time passes will fail. For
AmazonCloudFront_DevGuide-166
AmazonCloudFront_DevGuide.pdf
166
checks the expiration date and time in a signed URL at the time of the HTTP request. If a client begins to download a large file immediately before the expiration time, the download should complete even if the expiration time passes during the download. If the TCP connection drops and the client tries to restart the download after the expiration time passes, the download will fail. Use signed URLs 425 Amazon CloudFront Developer Guide If a client uses Range GETs to get a file in smaller pieces, any GET request that occurs after the expiration time passes will fail. For more information about Range GETs, see How CloudFront processes partial requests for an object (range GETs). Example code and third-party tools For example code that creates the hashed and signed part of signed URLs, see the following topics: • Create a URL signature using Perl • Create a URL signature using PHP • Create a URL signature using C# and the .NET Framework • Create a URL signature using Java Create a signed URL using a canned policy To create a signed URL using a canned policy, complete the following steps. To create a signed URL using a canned policy 1. If you're using .NET or Java to create signed URLs, and if you haven't reformatted the private key for your key pair from the default .pem format to a format compatible with .NET or with Java, do so now. For more information, see Reformat the private key (.NET and Java only). 2. Concatenate the following values. You can use the format in this example signed URL. https://d111111abcdef8.cloudfront.net/ image.jpg?color=red&size=medium&Expires=1357034400&Signature=nitfHRCrtziwO2HwPfWw~yYDhUF5EwRunQA- j19DzZrvDh6hQ73lDx~-ar3UocvvRQVw6EkC~GdpGQyyOSKQim- TxAnW7d8F5Kkai9HVx0FIu-5jcQb0UEmatEXAMPLE3ReXySpLSMj0yCd3ZAB4UcBCAqEijkytL6f3fVYNGQI6&Key- Pair-Id=K2JCJMDEHXQW5F Remove all empty spaces (including tabs and newline characters). You might have to include escape characters in the string in application code. All values have a type of String. 1. Base URL for the file The base URL is the CloudFront URL that you would use to access the file if you were not using signed URLs, including your own query string parameters, if any. In the preceding example, the base URL is https://d111111abcdef8.cloudfront.net/image.jpg. Use signed URLs 426 Amazon CloudFront Developer Guide For more information about the format of URLs for distributions, see Customize the URL format for files in CloudFront. • The following CloudFront URL is for an image file in a distribution (using the CloudFront domain name). Note that image.jpg is in an images directory. The path to the file in the URL must match the path to the file on your HTTP server or in your Amazon S3 bucket. https://d111111abcdef8.cloudfront.net/images/image.jpg • The following CloudFront URL includes a query string: https://d111111abcdef8.cloudfront.net/images/image.jpg?size=large • The following CloudFront URLs are for image files in a distribution. Both use an alternate domain name. The second one includes a query string: https://www.example.com/images/image.jpg https://www.example.com/images/image.jpg?color=red • The following CloudFront URL is for an image file in a distribution that uses an alternate domain name and the HTTPS protocol: https://www.example.com/images/image.jpg 2. ? The ? indicates that query parameters follow the base URL. Include the ? even if you don't specify any query parameters. Note You can specify the following query parameters in any order. 3. Your query string parameters, if any& (Optional) You can enter your own query string parameters. To do so, add an ampersand (&) between each one, such as color=red&size=medium. You can specify query string parameters in any order within the URL. Use signed URLs 427 Amazon CloudFront Developer Guide Important Your query string parameters can't be named Expires, Signature, or Key-Pair- Id. 4. Expires=date and time in Unix time format (in seconds) and Coordinated Universal Time (UTC) The date and time that you want the URL to stop allowing access to the file. Specify the expiration date and time in Unix time format (in seconds) and Coordinated Universal Time (UTC). For example, January 1, 2013 10:00 am UTC converts to 1357034400 in Unix time format, as shown in the example at the start of this topic. To use epoch time, use a 32-bit integer for a date that's no later than 2147483647 (January 19th, 2038 at 03:14:07 UTC). For information about UTC, see RFC 3339, Date and Time on the Internet: Timestamps. 5. &Signature=hashed and signed version of the policy statement A hashed, signed, and base64-encoded version of the JSON policy statement. For more information, see Create a signature for a signed URL that uses a canned policy. 6. &Key-Pair-Id=public key ID for the CloudFront public key whose corresponding private key you're using to generate the signature The ID for a CloudFront public key, for example, K2JCJMDEHXQW5F. The public key ID tells CloudFront which public key to use to validate the signed URL. CloudFront compares the information in the signature with the information in the policy statement to verify that the URL has not been tampered with. This public key
AmazonCloudFront_DevGuide-167
AmazonCloudFront_DevGuide.pdf
167
statement A hashed, signed, and base64-encoded version of the JSON policy statement. For more information, see Create a signature for a signed URL that uses a canned policy. 6. &Key-Pair-Id=public key ID for the CloudFront public key whose corresponding private key you're using to generate the signature The ID for a CloudFront public key, for example, K2JCJMDEHXQW5F. The public key ID tells CloudFront which public key to use to validate the signed URL. CloudFront compares the information in the signature with the information in the policy statement to verify that the URL has not been tampered with. This public key must belong to a key group that is a trusted signer in the distribution. For more information, see Specify signers that can create signed URLs and signed cookies. Create a signature for a signed URL that uses a canned policy To create the signature for a signed URL that uses a canned policy, complete the following procedures. Use signed URLs 428 Amazon CloudFront Topics • Create a policy statement for a signed URL that uses a canned policy • Create a signature for a signed URL that uses a canned policy Create a policy statement for a signed URL that uses a canned policy Developer Guide When you create a signed URL using a canned policy, the Signature parameter is a hashed and signed version of a policy statement. For signed URLs that use a canned policy, you don't include the policy statement in the URL, as you do for signed URLs that use a custom policy. To create the policy statement, do the following procedure. To create the policy statement for a signed URL that uses a canned policy 1. Construct the policy statement using the following JSON format and using UTF-8 character encoding. Include all punctuation and other literal values exactly as specified. For information about the Resource and DateLessThan parameters, see Values that you specify in the policy statement for a signed URL that uses a canned policy. { "Statement": [ { "Resource": "base URL or stream name", "Condition": { "DateLessThan": { "AWS:EpochTime": ending date and time in Unix time format and UTC } } } ] } 2. Remove all empty spaces (including tabs and newline characters) from the policy statement. You might have to include escape characters in the string in application code. Values that you specify in the policy statement for a signed URL that uses a canned policy When you create a policy statement for a canned policy, you specify the following values. Use signed URLs 429 Amazon CloudFront Resource Note You can specify only one value for Resource. Developer Guide The base URL including your query strings, if any, but excluding the CloudFront Expires, Signature, and Key-Pair-Id parameters, for example: https://d111111abcdef8.cloudfront.net/images/horizon.jpg? size=large&license=yes Note the following: • Protocol – The value must begin with http:// or https://. • Query string parameters – If you have no query string parameters, omit the question mark. • Alternate domain names – If you specify an alternate domain name (CNAME) in the URL, you must specify the alternate domain name when referencing the file in your webpage or application. Do not specify the Amazon S3 URL for the object. DateLessThan The expiration date and time for the URL in Unix time format (in seconds) and Coordinated Universal Time (UTC). For example, January 1, 2013 10:00 am UTC converts to 1357034400 in Unix time format. This value must match the value of the Expires query string parameter in the signed URL. Do not enclose the value in quotation marks. For more information, see When CloudFront checks expiration date and time in a signed URL. Example policy statement for a signed URL that uses a canned policy When you use the following example policy statement in a signed URL, a user can access the file https://d111111abcdef8.cloudfront.net/horizon.jpg until January 1, 2013 10:00 am UTC: { "Statement": [ Use signed URLs 430 Amazon CloudFront { Developer Guide "Resource": "https://d111111abcdef8.cloudfront.net/horizon.jpg? size=large&license=yes", "Condition": { "DateLessThan": { "AWS:EpochTime": 1357034400 } } } ] } Create a signature for a signed URL that uses a canned policy To create the value for the Signature parameter in a signed URL, you hash and sign the policy statement that you created in Create a policy statement for a signed URL that uses a canned policy. For additional information and examples of how to hash, sign, and encode the policy statement, see: • Linux commands and OpenSSL for base64 encoding and encryption • Code examples for creating a signature for a signed URL Option 1: To create a signature by using a canned policy 1. Use the SHA-1 hash function and RSA to hash and sign the policy statement that you created in the procedure To create the policy statement for a signed URL that uses a canned
AmazonCloudFront_DevGuide-168
AmazonCloudFront_DevGuide.pdf
168
statement that you created in Create a policy statement for a signed URL that uses a canned policy. For additional information and examples of how to hash, sign, and encode the policy statement, see: • Linux commands and OpenSSL for base64 encoding and encryption • Code examples for creating a signature for a signed URL Option 1: To create a signature by using a canned policy 1. Use the SHA-1 hash function and RSA to hash and sign the policy statement that you created in the procedure To create the policy statement for a signed URL that uses a canned policy. Use the version of the policy statement that no longer includes empty spaces. For the private key that is required by the hash function, use a private key whose public key is in an active trusted key group for the distribution. Note The method that you use to hash and sign the policy statement depends on your programming language and platform. For sample code, see Code examples for creating a signature for a signed URL. 2. Remove empty spaces (including tabs and newline characters) from the hashed and signed string. Use signed URLs 431 Amazon CloudFront Developer Guide 3. Base64-encode the string using MIME base64 encoding. For more information, see Section 6.8, Base64 Content-Transfer-Encoding in RFC 2045, MIME (Multipurpose Internet Mail Extensions) Part One: Format of Internet Message Bodies. 4. Replace characters that are invalid in a URL query string with characters that are valid. The following table lists invalid and valid characters. Replace these invalid characters With these valid characters + = / - (hyphen) _ (underscore) ~ (tilde) 5. Append the resulting value to your signed URL after &Signature=, and return to To create a signed URL using a canned policy to finish concatenating the parts of your signed URL. Create a signed URL using a custom policy To create a signed URL using a custom policy, complete the following procedure. To create a signed URL using a custom policy 1. If you're using .NET or Java to create signed URLs, and if you haven't reformatted the private key for your key pair from the default .pem format to a format compatible with .NET or with Java, do so now. For more information, see Reformat the private key (.NET and Java only). 2. Concatenate the following values. You can use the format in this example signed URL. https://d111111abcdef8.cloudfront.net/ image.jpg?color=red&size=medium&Policy=eyANCiAgICEXAMPLEW1lbnQiOiBbeyANCiAgICAgICJSZXNvdXJjZSI6Imh0dHA6Ly9kemJlc3FtN3VuMW0wLmNsb3VkZnJvbnQubmV0L2RlbW8ucGhwIiwgDQogICAgICAiQ29uZGl0aW9uIjp7IA0KICAgICAgICAgIklwQWRkcmVzcyI6eyJBV1M6U291cmNlSXAiOiIyMDcuMTcxLjE4MC4xMDEvMzIifSwNCiAgICAgICAgICJEYXRlR3JlYXRlclRoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTI5Njg2MDE3Nn0sDQogICAgICAgICAiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjEyOTY4NjAyMjZ9DQogICAgICB9IA0KICAgfV0gDQp9DQo&Signature=nitfHRCrtziwO2HwPfWw~yYDhUF5EwRunQA- j19DzZrvDh6hQ73lDx~-ar3UocvvRQVw6EkC~GdpGQyyOSKQim- TxAnW7d8F5Kkai9HVx0FIu-5jcQb0UEmatEXAMPLE3ReXySpLSMj0yCd3ZAB4UcBCAqEijkytL6f3fVYNGQI6&Key- Pair-Id=K2JCJMDEHXQW5F Remove all empty spaces (including tabs and newline characters). You might have to include escape characters in the string in application code. All values have a type of String. Use signed URLs 432 Amazon CloudFront Developer Guide 1. Base URL for the file The base URL is the CloudFront URL that you would use to access the file if you were not using signed URLs, including your own query string parameters, if any. In the preceding example, the base URL is https://d111111abcdef8.cloudfront.net/image.jpg. For more information about the format of URLs for distributions, see Customize the URL format for files in CloudFront. The following examples show values that you specify for distributions. • The following CloudFront URL is for an image file in a distribution (using the CloudFront domain name). Note that image.jpg is in an images directory. The path to the file in the URL must match the path to the file on your HTTP server or in your Amazon S3 bucket. https://d111111abcdef8.cloudfront.net/images/image.jpg • The following CloudFront URL includes a query string: https://d111111abcdef8.cloudfront.net/images/image.jpg?size=large • The following CloudFront URLs are for image files in a distribution. Both use an alternate domain name; the second one includes a query string: https://www.example.com/images/image.jpg https://www.example.com/images/image.jpg?color=red • The following CloudFront URL is for an image file in a distribution that uses an alternate domain name and the HTTPS protocol: https://www.example.com/images/image.jpg 2. ? The ? indicates that query string parameters follow the base URL. Include the ? even if you don't specify any query parameters. Note You can specify the following query parameters in any order. Use signed URLs 433 Amazon CloudFront Developer Guide 3. Your query string parameters, if any& (Optional) You can enter your own query string parameters. To do so, add an ampersand (&) between each one, such as color=red&size=medium. You can specify query string parameters in any order within the URL. Important Your query string parameters can't be named Policy, Signature, or Key-Pair- Id. If you add your own parameters, append an & after each one, including the last one. 4. Policy=base64 encoded version of policy statement Your policy statement in JSON format, with empty spaces removed, then base64 encoded. For more information, see Create a policy statement for a signed URL that uses a custom policy. The policy statement controls the access that a signed URL grants to a user. It includes the URL of the file,
AmazonCloudFront_DevGuide-169
AmazonCloudFront_DevGuide.pdf
169
color=red&size=medium. You can specify query string parameters in any order within the URL. Important Your query string parameters can't be named Policy, Signature, or Key-Pair- Id. If you add your own parameters, append an & after each one, including the last one. 4. Policy=base64 encoded version of policy statement Your policy statement in JSON format, with empty spaces removed, then base64 encoded. For more information, see Create a policy statement for a signed URL that uses a custom policy. The policy statement controls the access that a signed URL grants to a user. It includes the URL of the file, an expiration date and time, an optional date and time that the URL becomes valid, and an optional IP address or range of IP addresses that are allowed to access the file. 5. &Signature=hashed and signed version of the policy statement A hashed, signed, and base64-encoded version of the JSON policy statement. For more information, see Create a signature for a signed URL that uses a custom policy. 6. &Key-Pair-Id=public key ID for the CloudFront public key whose corresponding private key you're using to generate the signature The ID for a CloudFront public key, for example, K2JCJMDEHXQW5F. The public key ID tells CloudFront which public key to use to validate the signed URL. CloudFront compares the information in the signature with the information in the policy statement to verify that the URL has not been tampered with. This public key must belong to a key group that is a trusted signer in the distribution. For more information, see Specify signers that can create signed URLs and signed cookies. Use signed URLs 434 Amazon CloudFront Developer Guide Create a policy statement for a signed URL that uses a custom policy Complete the following steps to create a policy statement for a signed URL that uses a custom policy. For example policy statements that control access to files in a variety of ways, see the section called “Example policy statements for a signed URL that uses a custom policy”. To create the policy statement for a signed URL that uses a custom policy 1. Construct the policy statement using the following JSON format. Replace the less than (<) and greater than (>) symbols, and the descriptions within them, with your own values. For more information, see the section called “Values that you specify in the policy statement for a signed URL that uses a custom policy”. { "Statement": [ { "Resource": "<Optional but recommended: URL of the file>", "Condition": { "DateLessThan": { "AWS:EpochTime": <Required: ending date and time in Unix time format and UTC> }, "DateGreaterThan": { "AWS:EpochTime": <Optional: beginning date and time in Unix time format and UTC> }, "IpAddress": { "AWS:SourceIp": "<Optional: IP address>" } } } ] } Note the following: • You can include only one statement in the policy. • Use UTF-8 character encoding. Use signed URLs 435 Amazon CloudFront Developer Guide • Include all punctuation and parameter names exactly as specified. Abbreviations for parameter names are not accepted. • The order of the parameters in the Condition section doesn't matter. • For information about the values for Resource, DateLessThan, DateGreaterThan, and IpAddress, see the section called “Values that you specify in the policy statement for a signed URL that uses a custom policy”. 2. Remove all empty spaces (including tabs and newline characters) from the policy statement. You might have to include escape characters in the string in application code. 3. Base64-encode the policy statement using MIME base64 encoding. For more information, see Section 6.8, Base64 Content-Transfer-Encoding in RFC 2045, MIME (Multipurpose Internet Mail Extensions) Part One: Format of Internet Message Bodies. 4. Replace characters that are invalid in a URL query string with characters that are valid. The following table lists invalid and valid characters. Replace these invalid characters With these valid characters + = / - (hyphen) _ (underscore) ~ (tilde) 5. Append the resulting value to your signed URL after Policy=. 6. Create a signature for the signed URL by hashing, signing, and base64-encoding the policy statement. For more information, see the section called “Create a signature for a signed URL that uses a custom policy”. Values that you specify in the policy statement for a signed URL that uses a custom policy When you create a policy statement for a custom policy, you specify the following values. Resource The URL, including any query strings, but excluding the CloudFront Policy, Signature, and Key-Pair-Id parameters. For example: Use signed URLs 436 Amazon CloudFront Developer Guide https://d111111abcdef8.cloudfront.net/images/horizon.jpg\? size=large&license=yes You can specify only one URL value for Resource. Important You can omit the Resource parameter in a policy, but doing so means that anyone with the signed URL can access all of the files in any distribution that is associated with the key pair that you
AmazonCloudFront_DevGuide-170
AmazonCloudFront_DevGuide.pdf
170
statement for a signed URL that uses a custom policy When you create a policy statement for a custom policy, you specify the following values. Resource The URL, including any query strings, but excluding the CloudFront Policy, Signature, and Key-Pair-Id parameters. For example: Use signed URLs 436 Amazon CloudFront Developer Guide https://d111111abcdef8.cloudfront.net/images/horizon.jpg\? size=large&license=yes You can specify only one URL value for Resource. Important You can omit the Resource parameter in a policy, but doing so means that anyone with the signed URL can access all of the files in any distribution that is associated with the key pair that you use to create the signed URL. Note the following: • Protocol – The value must begin with http://, https://, or *://. • Query string parameters – If the URL has query string parameters, use a backslash character (\) to escape the question mark character (?) that begins the query string. For example: https://d111111abcdef8.cloudfront.net/images/horizon.jpg\? size=large&license=yes • Wildcard characters – You can use wildcard characters in the URL in the policy. The following wildcard characters are supported: • asterisk (*), which matches zero or more characters • question mark (?), which matches exactly one character When CloudFront matches the URL in the policy to the URL in the HTTP request, the URL in the policy is divided into four sections—protocol, domain, path, and query string—as follows: [protocol]://[domain]/[path]\?[query string] When you use a wildcard character in the URL in the policy, the wildcard matching applies only within the boundaries of the section that contains the wildcard. For example, consider this URL in a policy: https://www.example.com/hello*world In this example, the asterisk wildcard (*) only applies within the path section, so it matches the URLs https://www.example.com/helloworld and https://www.example.com/ hello-world, but it does not match the URL https://www.example.net/hello?world. Use signed URLs 437 Amazon CloudFront Developer Guide The following exceptions apply to the section boundaries for wildcard matching: • A trailing asterisk in the path section implies an asterisk in the query string section. For example, http://example.com/hello* is equivalent to http://example.com/ hello*\?*. • A trailing asterisk in the domain section implies an asterisk in both the path and query string sections. For example, http://example.com* is equivalent to http:// example.com*/*\?*. • A URL in the policy can omit the protocol section and start with an asterisk in the domain section. In that case, the protocol section is implicitly set to an asterisk. For example, the URL *example.com in a policy is equivalent to *://*example.com/. • An asterisk by itself ("Resource": "*") matches any URL. For example, the value: https://d111111abcdef8.cloudfront.net/ *game_download.zip* in a policy matches all of the following URLs: • https://d111111abcdef8.cloudfront.net/game_download.zip • https://d111111abcdef8.cloudfront.net/example_game_download.zip? license=yes • https://d111111abcdef8.cloudfront.net/test_game_download.zip? license=temp • Alternate domain names – If you specify an alternate domain name (CNAME) in the URL in the policy, the HTTP request must use the alternate domain name in your webpage or application. Do not specify the Amazon S3 URL for the file in a policy. DateLessThan The expiration date and time for the URL in Unix time format (in seconds) and Coordinated Universal Time (UTC). In the policy, do not enclose the value in quotation marks. For information about UTC, see Date and Time on the Internet: Timestamps. For example, January 31, 2023 10:00 AM UTC converts to 1675159200 in Unix time format. This is the only required parameter in the Condition section. CloudFront requires this value to prevent users from having permanent access to your private content. For more information, see the section called “When CloudFront checks expiration date and time in a signed URL” Use signed URLs 438 Amazon CloudFront DateGreaterThan (Optional) Developer Guide An optional start date and time for the URL in Unix time format (in seconds) and Coordinated Universal Time (UTC). Users are not allowed to access the file on or before the specified date and time. Do not enclose the value in quotation marks. IpAddress (Optional) The IP address of the client making the HTTP request. Note the following: • To allow any IP address to access the file, omit the IpAddress parameter. • You can specify either one IP address or one IP address range. You can't use the policy to allow access if the client's IP address is in one of two separate ranges. • To allow access from a single IP address, you specify: "IPv4 IP address/32" • You must specify IP address ranges in standard IPv4 CIDR format (for example, 192.0.2.0/24). For more information, see Classless Inter-domain Routing (CIDR): The Internet Address Assignment and Aggregation Plan. Important IP addresses in IPv6 format, such as 2001:0db8:85a3::8a2e:0370:7334, are not supported. If you're using a custom policy that includes IpAddress, do not enable IPv6 for the distribution. If you want to restrict access to some content by IP address and support IPv6 requests for other content, you can create two distributions. For more
AmazonCloudFront_DevGuide-171
AmazonCloudFront_DevGuide.pdf
171
separate ranges. • To allow access from a single IP address, you specify: "IPv4 IP address/32" • You must specify IP address ranges in standard IPv4 CIDR format (for example, 192.0.2.0/24). For more information, see Classless Inter-domain Routing (CIDR): The Internet Address Assignment and Aggregation Plan. Important IP addresses in IPv6 format, such as 2001:0db8:85a3::8a2e:0370:7334, are not supported. If you're using a custom policy that includes IpAddress, do not enable IPv6 for the distribution. If you want to restrict access to some content by IP address and support IPv6 requests for other content, you can create two distributions. For more information, see the section called “Enable IPv6” in the topic the section called “Distribution settings”. Example policy statements for a signed URL that uses a custom policy The following example policy statements show how to control access to a specific file, all of the files in a directory, or all of the files associated with a key pair ID. The examples also show how to control access from an individual IP address or a range of IP addresses, and how to prevent users from using the signed URL after a specified date and time. Use signed URLs 439 Amazon CloudFront Developer Guide If you copy and paste any of these examples, remove any empty spaces (including tabs and newline characters), replace the values with your own values, and include a newline character after the closing brace (}). For more information, see the section called “Values that you specify in the policy statement for a signed URL that uses a custom policy”. Topics • Example policy statement: Access one file from a range of IP addresses • Example policy statement: Access all files in a directory from a range of IP addresses • Example policy statement: Access all files associated with a key pair ID from one IP address Example policy statement: Access one file from a range of IP addresses The following example custom policy in a signed URL specifies that a user can access the file https://d111111abcdef8.cloudfront.net/game_download.zip from IP addresses in the range 192.0.2.0/24 until January 31, 2023 10:00 AM UTC: { "Statement": [ { "Resource": "https://d111111abcdef8.cloudfront.net/game_download.zip", "Condition": { "IpAddress": { "AWS:SourceIp": "192.0.2.0/24" }, "DateLessThan": { "AWS:EpochTime": 1675159200 } } } ] } Example policy statement: Access all files in a directory from a range of IP addresses The following example custom policy allows you to create signed URLs for any file in the training directory, as indicated by the asterisk wildcard character (*) in the Resource parameter. Users can access the file from an IP address in the range 192.0.2.0/24 until January 31, 2023 10:00 AM UTC: Use signed URLs 440 Amazon CloudFront Developer Guide { "Statement": [ { "Resource": "https://d111111abcdef8.cloudfront.net/training/*", "Condition": { "IpAddress": { "AWS:SourceIp": "192.0.2.0/24" }, "DateLessThan": { "AWS:EpochTime": 1675159200 } } } ] } Each signed URL with which you use this policy has a URL that identifies a specific file, for example: https://d111111abcdef8.cloudfront.net/training/orientation.pdf Example policy statement: Access all files associated with a key pair ID from one IP address The following example custom policy allows you to create signed URLs for any file associated with any distribution, as indicated by the asterisk wildcard character (*) in the Resource parameter. The signed URL must use the https:// protocol, not http://. The user must use the IP address 192.0.2.10/32. (The value 192.0.2.10/32 in CIDR notation refers to a single IP address, 192.0.2.10.) The files are available only from January 31, 2023 10:00 AM UTC until February 2, 2023 10:00 AM UTC: { "Statement": [ { "Resource": "https://*", "Condition": { "IpAddress": { "AWS:SourceIp": "192.0.2.10/32" }, "DateGreaterThan": { "AWS:EpochTime": 1675159200 }, "DateLessThan": { "AWS:EpochTime": 1675332000 Use signed URLs 441 Amazon CloudFront } } } ] } Developer Guide Each signed URL with which you use this policy has a URL that identifies a specific file in a specific CloudFront distribution, for example: https://d111111abcdef8.cloudfront.net/training/orientation.pdf The signed URL also includes a key pair ID, which must be associated with a trusted key group in the distribution (d111111abcdef8.cloudfront.net) that you specify in the URL. Create a signature for a signed URL that uses a custom policy The signature for a signed URL that uses a custom policy is a hashed, signed, and base64-encoded version of the policy statement. To create a signature for a custom policy, complete the following steps. For additional information and examples of how to hash, sign, and encode the policy statement, see: • Linux commands and OpenSSL for base64 encoding and encryption • Code examples for creating a signature for a signed URL Option 1: To create a signature by using a custom policy 1. Use the SHA-1 hash function and RSA to hash and sign the JSON policy statement that you created in the procedure To create the policy statement for a signed URL that uses
AmazonCloudFront_DevGuide-172
AmazonCloudFront_DevGuide.pdf
172
and base64-encoded version of the policy statement. To create a signature for a custom policy, complete the following steps. For additional information and examples of how to hash, sign, and encode the policy statement, see: • Linux commands and OpenSSL for base64 encoding and encryption • Code examples for creating a signature for a signed URL Option 1: To create a signature by using a custom policy 1. Use the SHA-1 hash function and RSA to hash and sign the JSON policy statement that you created in the procedure To create the policy statement for a signed URL that uses a custom policy. Use the version of the policy statement that no longer includes empty spaces but that has not yet been base64-encoded. For the private key that is required by the hash function, use a private key whose public key is in an active trusted key group for the distribution. Use signed URLs 442 Amazon CloudFront Note Developer Guide The method that you use to hash and sign the policy statement depends on your programming language and platform. For sample code, see Code examples for creating a signature for a signed URL. 2. Remove empty spaces (including tabs and newline characters) from the hashed and signed string. 3. Base64-encode the string using MIME base64 encoding. For more information, see Section 6.8, Base64 Content-Transfer-Encoding in RFC 2045, MIME (Multipurpose Internet Mail Extensions) Part One: Format of Internet Message Bodies. 4. Replace characters that are invalid in a URL query string with characters that are valid. The following table lists invalid and valid characters. Replace these invalid characters With these valid characters + = / - (hyphen) _ (underscore) ~ (tilde) 5. Append the resulting value to your signed URL after &Signature=, and return to To create a signed URL using a custom policy to finish concatenating the parts of your signed URL. Use signed cookies CloudFront signed cookies allow you to control who can access your content when you don't want to change your current URLs or when you want to provide access to multiple restricted files, for example, all of the files in the subscribers' area of a website. This topic explains the considerations when using signed cookies and describes how to set signed cookies using canned and custom policies. Topics • Decide to use canned or custom policies for signed cookies • How signed cookies work Use signed cookies 443 Amazon CloudFront Developer Guide • Prevent misuse of signed cookies • When CloudFront checks expiration date and time in a signed cookie • Sample code and third-party tools • Set signed cookies using a canned policy • Set signed cookies using a custom policy • Create signed cookies using PHP Decide to use canned or custom policies for signed cookies When you create a signed cookie, you write a policy statement in JSON format that specifies the restrictions on the signed cookie, for example, how long the cookie is valid. You can use canned policies or custom policies. The following table compares canned and custom policies: Description Canned policy Custom policy You can reuse the policy statement for multiple files. To reuse the policy statement, you must use No Yes wildcard characters in the Resource object. For more information, see Values that you specify in the policy statement for a custom policy for signed cookies.) You can specify the date and time that users can begin to access your content You can specify the date and time that users can no longer access your content You can specify the IP address or range of IP addresses of the users who can access your content No Yes No Yes (optional) Yes Yes (optional) For information about creating signed cookies using a canned policy, see Set signed cookies using a canned policy. For information about creating signed cookies using a custom policy, see Set signed cookies using a custom policy. Use signed cookies 444 Amazon CloudFront How signed cookies work Developer Guide Here's an overview of how you configure CloudFront for signed cookies and how CloudFront responds when a user submits a request that contains a signed cookie. 1. In your CloudFront distribution, specify one or more trusted key groups, which contain the public keys that CloudFront can use to verify the URL signature. You use the corresponding private keys to sign the URLs. For more information, see Specify signers that can create signed URLs and signed cookies. 2. You develop your application to determine whether a user should have access to your content and, if so, to send three Set-Cookie headers to the viewer. (Each Set-Cookie header can contain only one name-value pair, and a CloudFront signed cookie requires three name-value pairs.) You must send the Set-Cookie headers to the viewer before the viewer requests your private content. If
AmazonCloudFront_DevGuide-173
AmazonCloudFront_DevGuide.pdf
173
which contain the public keys that CloudFront can use to verify the URL signature. You use the corresponding private keys to sign the URLs. For more information, see Specify signers that can create signed URLs and signed cookies. 2. You develop your application to determine whether a user should have access to your content and, if so, to send three Set-Cookie headers to the viewer. (Each Set-Cookie header can contain only one name-value pair, and a CloudFront signed cookie requires three name-value pairs.) You must send the Set-Cookie headers to the viewer before the viewer requests your private content. If you set a short expiration time on the cookie, you might also want to send three more Set-Cookie headers in response to subsequent requests, so that the user continues to have access. Typically, your CloudFront distribution will have at least two cache behaviors, one that doesn't require authentication and one that does. The error page for the secure portion of the site includes a redirector or a link to a login page. If you configure your distribution to cache files based on cookies, CloudFront doesn't cache separate files based on the attributes in signed cookies. 3. A user signs in to your website and either pays for content or meets some other requirement for access. 4. Your application returns the Set-Cookie headers in the response, and the viewer stores the name-value pairs. 5. The user requests a file. The user's browser or other viewer gets the name-value pairs from step 4 and adds them to the request in a Cookie header. This is the signed cookie. 6. CloudFront uses the public key to validate the signature in the signed cookie and to confirm that the cookie hasn't been tampered with. If the signature is invalid, the request is rejected. If the signature in the cookie is valid, CloudFront looks at the policy statement in the cookie (or constructs one if you're using a canned policy) to confirm that the request is still valid. For example, if you specified a beginning and ending date and time for the cookie, CloudFront Use signed cookies 445 Amazon CloudFront Developer Guide confirms that the user is trying to access your content during the time period that you want to allow access. If the request meets the requirements in the policy statement, CloudFront serves your content as it does for content that isn't restricted: it determines whether the file is already in the edge cache, forwards the request to the origin if necessary, and returns the file to the user. Prevent misuse of signed cookies If you specify the Domain parameter in a Set-Cookie header, specify the most precise value possible to reduce the potential for access by someone with the same root domain name. For example, app.example.com is preferable to example.com, especially when you don't control example.com. This helps prevent someone from accessing your content from www.example.com. To help prevent this type of attack, do the following: • Exclude the Expires and Max-Age cookie attributes, so that the Set-Cookie header creates a session cookie. Session cookies are automatically deleted when the user closes the browser, which reduces the possibility of someone getting unauthorized access to your content. • Include the Secure attribute, so that the cookie is encrypted when a viewer includes it in a request. • When possible, use a custom policy and include the IP address of the viewer. • In the CloudFront-Expires attribute, specify the shortest reasonable expiration time based on how long you want users to have access to your content. When CloudFront checks expiration date and time in a signed cookie To determine whether a signed cookie is still valid, CloudFront checks the expiration date and time in the cookie at the time of the HTTP request. If a client begins to download a large file immediately before the expiration time, the download should complete even if the expiration time passes during the download. If the TCP connection drops and the client tries to restart the download after the expiration time passes, the download will fail. If a client uses Range GETs to get a file in smaller pieces, any GET request that occurs after the expiration time passes will fail. For more information about Range GETs, see How CloudFront processes partial requests for an object (range GETs). Use signed cookies 446 Amazon CloudFront Developer Guide Sample code and third-party tools The sample code for private content shows only how to create the signature for signed URLs. However, the process for creating a signature for a signed cookie is very similar, so much of the sample code is still relevant. For more information, see the following topics: • Create a URL signature using Perl • Create a URL signature using PHP • Create a URL signature using C# and
AmazonCloudFront_DevGuide-174
AmazonCloudFront_DevGuide.pdf
174
will fail. For more information about Range GETs, see How CloudFront processes partial requests for an object (range GETs). Use signed cookies 446 Amazon CloudFront Developer Guide Sample code and third-party tools The sample code for private content shows only how to create the signature for signed URLs. However, the process for creating a signature for a signed cookie is very similar, so much of the sample code is still relevant. For more information, see the following topics: • Create a URL signature using Perl • Create a URL signature using PHP • Create a URL signature using C# and the .NET Framework • Create a URL signature using Java Set signed cookies using a canned policy To set a signed cookie by using a canned policy, complete the following steps. To create the signature, see Create a signature for a signed cookie that uses a canned policy. To set a signed cookie using a canned policy 1. If you're using .NET or Java to create signed cookies, and if you haven't reformatted the private key for your key pair from the default .pem format to a format compatible with .NET or with Java, do so now. For more information, see Reformat the private key (.NET and Java only). 2. Program your application to send three Set-Cookie headers to approved viewers. You need three Set-Cookie headers because each Set-Cookie header can contain only one name- value pair, and a CloudFront signed cookie requires three name-value pairs. The name-value pairs are: CloudFront-Expires, CloudFront-Signature, and CloudFront-Key-Pair- Id. The values must be present on the viewer before a user makes the first request for a file that you want to control access to. Note In general, we recommend that you exclude Expires and Max-Age attributes. Excluding the attributes causes the browser to delete the cookie when the user closes the browser, which reduces the possibility of someone getting unauthorized access to your content. For more information, see Prevent misuse of signed cookies. The names of cookie attributes are case-sensitive. Use signed cookies 447 Amazon CloudFront Developer Guide Line breaks are included only to make the attributes more readable. Set-Cookie: CloudFront-Expires=date and time in Unix time format (in seconds) and Coordinated Universal Time (UTC); Domain=optional domain name; Path=/optional directory path; Secure; HttpOnly Set-Cookie: CloudFront-Signature=hashed and signed version of the policy statement; Domain=optional domain name; Path=/optional directory path; Secure; HttpOnly Set-Cookie: CloudFront-Key-Pair-Id=public key ID for the CloudFront public key whose corresponding private key you're using to generate the signature; Domain=optional domain name; Path=/optional directory path; Secure; HttpOnly (Optional) Domain The domain name for the requested file. If you don't specify a Domain attribute, the default value is the domain name in the URL, and it applies only to the specified domain name, not to subdomains. If you specify a Domain attribute, it also applies to subdomains. A leading dot in the domain name (for example, Domain=.example.com) is optional. In addition, if you specify a Domain attribute, the domain name in the URL and the value of the Domain attribute must match. You can specify the domain name that CloudFront assigned to your distribution, for example, d111111abcdef8.cloudfront.net, but you can't specify *.cloudfront.net for the domain name. If you want to use an alternate domain name such as example.com in URLs, you must add the alternate domain name to your distribution regardless of whether you specify the Use signed cookies 448 Amazon CloudFront Developer Guide Domain attribute. For more information, see Alternate domain names (CNAMEs) in the topic Distribution settings reference. (Optional) Path The path for the requested file. If you don't specify a Path attribute, the default value is the path in the URL. Secure Requires that the viewer encrypt cookies before sending a request. We recommend that you send the Set-Cookie header over an HTTPS connection to ensure that the cookie attributes are protected from man-in-the-middle attacks. HttpOnly Defines how the browser (where supported) interacts with the cookie value. With HttpOnly, the cookie values are inaccessible to JavaScript. This precaution can help mitigate cross-site scripting (XSS) attacks. For more information, see Using HTTP cookies. CloudFront-Expires Specify the expiration date and time in Unix time format (in seconds) and Coordinated Universal Time (UTC). For example, January 1, 2013 10:00 am UTC converts to 1357034400 in Unix time format. To use epoch time, use a 32-bit integer for a date that's no later than 2147483647 (January 19th, 2038 at 03:14:07 UTC). For information about UTC, see RFC 3339, Date and Time on the Internet: Timestamps, https://tools.ietf.org/html/rfc3339. CloudFront-Signature A hashed, signed, and base64-encoded version of a JSON policy statement. For more information, see Create a signature for a signed cookie that uses a canned policy. CloudFront-Key-Pair-Id The ID for a CloudFront public key, for example, K2JCJMDEHXQW5F. The public key ID tells CloudFront which public key to use to
AmazonCloudFront_DevGuide-175
AmazonCloudFront_DevGuide.pdf
175
1, 2013 10:00 am UTC converts to 1357034400 in Unix time format. To use epoch time, use a 32-bit integer for a date that's no later than 2147483647 (January 19th, 2038 at 03:14:07 UTC). For information about UTC, see RFC 3339, Date and Time on the Internet: Timestamps, https://tools.ietf.org/html/rfc3339. CloudFront-Signature A hashed, signed, and base64-encoded version of a JSON policy statement. For more information, see Create a signature for a signed cookie that uses a canned policy. CloudFront-Key-Pair-Id The ID for a CloudFront public key, for example, K2JCJMDEHXQW5F. The public key ID tells CloudFront which public key to use to validate the signed URL. CloudFront compares the information in the signature with the information in the policy statement to verify that the URL has not been tampered with. This public key must belong to a key group that is a trusted signer in the distribution. For more information, see Specify signers that can create signed URLs and signed cookies. Use signed cookies 449 Amazon CloudFront Developer Guide The following example shows Set-Cookie headers for one signed cookie when you're using the domain name that is associated with your distribution in the URLs for your files: Set-Cookie: CloudFront-Expires=1426500000; Domain=d111111abcdef8.cloudfront.net; Path=/ images/*; Secure; HttpOnly Set-Cookie: CloudFront-Signature=yXrSIgyQoeE4FBI4eMKF6ho~CA8_; Domain=d111111abcdef8.cloudfront.net; Path=/images/*; Secure; HttpOnly Set-Cookie: CloudFront-Key-Pair-Id=K2JCJMDEHXQW5F; Domain=d111111abcdef8.cloudfront.net; Path=/images/*; Secure; HttpOnly The following example shows Set-Cookie headers for one signed cookie when you're using the alternate domain name example.org in the URLs for your files: Set-Cookie: CloudFront-Expires=1426500000; Domain=example.org; Path=/images/*; Secure; HttpOnly Set-Cookie: CloudFront-Signature=yXrSIgyQoeE4FBI4eMKF6ho~CA8_; Domain=example.org; Path=/images/*; Secure; HttpOnly Set-Cookie: CloudFront-Key-Pair-Id=K2JCJMDEHXQW5F; Domain=example.org; Path=/images/*; Secure; HttpOnly If you want to use an alternate domain name such as example.com in URLs, you must add the alternate domain name to your distribution regardless of whether you specify the Domain attribute. For more information, see Alternate domain names (CNAMEs) in the topic Distribution settings reference. Create a signature for a signed cookie that uses a canned policy To create the signature for a signed cookie that uses a canned policy, complete the following procedures. Topics • Create a policy statement for a signed cookie that uses a canned policy • Sign the policy statement to create a signature for a signed cookie that uses a canned policy Create a policy statement for a signed cookie that uses a canned policy When you set a signed cookie that uses a canned policy, the CloudFront-Signature attribute is a hashed and signed version of a policy statement. For signed cookies that use a canned policy, you don't include the policy statement in the Set-Cookie header, as you do for signed cookies that use a custom policy. To create the policy statement, complete the following steps. Use signed cookies 450 Amazon CloudFront Developer Guide To create a policy statement for a signed cookie that uses a canned policy 1. Construct the policy statement using the following JSON format and using UTF-8 character encoding. Include all punctuation and other literal values exactly as specified. For information about the Resource and DateLessThan parameters, see Values that you specify in the policy statement for a canned policy for signed cookies. { "Statement": [ { "Resource": "base URL or stream name", "Condition": { "DateLessThan": { "AWS:EpochTime": ending date and time in Unix time format and UTC } } } ] } 2. Remove all empty spaces (including tabs and newline characters) from the policy statement. You might have to include escape characters in the string in application code. Values that you specify in the policy statement for a canned policy for signed cookies When you create a policy statement for a canned policy, you specify the following values: Resource The base URL including your query strings, if any, for example: https://d111111abcdef8.cloudfront.net/images/horizon.jpg? size=large&license=yes You can specify only one value for Resource. Note the following: • Protocol – The value must begin with http:// or https://. • Query string parameters – If you have no query string parameters, omit the question mark. Use signed cookies 451 Amazon CloudFront Developer Guide • Alternate domain names – If you specify an alternate domain name (CNAME) in the URL, you must specify the alternate domain name when referencing the file in your webpage or application. Do not specify the Amazon S3 URL for the file. DateLessThan The expiration date and time for the URL in Unix time format (in seconds) and Coordinated Universal Time (UTC). Do not enclose the value in quotation marks. For example, March 16, 2015 10:00 am UTC converts to 1426500000 in Unix time format. This value must match the value of the CloudFront-Expires attribute in the Set-Cookie header. Do not enclose the value in quotation marks. For more information, see When CloudFront checks expiration date and time in a signed cookie. Example policy statement for a canned policy When you use the following example policy statement in a signed cookie, a user
AmazonCloudFront_DevGuide-176
AmazonCloudFront_DevGuide.pdf
176
The expiration date and time for the URL in Unix time format (in seconds) and Coordinated Universal Time (UTC). Do not enclose the value in quotation marks. For example, March 16, 2015 10:00 am UTC converts to 1426500000 in Unix time format. This value must match the value of the CloudFront-Expires attribute in the Set-Cookie header. Do not enclose the value in quotation marks. For more information, see When CloudFront checks expiration date and time in a signed cookie. Example policy statement for a canned policy When you use the following example policy statement in a signed cookie, a user can access the file https://d111111abcdef8.cloudfront.net/horizon.jpg until March 16, 2015 10:00 am UTC: { "Statement": [ { "Resource": "https://d111111abcdef8.cloudfront.net/horizon.jpg? size=large&license=yes", "Condition": { "DateLessThan": { "AWS:EpochTime": 1426500000 } } } ] } Sign the policy statement to create a signature for a signed cookie that uses a canned policy To create the value for the CloudFront-Signature attribute in a Set-Cookie header, you hash and sign the policy statement that you created in To create a policy statement for a signed cookie that uses a canned policy. Use signed cookies 452 Amazon CloudFront Developer Guide For additional information and examples of how to hash, sign, and encode the policy statement, see the following topics: • Linux commands and OpenSSL for base64 encoding and encryption • Code examples for creating a signature for a signed URL To create a signature for a signed cookie using a canned policy 1. Use the SHA-1 hash function and RSA to hash and sign the policy statement that you created in the procedure To create a policy statement for a signed cookie that uses a canned policy. Use the version of the policy statement that no longer includes empty spaces. For the private key that is required by the hash function, use a private key whose public key is in an active trusted key group for the distribution. Note The method that you use to hash and sign the policy statement depends on your programming language and platform. For sample code, see Code examples for creating a signature for a signed URL. 2. Remove empty spaces (including tabs and newline characters) from the hashed and signed string. 3. Base64-encode the string using MIME base64 encoding. For more information, see Section 6.8, Base64 Content-Transfer-Encoding in RFC 2045, MIME (Multipurpose Internet Mail Extensions) Part One: Format of Internet Message Bodies. 4. Replace characters that are invalid in a URL query string with characters that are valid. The following table lists invalid and valid characters. Replace these invalid characters With these valid characters + = / - (hyphen) _ (underscore) ~ (tilde) Use signed cookies 453 Amazon CloudFront Developer Guide 5. Include the resulting value in the Set-Cookie header for the CloudFront-Signature name-value pair. Then return to To set a signed cookie using a canned policy add the Set- Cookie header for CloudFront-Key-Pair-Id. Set signed cookies using a custom policy To set a signed cookie that uses a custom policy, complete the following steps. To set a signed cookie using a custom policy 1. If you're using .NET or Java to create signed URLs, and if you haven't reformatted the private key for your key pair from the default .pem format to a format compatible with .NET or with Java, do so now. For more information, see Reformat the private key (.NET and Java only). 2. Program your application to send three Set-Cookie headers to approved viewers. You need three Set-Cookie headers because each Set-Cookie header can contain only one name- value pair, and a CloudFront signed cookie requires three name-value pairs. The name-value pairs are: CloudFront-Policy, CloudFront-Signature, and CloudFront-Key-Pair- Id. The values must be present on the viewer before a user makes the first request for a file that you want to control access to. Note In general, we recommend that you exclude Expires and Max-Age attributes. This causes the browser to delete the cookie when the user closes the browser, which reduces the possibility of someone getting unauthorized access to your content. For more information, see Prevent misuse of signed cookies. The names of cookie attributes are case-sensitive. Line breaks are included only to make the attributes more readable. Set-Cookie: CloudFront-Policy=base64 encoded version of the policy statement; Domain=optional domain name; Path=/optional directory path; Secure; HttpOnly Use signed cookies 454 Amazon CloudFront Developer Guide Set-Cookie: CloudFront-Signature=hashed and signed version of the policy statement; Domain=optional domain name; Path=/optional directory path; Secure; HttpOnly Set-Cookie: CloudFront-Key-Pair-Id=public key ID for the CloudFront public key whose corresponding private key you're using to generate the signature; Domain=optional domain name; Path=/optional directory path; Secure; HttpOnly (Optional) Domain The domain name for the requested file. If you don't specify a Domain attribute, the default value is the domain name in the URL, and it applies only to the
AmazonCloudFront_DevGuide-177
AmazonCloudFront_DevGuide.pdf
177
Set-Cookie: CloudFront-Policy=base64 encoded version of the policy statement; Domain=optional domain name; Path=/optional directory path; Secure; HttpOnly Use signed cookies 454 Amazon CloudFront Developer Guide Set-Cookie: CloudFront-Signature=hashed and signed version of the policy statement; Domain=optional domain name; Path=/optional directory path; Secure; HttpOnly Set-Cookie: CloudFront-Key-Pair-Id=public key ID for the CloudFront public key whose corresponding private key you're using to generate the signature; Domain=optional domain name; Path=/optional directory path; Secure; HttpOnly (Optional) Domain The domain name for the requested file. If you don't specify a Domain attribute, the default value is the domain name in the URL, and it applies only to the specified domain name, not to subdomains. If you specify a Domain attribute, it also applies to subdomains. A leading dot in the domain name (for example, Domain=.example.com) is optional. In addition, if you specify a Domain attribute, the domain name in the URL and the value of the Domain attribute must match. You can specify the domain name that CloudFront assigned to your distribution, for example, d111111abcdef8.cloudfront.net, but you can't specify *.cloudfront.net for the domain name. If you want to use an alternate domain name such as example.com in URLs, you must add the alternate domain name to your distribution regardless of whether you specify the Domain attribute. For more information, see Alternate domain names (CNAMEs) in the topic Distribution settings reference. (Optional) Path The path for the requested file. If you don't specify a Path attribute, the default value is the path in the URL. Use signed cookies 455 Amazon CloudFront Secure Developer Guide Requires that the viewer encrypt cookies before sending a request. We recommend that you send the Set-Cookie header over an HTTPS connection to ensure that the cookie attributes are protected from man-in-the-middle attacks. HttpOnly Requires that the viewer send the cookie only in HTTP or HTTPS requests. CloudFront-Policy Your policy statement in JSON format, with empty spaces removed, then base64 encoded. For more information, see Create a signature for a signed cookie that uses a custom policy. The policy statement controls the access that a signed cookie grants to a user. It includes the files that the user can access, an expiration date and time, an optional date and time that the URL becomes valid, and an optional IP address or range of IP addresses that are allowed to access the file. CloudFront-Signature A hashed, signed, and base64-encoded version of the JSON policy statement. For more information, see Create a signature for a signed cookie that uses a custom policy. CloudFront-Key-Pair-Id The ID for a CloudFront public key, for example, K2JCJMDEHXQW5F. The public key ID tells CloudFront which public key to use to validate the signed URL. CloudFront compares the information in the signature with the information in the policy statement to verify that the URL has not been tampered with. This public key must belong to a key group that is a trusted signer in the distribution. For more information, see Specify signers that can create signed URLs and signed cookies. Example Set-Cookie headers for custom policies See the following examples of Set-Cookie header pairs. If you want to use an alternate domain name such as example.org in URLs, you must add the alternate domain name to your distribution regardless of whether you specify the Domain Use signed cookies 456 Amazon CloudFront Developer Guide attribute. For more information, see Alternate domain names (CNAMEs) in the topic Distribution settings reference. Example Example 1 You can use the Set-Cookie headers for one signed cookie when you're using the domain name that is associated with your distribution in the URLs for your files. Set-Cookie: CloudFront- Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cDovL2QxMTExMTFhYmNkZWY4LmNsb3VkZnJvbnQubmV0L2dhbWVfZG93bmxvYWQuemlwIiwiQ29uZGl0aW9uIjp7IklwQWRkcmVzcyI6eyJBV1M6U291cmNlSXAiOiIxOTIuMC4yLjAvMjQifSwiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE0MjY1MDAwMDB9fX1dfQ__; Domain=d111111abcdef8.cloudfront.net; Path=/; Secure; HttpOnly Set-Cookie: CloudFront-Signature=dtKhpJ3aUYxqDIwepczPiDb9NXQ_; Domain=d111111abcdef8.cloudfront.net; Path=/; Secure; HttpOnly Set-Cookie: CloudFront-Key-Pair-Id=K2JCJMDEHXQW5F; Domain=d111111abcdef8.cloudfront.net; Path=/; Secure; HttpOnly Example Example 2 You can use the Set-Cookie headers for one signed cookie when you're using an alternate domain name (example.org) in the URLs for your files. Set-Cookie: CloudFront- Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cDovL2QxMTExMTFhYmNkZWY4LmNsb3VkZnJvbnQubmV0L2dhbWVfZG93bmxvYWQuemlwIiwiQ29uZGl0aW9uIjp7IklwQWRkcmVzcyI6eyJBV1M6U291cmNlSXAiOiIxOTIuMC4yLjAvMjQifSwiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE0MjY1MDAwMDB9fX1dfQ__; Domain=example.org; Path=/; Secure; HttpOnly Set-Cookie: CloudFront-Signature=dtKhpJ3aUYxqDIwepczPiDb9NXQ_; Domain=example.org; Path=/; Secure; HttpOnly Set-Cookie: CloudFront-Key-Pair-Id=K2JCJMDEHXQW5F; Domain=example.org; Path=/; Secure; HttpOnly Example Example 3 You can use the Set-Cookie header pairs for a signed request when you're using the domain name that is associated with your distribution in the URLs for your files. Set-Cookie: CloudFront- Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cDovL2QxMTExMTFhYmNkZWY4LmNsb3VkZnJvbnQubmV0L2dhbWVfZG93bmxvYWQuemlwIiwiQ29uZGl0aW9uIjp7IklwQWRkcmVzcyI6eyJBV1M6U291cmNlSXAiOiIxOTIuMC4yLjAvMjQifSwiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE0MjY1MDAwMDB9fX1dfQ__; Domain=d111111abcdef8.cloudfront.net; Path=/; Secure; HttpOnly Set-Cookie: CloudFront-Signature=dtKhpJ3aUYxqDIwepczPiDb9NXQ_; Domain=d111111abcdef8.cloudfront.net; Path=/; Secure; HttpOnly Set-Cookie: CloudFront-Key-Pair-Id=K2JCJMDEHXQW5F; Domain=dd111111abcdef8.cloudfront.net; Path=/; Secure; HttpOnly Use signed cookies 457 Amazon CloudFront Example Example 4 Developer Guide You can use the Set-Cookie header pairs for one signed request when you're using an alternate domain name (example.org) that is associated with your distribution in the URLs for your files. Set-Cookie: CloudFront- Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cDovL2QxMTExMTFhYmNkZWY4LmNsb3VkZnJvbnQubmV0L2dhbWVfZG93bmxvYWQuemlwIiwiQ29uZGl0aW9uIjp7IklwQWRkcmVzcyI6eyJBV1M6U291cmNlSXAiOiIxOTIuMC4yLjAvMjQifSwiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE0MjY1MDAwMDB9fX1dfQ__; Domain=example.org; Path=/; Secure; HttpOnly Set-Cookie: CloudFront-Signature=dtKhpJ3aUYxqDIwepczPiDb9NXQ_; Domain=example.org; Path=/; Secure; HttpOnly Set-Cookie: CloudFront-Key-Pair-Id=K2JCJMDEHXQW5F; Domain=example.org; Path=/; Secure; HttpOnly Create a policy statement for a signed cookie that uses a custom policy To create a policy statement for a custom policy, complete the following steps. For
AmazonCloudFront_DevGuide-178
AmazonCloudFront_DevGuide.pdf
178
Set-Cookie: CloudFront-Signature=dtKhpJ3aUYxqDIwepczPiDb9NXQ_; Domain=d111111abcdef8.cloudfront.net; Path=/; Secure; HttpOnly Set-Cookie: CloudFront-Key-Pair-Id=K2JCJMDEHXQW5F; Domain=dd111111abcdef8.cloudfront.net; Path=/; Secure; HttpOnly Use signed cookies 457 Amazon CloudFront Example Example 4 Developer Guide You can use the Set-Cookie header pairs for one signed request when you're using an alternate domain name (example.org) that is associated with your distribution in the URLs for your files. Set-Cookie: CloudFront- Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cDovL2QxMTExMTFhYmNkZWY4LmNsb3VkZnJvbnQubmV0L2dhbWVfZG93bmxvYWQuemlwIiwiQ29uZGl0aW9uIjp7IklwQWRkcmVzcyI6eyJBV1M6U291cmNlSXAiOiIxOTIuMC4yLjAvMjQifSwiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE0MjY1MDAwMDB9fX1dfQ__; Domain=example.org; Path=/; Secure; HttpOnly Set-Cookie: CloudFront-Signature=dtKhpJ3aUYxqDIwepczPiDb9NXQ_; Domain=example.org; Path=/; Secure; HttpOnly Set-Cookie: CloudFront-Key-Pair-Id=K2JCJMDEHXQW5F; Domain=example.org; Path=/; Secure; HttpOnly Create a policy statement for a signed cookie that uses a custom policy To create a policy statement for a custom policy, complete the following steps. For several example policy statements that control access to files in a variety of ways, see Example policy statements for a signed cookie that uses a custom policy. To create the policy statement for a signed cookie that uses a custom policy 1. Construct the policy statement using the following JSON format. { "Statement": [ { "Resource": "URL of the file", "Condition": { "DateLessThan": { "AWS:EpochTime":required ending date and time in Unix time format and UTC }, "DateGreaterThan": { "AWS:EpochTime":optional beginning date and time in Unix time format and UTC }, "IpAddress": { "AWS:SourceIp": "optional IP address" } } } ] Use signed cookies 458 Amazon CloudFront } Note the following: • You can include only one statement. • Use UTF-8 character encoding. Developer Guide • Include all punctuation and parameter names exactly as specified. Abbreviations for parameter names are not accepted. • The order of the parameters in the Condition section doesn't matter. • For information about the values for Resource, DateLessThan, DateGreaterThan, and IpAddress, see Values that you specify in the policy statement for a custom policy for signed cookies. 2. Remove all empty spaces (including tabs and newline characters) from the policy statement. You might have to include escape characters in the string in application code. 3. Base64-encode the policy statement using MIME base64 encoding. For more information, see Section 6.8, Base64 Content-Transfer-Encoding in RFC 2045, MIME (Multipurpose Internet Mail Extensions) Part One: Format of Internet Message Bodies. 4. Replace characters that are invalid in a URL query string with characters that are valid. The following table lists invalid and valid characters. Replace these invalid characters With these valid characters + = / - (hyphen) _ (underscore) ~ (tilde) 5. Include the resulting value in your Set-Cookie header after CloudFront-Policy=. 6. Create a signature for the Set-Cookie header for CloudFront-Signature by hashing, signing, and base64-encoding the policy statement. For more information, see Create a signature for a signed cookie that uses a custom policy. Use signed cookies 459 Amazon CloudFront Developer Guide Values that you specify in the policy statement for a custom policy for signed cookies When you create a policy statement for a custom policy, you specify the following values. Resource The base URL including your query strings, if any: https://d111111abcdef8.cloudfront.net/images/horizon.jpg? size=large&license=yes Important If you omit the Resource parameter, users can access all of the files associated with any distribution that is associated with the key pair that you use to create the signed URL. You can specify only one value for Resource. Note the following: • Protocol – The value must begin with http:// or https://. • Query string parameters – If you have no query string parameters, omit the question mark. • Wildcards – You can use the wildcard character that matches zero or more characters (*) or the wild-card character that matches exactly one character (?) anywhere in the string. For example, the value: https://d111111abcdef8.cloudfront.net/*game_download.zip* would include (for example) the following files: • https://d111111abcdef8.cloudfront.net/game_download.zip • https://d111111abcdef8.cloudfront.net/example_game_download.zip? license=yes • https://d111111abcdef8.cloudfront.net/test_game_download.zip? license=temp • Alternate domain names – If you specify an alternate domain name (CNAME) in the URL, you must specify the alternate domain name when referencing the file in your webpage or application. Do not specify the Amazon S3 URL for the file. Use signed cookies 460 Amazon CloudFront DateLessThan Developer Guide The expiration date and time for the URL in Unix time format (in seconds) and Coordinated Universal Time (UTC). Do not enclose the value in quotation marks. For example, March 16, 2015 10:00 am UTC converts to 1426500000 in Unix time format. For more information, see When CloudFront checks expiration date and time in a signed cookie. DateGreaterThan (Optional) An optional start date and time for the URL in Unix time format (in seconds) and Coordinated Universal Time (UTC). Users are not allowed to access the file on or before the specified date and time. Do not enclose the value in quotation marks. IpAddress (Optional) The IP address of the client making the GET request. Note the following: • To allow any IP address to access the file, omit the IpAddress parameter. • You can specify either one IP address or one IP address range. For example, you can't set the policy
AmazonCloudFront_DevGuide-179
AmazonCloudFront_DevGuide.pdf
179
time in a signed cookie. DateGreaterThan (Optional) An optional start date and time for the URL in Unix time format (in seconds) and Coordinated Universal Time (UTC). Users are not allowed to access the file on or before the specified date and time. Do not enclose the value in quotation marks. IpAddress (Optional) The IP address of the client making the GET request. Note the following: • To allow any IP address to access the file, omit the IpAddress parameter. • You can specify either one IP address or one IP address range. For example, you can't set the policy to allow access if the client's IP address is in one of two separate ranges. • To allow access from a single IP address, you specify: "IPv4 IP address/32" • You must specify IP address ranges in standard IPv4 CIDR format (for example, 192.0.2.0/24). For more information, go to RFC 4632, Classless Inter-domain Routing (CIDR): The Internet Address Assignment and Aggregation Plan, https://tools.ietf.org/html/ rfc4632. Important IP addresses in IPv6 format, such as 2001:0db8:85a3::8a2e:0370:7334, are not supported. If you're using a custom policy that includes IpAddress, do not enable IPv6 for the distribution. If you want to restrict access to some content by IP address and support IPv6 requests for other content, you can create two distributions. For more information, see Enable IPv6 in the topic Distribution settings reference. Use signed cookies 461 Amazon CloudFront Developer Guide Example policy statements for a signed cookie that uses a custom policy The following example policy statements show how to control access to a specific file, all of the files in a directory, or all of the files associated with a key pair ID. The examples also show how to control access from an individual IP address or a range of IP addresses, and how to prevent users from using the signed cookie after a specified date and time. If you copy and paste any of these examples, remove any empty spaces (including tabs and newline characters), replace the values with your own values, and include a newline character after the closing brace ( } ). For more information, see Values that you specify in the policy statement for a custom policy for signed cookies. Topics • Example policy statement: Access one file from a range of IP addresses • Example policy statement: Access all files in a directory from a range of IP addresses • Example policy statement: Access all files associated with a key pair ID from one IP address Example policy statement: Access one file from a range of IP addresses The following example custom policy in a signed cookie specifies that a user can access the file https://d111111abcdef8.cloudfront.net/game_download.zip from IP addresses in the range 192.0.2.0/24 until January 1, 2023 10:00 am UTC: { "Statement": [ { "Resource": "https://d111111abcdef8.cloudfront.net/game_download.zip", "Condition": { "IpAddress": { "AWS:SourceIp": "192.0.2.0/24" }, "DateLessThan": { "AWS:EpochTime": 1357034400 } } } ] } Use signed cookies 462 Amazon CloudFront Developer Guide Example policy statement: Access all files in a directory from a range of IP addresses The following example custom policy allows you to create signed cookies for any file in the training directory, as indicated by the * wildcard character in the Resource parameter. Users can access the file from an IP address in the range 192.0.2.0/24 until January 1, 2013 10:00 am UTC: { "Statement": [ { "Resource": "https://d111111abcdef8.cloudfront.net/training/*", "Condition": { "IpAddress": { "AWS:SourceIp": "192.0.2.0/24" }, "DateLessThan": { "AWS:EpochTime": 1357034400 } } } ] } Each signed cookie in which you use this policy includes a base URL that identifies a specific file, for example: https://d111111abcdef8.cloudfront.net/training/orientation.pdf Example policy statement: Access all files associated with a key pair ID from one IP address The following sample custom policy allows you to set signed cookies for any file associated with any distribution, as indicated by the * wildcard character in the Resource parameter. The user must use the IP address 192.0.2.10/32. (The value 192.0.2.10/32 in CIDR notation refers to a single IP address, 192.0.2.10.) The files are available only from January 1, 2013 10:00 am UTC until January 2, 2013 10:00 am UTC: { "Statement": [ { "Resource": "https://*", "Condition": { "IpAddress": { Use signed cookies 463 Amazon CloudFront Developer Guide "AWS:SourceIp": "192.0.2.10/32" }, "DateGreaterThan": { "AWS:EpochTime": 1357034400 }, "DateLessThan": { "AWS:EpochTime": 1357120800 } } } ] } Each signed cookie in which you use this policy includes a base URL that identifies a specific file in a specific CloudFront distribution, for example: https://d111111abcdef8.cloudfront.net/training/orientation.pdf The signed cookie also includes a key pair ID, which must be associated with a trusted key group in the distribution (d111111abcdef8.cloudfront.net) that you specify in the base URL. Create a signature for a signed cookie that uses a custom policy The signature for a signed cookie that uses a custom policy is a hashed,
AmazonCloudFront_DevGuide-180
AmazonCloudFront_DevGuide.pdf
180
Developer Guide "AWS:SourceIp": "192.0.2.10/32" }, "DateGreaterThan": { "AWS:EpochTime": 1357034400 }, "DateLessThan": { "AWS:EpochTime": 1357120800 } } } ] } Each signed cookie in which you use this policy includes a base URL that identifies a specific file in a specific CloudFront distribution, for example: https://d111111abcdef8.cloudfront.net/training/orientation.pdf The signed cookie also includes a key pair ID, which must be associated with a trusted key group in the distribution (d111111abcdef8.cloudfront.net) that you specify in the base URL. Create a signature for a signed cookie that uses a custom policy The signature for a signed cookie that uses a custom policy is a hashed, signed, and base64- encoded version of the policy statement. For additional information and examples of how to hash, sign, and encode the policy statement, see: • Linux commands and OpenSSL for base64 encoding and encryption • Code examples for creating a signature for a signed URL To create a signature for a signed cookie by using a custom policy 1. Use the SHA-1 hash function and RSA to hash and sign the JSON policy statement that you created in the procedure To create the policy statement for a signed URL that uses a custom policy. Use the version of the policy statement that no longer includes empty spaces but that has not yet been base64-encoded. For the private key that is required by the hash function, use a private key whose public key is in an active trusted key group for the distribution. Use signed cookies 464 Amazon CloudFront Note Developer Guide The method that you use to hash and sign the policy statement depends on your programming language and platform. For sample code, see Code examples for creating a signature for a signed URL. 2. Remove empty spaces (including tabs and newline characters) from the hashed and signed string. 3. Base64-encode the string using MIME base64 encoding. For more information, see Section 6.8, Base64 Content-Transfer-Encoding in RFC 2045, MIME (Multipurpose Internet Mail Extensions) Part One: Format of Internet Message Bodies. 4. Replace characters that are invalid in a URL query string with characters that are valid. The following table lists invalid and valid characters. Replace these invalid characters With these valid characters + = / - (hyphen) _ (underscore) ~ (tilde) 5. Include the resulting value in the Set-Cookie header for the CloudFront-Signature= name-value pair, and return to To set a signed cookie using a custom policy to add the Set- Cookie header for CloudFront-Key-Pair-Id. Create signed cookies using PHP The following code example is similar to the example in the Create a URL signature using PHP in that it creates a link to a video. However, instead of signing the URL in the code, this example signs the cookies with the create_signed_cookies() function. The client-side player uses the cookies to authenticate each request to the CloudFront distribution. This approach is useful to stream content, such as HTTP Live Streaming (HLS) or Dynamic Adaptive Streaming over HTTP (DASH), where the client needs to make multiple requests to retrieve Use signed cookies 465 Amazon CloudFront Developer Guide the manifest, segments, and related playback assets. By using signed cookies, the client can authenticate each request without needing to generate a new signed URL for each segment. Note • Creating a URL signature is just one part of the process of serving private content using signed cookies. For more information, see Use signed cookies. Topics • Create the RSA SHA-1 signature • Create the signed cookies • Full code The following sections breaks down the code example into individual parts. You can find the complete code sample below. Create the RSA SHA-1 signature This code example does the following: 1. The function rsa_sha1_sign hashes and signs the policy statement. The arguments required are a policy statement and the private key that corresponds with a public key that’s in a trusted key group for your distribution. 2. Next, the url_safe_base64_encode function creates a URL-safe version of the signature. function rsa_sha1_sign($policy, $private_key_filename) { $signature = ""; $fp = fopen($private_key_filename, "r"); $priv_key = fread($fp, 8192); fclose($fp); $pkeyid = openssl_get_privatekey($priv_key); openssl_sign($policy, $signature, $pkeyid); openssl_free_key($pkeyid); return $signature; } function url_safe_base64_encode($value) { Use signed cookies 466 Amazon CloudFront Developer Guide $encoded = base64_encode($value); return str_replace( array('+', '=', '/'), array('-', '_', '~'), $encoded); } Create the signed cookies The following code constructs a creates the signed cookies, using the following cookie attributes: CloudFront-Expires, CloudFront-Signature, and CloudFront-Key-Pair-Id. The code uses a custom policy. function create_signed_cookies($resource, $private_key_filename, $key_pair_id, $expires, $client_ip = null) { $policy = array( 'Statement' => array( array( 'Resource' => $resource, 'Condition' => array( 'DateLessThan' => array('AWS:EpochTime' => $expires) ) ) ) ); if ($client_ip) { $policy['Statement'][0]['Condition']['IpAddress'] = array('AWS:SourceIp' => $client_ip . '/32'); } $policy = json_encode($policy); $encoded_policy = url_safe_base64_encode($policy); $signature = rsa_sha1_sign($policy, $private_key_filename); $encoded_signature = url_safe_base64_encode($signature); return array( 'CloudFront-Policy' => $encoded_policy, 'CloudFront-Signature' => $encoded_signature, 'CloudFront-Key-Pair-Id' => $key_pair_id );
AmazonCloudFront_DevGuide-181
AmazonCloudFront_DevGuide.pdf
181
array('-', '_', '~'), $encoded); } Create the signed cookies The following code constructs a creates the signed cookies, using the following cookie attributes: CloudFront-Expires, CloudFront-Signature, and CloudFront-Key-Pair-Id. The code uses a custom policy. function create_signed_cookies($resource, $private_key_filename, $key_pair_id, $expires, $client_ip = null) { $policy = array( 'Statement' => array( array( 'Resource' => $resource, 'Condition' => array( 'DateLessThan' => array('AWS:EpochTime' => $expires) ) ) ) ); if ($client_ip) { $policy['Statement'][0]['Condition']['IpAddress'] = array('AWS:SourceIp' => $client_ip . '/32'); } $policy = json_encode($policy); $encoded_policy = url_safe_base64_encode($policy); $signature = rsa_sha1_sign($policy, $private_key_filename); $encoded_signature = url_safe_base64_encode($signature); return array( 'CloudFront-Policy' => $encoded_policy, 'CloudFront-Signature' => $encoded_signature, 'CloudFront-Key-Pair-Id' => $key_pair_id ); } Use signed cookies 467 Amazon CloudFront Developer Guide For more information, see Set signed cookies using a custom policy. Full code The following example code provides a complete demonstration of creating CloudFront signed cookies with PHP. You can download the full example from the demo-php.zip file. In the following example, you can modify the $policy Condition element to allow both IPv4 and IPv6 address ranges. For an example, see Using IPv6 addresses in IAM policies in the Amazon Simple Storage Service User Guide. <?php function rsa_sha1_sign($policy, $private_key_filename) { $signature = ""; $fp = fopen($private_key_filename, "r"); $priv_key = fread($fp, 8192); fclose($fp); $pkeyid = openssl_get_privatekey($priv_key); openssl_sign($policy, $signature, $pkeyid); openssl_free_key($pkeyid); return $signature; } function url_safe_base64_encode($value) { $encoded = base64_encode($value); return str_replace( array('+', '=', '/'), array('-', '_', '~'), $encoded); } function create_signed_cookies($resource, $private_key_filename, $key_pair_id, $expires, $client_ip = null) { $policy = array( 'Statement' => array( array( 'Resource' => $resource, 'Condition' => array( 'DateLessThan' => array('AWS:EpochTime' => $expires) ) ) ) Use signed cookies 468 Amazon CloudFront ); if ($client_ip) { Developer Guide $policy['Statement'][0]['Condition']['IpAddress'] = array('AWS:SourceIp' => $client_ip . '/32'); } $policy = json_encode($policy); $encoded_policy = url_safe_base64_encode($policy); $signature = rsa_sha1_sign($policy, $private_key_filename); $encoded_signature = url_safe_base64_encode($signature); return array( 'CloudFront-Policy' => $encoded_policy, 'CloudFront-Signature' => $encoded_signature, 'CloudFront-Key-Pair-Id' => $key_pair_id ); } $private_key_filename = '/home/test/secure/example-priv-key.pem'; $key_pair_id = 'K2JCJMDEHXQW5F'; $base_url = 'https://d1234.cloudfront.net'; $expires = time() + 3600; // 1 hour from now // Get the viewer real IP from the x-forward-for header as $_SERVER['REMOTE_ADDR'] will return viewer facing IP. An alternative option is to use CloudFront-Viewer- Address header. Note that this header is a trusted CloudFront immutable header. Example format: IP:PORT ("CloudFront-Viewer-Address": "1.2.3.4:12345") $client_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // For HLS manifest and segments (using wildcard) $hls_resource = $base_url . '/sign/*'; $signed_cookies = create_signed_cookies($hls_resource, $private_key_filename, $key_pair_id, $expires, $client_ip); // Set the cookies $cookie_domain = parse_url($base_url, PHP_URL_HOST); foreach ($signed_cookies as $name => $value) { setcookie($name, $value, $expires, '/', $cookie_domain, true, true); } Use signed cookies 469 Amazon CloudFront Developer Guide ?> <!DOCTYPE html> <html> <head> <title>CloudFront Signed HLS Stream with Cookies</title> </head> <body> <h1>Amazon CloudFront Signed HLS Stream with Cookies</h1> <h2>Expires at <?php echo gmdate('Y-m-d H:i:s T', $expires); ?> only viewable by IP <?php echo $client_ip; ?></h2> <div id='hls-video'> <video id="video" width="640" height="360" controls></video> </div> <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script> <script> var video = document.getElementById('video'); var manifestUrl = '<?php echo $base_url; ?>/sign/manifest.m3u8'; if (Hls.isSupported()) { var hls = new Hls(); hls.loadSource(manifestUrl); hls.attachMedia(video); } else if (video.canPlayType('application/vnd.apple.mpegurl')) { video.src = manifestUrl; } </script> </body> </html> Instead of using signed cookies, you can use signed URLs. For more information, see Create a URL signature using PHP. Linux commands and OpenSSL for base64 encoding and encryption You can use the following Linux command-line command and OpenSSL to hash and sign the policy statement, base64-encode the signature, and replace characters that are not valid in URL query string parameters with characters that are valid. Linux commands and OpenSSL for base64 encoding and encryption 470 Amazon CloudFront Developer Guide For information about OpenSSL, go to https://www.openssl.org. cat policy | tr -d "\n" | tr -d " \t\n\r" | openssl sha1 -sign private_key.pem | openssl base64 -A | tr -- '+=/' '-_~' In the preceding command: • cat reads the policy file • tr -d "\n" | tr -d " \t\n\r" removes the empty spaces and newline character that were added by cat • OpenSSL hashes the file using SHA-1 and signs it using RSA and the private key file private_key.pem • OpenSSL base64-encodes the hashed and signed policy statement • tr replaces characters that are not valid in URL query string parameters with characters that are valid For more code examples that demonstrate creating a signature, see Code examples for creating a signature for a signed URL. Code examples for creating a signature for a signed URL This section includes downloadable application examples that demonstrate how to create signatures for signed URLs. Examples are available in Perl, PHP, C#, and Java. You can use any of the examples to create signed URLs. The Perl script runs on Linux and macOS platforms. The PHP example will work on any server that runs PHP. The C# example uses the .NET Framework. For example code in JavaScript (Node.js), see Creating Amazon CloudFront Signed URLs in Node.js on the AWS Developer Blog. For example code
AmazonCloudFront_DevGuide-182
AmazonCloudFront_DevGuide.pdf
182
a signature for a signed URL. Code examples for creating a signature for a signed URL This section includes downloadable application examples that demonstrate how to create signatures for signed URLs. Examples are available in Perl, PHP, C#, and Java. You can use any of the examples to create signed URLs. The Perl script runs on Linux and macOS platforms. The PHP example will work on any server that runs PHP. The C# example uses the .NET Framework. For example code in JavaScript (Node.js), see Creating Amazon CloudFront Signed URLs in Node.js on the AWS Developer Blog. For example code in Python, see Generate a signed URL for Amazon CloudFront in the AWS SDK for Python (Boto3) API Reference and this example code in the Boto3 GitHub repository. Topics • Create a URL signature using Perl • Create a URL signature using PHP • Create a URL signature using C# and the .NET Framework • Create a URL signature using Java Code examples for signed URLs 471 Amazon CloudFront Developer Guide Create a URL signature using Perl This section includes a Perl script for Linux/Mac platforms that you can use to create the signature for private content. To create the signature, run the script with command line arguments that specify the CloudFront URL, the path to the private key of the signer, the key ID, and an expiration date for the URL. The tool can also decode signed URLs. Note Creating a URL signature is just one part of the process of serving private content using a signed URL. For more information about the end-to-end process, see Use signed URLs. Topics • Source for the Perl script to create a signed URL Source for the Perl script to create a signed URL The following Perl source code can be used to create a signed URL for CloudFront. Comments in the code include information about the command line switches and the features of the tool. #!/usr/bin/perl -w # Copyright 2008 Amazon Technologies, Inc. Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. You may obtain a copy of the License at: # # https://aws.amazon.com/apache2.0 # # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and limitations under the License. =head1 cfsign.pl cfsign.pl - A tool to generate and verify Amazon CloudFront signed URLs =head1 SYNOPSIS Code examples for signed URLs 472 Amazon CloudFront Developer Guide This script uses an existing RSA key pair to sign and verify Amazon CloudFront signed URLs View the script source for details as to which CPAN packages are required beforehand. For help, try: cfsign.pl --help URL signing examples: cfsign.pl --action encode --url https://images.my-website.com/gallery1.zip --policy sample_policy.json --private-key privkey.pem --key-pair-id mykey cfsign.pl --action encode --url https://images.my-website.com/gallery1.zip --expires 1257439868 --private-key privkey.pem --key-pair-id mykey URL decode example: cfsign.pl --action decode --url "http//mydist.cloudfront.net/?Signature=AGO- PgxkYo99MkJFHvjfGXjG1QDEXeaDb4Qtzmy85wqyJjK7eKojQWa4BCRcow__&Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiaHR0cDovLypicmFkbS5qcGciLCJDb25kaXRpb24iOnsiSXBBZGRyZXNzIjp7IkFXUzpTb3VyY2VJcCI6IjEwLjUyLjE3LjkvMCJ9LCJEYXRlR3JlYXRlclRoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTI1MjUyMDgzMH19fV19Cg__&Key- Pair-Id=mykey" To generate an RSA key pair, you can use openssl and the following commands: # Generate a 2048 bit key pair openssl genrsa -out private-key.pem 2048 openssl rsa -in private-key.pem -pubout -out public-key.pem =head1 OPTIONS =over 8 =item B<--help> Print a help message and exits. =item B<--action> [action] The action to execute. action can be one of: encode - Generate a signed URL (using a canned policy or a user policy) Code examples for signed URLs 473 Amazon CloudFront Developer Guide decode - Decode a signed URL =item B<--url> The URL to en/decode =item B<--stream> The stream to en/decode =item B<--private-key> The path to your private key. =item B<--key-pair-id> The key pair identifier. =item B<--policy> The CloudFront policy document. =item B<--expires> The Unix epoch time when the URL is to expire. If both this option and the --policy option are specified, --policy will be used. Otherwise, this option alone will use a canned policy. =back =cut use strict; use warnings; # you might need to use CPAN to get these modules. # run perl -MCPAN -e "install <module>" to get them. # The openssl command line will also need to be in your $PATH. use File::Temp qw/tempfile/; use File::Slurp; use Getopt::Long; use IPC::Open2; use MIME::Base64 qw(encode_base64 decode_base64); use Pod::Usage; Code examples for signed URLs 474 Amazon CloudFront use URI; my $CANNED_POLICY = '{"Statement":[{"Resource":"<RESOURCE>","Condition":{"DateLessThan": {"AWS:EpochTime":<EXPIRES>}}}]}'; Developer Guide my $POLICY_PARAM = "Policy"; my $EXPIRES_PARAM = "Expires"; my $SIGNATURE_PARAM = "Signature"; my $KEY_PAIR_ID_PARAM = "Key-Pair-Id"; my $verbose = 0; my $policy_filename = ""; my $expires_epoch = 0; my $action = ""; my $help = 0; my $key_pair_id = ""; my $url = ""; my $stream = ""; my $private_key_filename = ""; my $result = GetOptions("action=s" => \$action, "policy=s" => \$policy_filename, "expires=i" => \$expires_epoch, "private-key=s" => \$private_key_filename, "key-pair-id=s" => \$key_pair_id, "verbose" => \$verbose, "help" =>
AmazonCloudFront_DevGuide-183
AmazonCloudFront_DevGuide.pdf
183
use IPC::Open2; use MIME::Base64 qw(encode_base64 decode_base64); use Pod::Usage; Code examples for signed URLs 474 Amazon CloudFront use URI; my $CANNED_POLICY = '{"Statement":[{"Resource":"<RESOURCE>","Condition":{"DateLessThan": {"AWS:EpochTime":<EXPIRES>}}}]}'; Developer Guide my $POLICY_PARAM = "Policy"; my $EXPIRES_PARAM = "Expires"; my $SIGNATURE_PARAM = "Signature"; my $KEY_PAIR_ID_PARAM = "Key-Pair-Id"; my $verbose = 0; my $policy_filename = ""; my $expires_epoch = 0; my $action = ""; my $help = 0; my $key_pair_id = ""; my $url = ""; my $stream = ""; my $private_key_filename = ""; my $result = GetOptions("action=s" => \$action, "policy=s" => \$policy_filename, "expires=i" => \$expires_epoch, "private-key=s" => \$private_key_filename, "key-pair-id=s" => \$key_pair_id, "verbose" => \$verbose, "help" => \$help, "url=s" => \$url, "stream=s" => \$stream, ); if ($help or !$result) { pod2usage(1); exit; } if ($url eq "" and $stream eq "") { print STDERR "Must include a stream or a URL to encode or decode with the --stream or --url option\n"; exit; } if ($url ne "" and $stream ne "") { Code examples for signed URLs 475 Amazon CloudFront Developer Guide print STDERR "Only one of --url and --stream may be specified\n"; exit; } if ($url ne "" and !is_url_valid($url)) { exit; } if ($stream ne "") { exit unless is_stream_valid($stream); # The signing mechanism is identical, so from here on just pretend we're # dealing with a URL $url = $stream; } if ($action eq "encode") { # The encode action will generate a private content URL given a base URL, # a policy file (or an expires timestamp) and a key pair id parameter my $private_key; my $public_key; my $public_key_file; my $policy; if ($policy_filename eq "") { if ($expires_epoch == 0) { print STDERR "Must include policy filename with --policy argument or an expires" . "time using --expires\n"; } $policy = $CANNED_POLICY; $policy =~ s/<EXPIRES>/$expires_epoch/g; $policy =~ s/<RESOURCE>/$url/g; } else { if (! -e $policy_filename) { print STDERR "Policy file $policy_filename does not exist\n"; exit; } $expires_epoch = 0; # ignore if set $policy = read_file($policy_filename); } if ($private_key_filename eq "") { Code examples for signed URLs 476 Amazon CloudFront Developer Guide print STDERR "You must specific the path to your private key file with -- private-key\n"; exit; } if (! -e $private_key_filename) { print STDERR "Private key file $private_key_filename does not exist\n"; exit; } if ($key_pair_id eq "") { print STDERR "You must specify a key pair id with --key-pair-id\n"; exit; } my $encoded_policy = url_safe_base64_encode($policy); my $signature = rsa_sha1_sign($policy, $private_key_filename); my $encoded_signature = url_safe_base64_encode($signature); my $generated_url = create_url($url, $encoded_policy, $encoded_signature, $key_pair_id, $expires_epoch); if ($stream ne "") { print "Encoded stream (for use within a swf):\n" . $generated_url . "\n"; print "Encoded and escaped stream (for use on a webpage):\n" . escape_url_for_webpage($generated_url) . "\n"; } else { print "Encoded URL:\n" . $generated_url . "\n"; } } elsif ($action eq "decode") { my $decoded = decode_url($url); if (!$decoded) { print STDERR "Improperly formed URL\n"; exit; } print_decoded_url($decoded); } else { # No action specified, print help. But only if this is run as a program (caller will be empty) pod2usage(1) unless caller(); } Code examples for signed URLs 477 Amazon CloudFront Developer Guide # Decode a private content URL into its component parts sub decode_url { my $url = shift; if ($url =~ /(.*)\?(.*)/) { my $base_url = $1; my $params = $2; my @unparsed_params = split(/&/, $params); my %params = (); foreach my $param (@unparsed_params) { my ($key, $val) = split(/=/, $param); $params{$key} = $val; } my $encoded_signature = ""; if (exists $params{$SIGNATURE_PARAM}) { $encoded_signature = $params{"Signature"}; } else { print STDERR "Missing Signature URL parameter\n"; return 0; } my $encoded_policy = ""; if (exists $params{$POLICY_PARAM}) { $encoded_policy = $params{$POLICY_PARAM}; } else { if (!exists $params{$EXPIRES_PARAM}) { print STDERR "Either the Policy or Expires URL parameter needs to be specified\n"; return 0; } my $expires = $params{$EXPIRES_PARAM}; my $policy = $CANNED_POLICY; $policy =~ s/<EXPIRES>/$expires/g; my $url_without_cf_params = $url; $url_without_cf_params =~ s/$SIGNATURE_PARAM=[^&]*&?//g; $url_without_cf_params =~ s/$POLICY_PARAM=[^&]*&?//g; $url_without_cf_params =~ s/$EXPIRES_PARAM=[^&]*&?//g; $url_without_cf_params =~ s/$KEY_PAIR_ID_PARAM=[^&]*&?//g; Code examples for signed URLs 478 Amazon CloudFront Developer Guide if ($url_without_cf_params =~ /(.*)\?$/) { $url_without_cf_params = $1; } $policy =~ s/<RESOURCE>/$url_without_cf_params/g; $encoded_policy = url_safe_base64_encode($policy); } my $key = ""; if (exists $params{$KEY_PAIR_ID_PARAM}) { $key = $params{$KEY_PAIR_ID_PARAM}; } else { print STDERR "Missing $KEY_PAIR_ID_PARAM parameter\n"; return 0; } my $policy = url_safe_base64_decode($encoded_policy); my %ret = (); $ret{"base_url"} = $base_url; $ret{"policy"} = $policy; $ret{"key"} = $key; return \%ret; } else { return 0; } } # Print a decoded URL out sub print_decoded_url { my $decoded = shift; print "Base URL: \n" . $decoded->{"base_url"} . "\n"; print "Policy: \n" . $decoded->{"policy"} . "\n"; print "Key: \n" . $decoded->{"key"} . "\n"; } # Encode a string with base 64 encoding and replace some invalid URL characters sub url_safe_base64_encode { my ($value) = @_; my $result = encode_base64($value); Code examples for signed URLs 479 Amazon CloudFront $result =~ tr|+=/|-_~|; return $result; } Developer Guide # Decode
AmazonCloudFront_DevGuide-184
AmazonCloudFront_DevGuide.pdf
184
%ret = (); $ret{"base_url"} = $base_url; $ret{"policy"} = $policy; $ret{"key"} = $key; return \%ret; } else { return 0; } } # Print a decoded URL out sub print_decoded_url { my $decoded = shift; print "Base URL: \n" . $decoded->{"base_url"} . "\n"; print "Policy: \n" . $decoded->{"policy"} . "\n"; print "Key: \n" . $decoded->{"key"} . "\n"; } # Encode a string with base 64 encoding and replace some invalid URL characters sub url_safe_base64_encode { my ($value) = @_; my $result = encode_base64($value); Code examples for signed URLs 479 Amazon CloudFront $result =~ tr|+=/|-_~|; return $result; } Developer Guide # Decode a string with base 64 encoding. URL-decode the string first # followed by reversing any special character ("+=/") translation. sub url_safe_base64_decode { my ($value) = @_; $value =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg; $value =~ tr|-_~|+=/|; my $result = decode_base64($value); return $result; } # Create a private content URL sub create_url { my ($path, $policy, $signature, $key_pair_id, $expires) = @_; my $result; my $separator = $path =~ /\?/ ? '&' : '?'; if ($expires) { $result = "$path$separator$EXPIRES_PARAM=$expires&$SIGNATURE_PARAM=$signature& $KEY_PAIR_ID_PARAM=$key_pair_id"; } else { $result = "$path$separator$POLICY_PARAM=$policy&$SIGNATURE_PARAM=$signature& $KEY_PAIR_ID_PARAM=$key_pair_id"; } $result =~ s/\n//g; return $result; } # Sign a document with given private key file. # The first argument is the document to sign # The second argument is the name of the private key file sub rsa_sha1_sign { my ($to_sign, $pvkFile) = @_; print "openssl sha1 -sign $pvkFile $to_sign\n"; return write_to_program($pvkFile, $to_sign); Code examples for signed URLs 480 Amazon CloudFront } Developer Guide # Helper function to write data to a program sub write_to_program { my ($keyfile, $data) = @_; unlink "temp_policy.dat" if (-e "temp_policy.dat"); unlink "temp_sign.dat" if (-e "temp_sign.dat"); write_file("temp_policy.dat", $data); system("openssl dgst -sha1 -sign \"$keyfile\" -out temp_sign.dat temp_policy.dat"); my $output = read_file("temp_sign.dat"); return $output; } # Read a file into a string and return the string sub read_file { my ($file) = @_; open(INFILE, "<$file") or die("Failed to open $file: $!"); my $str = join('', <INFILE>); close INFILE; return $str; } sub is_url_valid { my ($url) = @_; # HTTP distributions start with http[s]:// and are the correct thing to sign if ($url =~ /^https?:\/\//) { return 1; } else { print STDERR "CloudFront requires absolute URLs for HTTP distributions\n"; return 0; } } sub is_stream_valid { my ($stream) = @_; if ($stream =~ /^rtmp:\/\// or $stream =~ /^\/?cfx\/st/) { Code examples for signed URLs 481 Amazon CloudFront Developer Guide print STDERR "Streaming distributions require that only the stream name is signed.\n"; print STDERR "The stream name is everything after, but not including, cfx/st/ \n"; return 0; } else { return 1; } } # flash requires that the query parameters in the stream name are url # encoded when passed in through javascript, etc. This sub handles the minimal # required url encoding. sub escape_url_for_webpage { my ($url) = @_; $url =~ s/\?/%3F/g; $url =~ s/=/%3D/g; $url =~ s/&/%26/g; return $url; } 1; Create a URL signature using PHP Any web server that runs PHP can use this PHP example code to create policy statements and signatures for private CloudFront distributions. The full example creates a functioning webpage with signed URL links that play a video stream using CloudFront streaming. You can download the full example from the demo-php.zip file. Notes • Creating a URL signature is just one part of the process of serving private content using a signed URL. For more information about the entire process, see Use signed URLs. • You can also create signed URLs by using the UrlSigner class in the AWS SDK for PHP. For more information, see Class UrlSigner in the AWS SDK for PHP API Reference. Topics Code examples for signed URLs 482 Amazon CloudFront Developer Guide • Create the RSA SHA-1 signature • Create a canned policy • Create a custom policy • Full code example The following sections breaks down the code example into individual parts. You can find the Full code example below. Create the RSA SHA-1 signature This code example does the following: • The function rsa_sha1_sign hashes and signs the policy statement. The arguments required are a policy statement and the private key that corresponds with a public key that’s in a trusted key group for your distribution. • Next, the url_safe_base64_encode function creates a URL-safe version of the signature. function rsa_sha1_sign($policy, $private_key_filename) { $signature = ""; // load the private key $fp = fopen($private_key_filename, "r"); $priv_key = fread($fp, 8192); fclose($fp); $pkeyid = openssl_get_privatekey($priv_key); // compute signature openssl_sign($policy, $signature, $pkeyid); // free the key from memory openssl_free_key($pkeyid); return $signature; } function url_safe_base64_encode($value) { $encoded = base64_encode($value); // replace unsafe characters +, = and / with // the safe characters -, _ and ~ return str_replace( Code examples for signed URLs 483 Amazon CloudFront Developer Guide array('+', '=', '/'), array('-', '_', '~'), $encoded); } The following code snippet uses the functions
AmazonCloudFront_DevGuide-185
AmazonCloudFront_DevGuide.pdf
185
the url_safe_base64_encode function creates a URL-safe version of the signature. function rsa_sha1_sign($policy, $private_key_filename) { $signature = ""; // load the private key $fp = fopen($private_key_filename, "r"); $priv_key = fread($fp, 8192); fclose($fp); $pkeyid = openssl_get_privatekey($priv_key); // compute signature openssl_sign($policy, $signature, $pkeyid); // free the key from memory openssl_free_key($pkeyid); return $signature; } function url_safe_base64_encode($value) { $encoded = base64_encode($value); // replace unsafe characters +, = and / with // the safe characters -, _ and ~ return str_replace( Code examples for signed URLs 483 Amazon CloudFront Developer Guide array('+', '=', '/'), array('-', '_', '~'), $encoded); } The following code snippet uses the functions get_canned_policy_stream_name() and get_custom_policy_stream_name() to create a canned and custom policy. CloudFront uses the policies to create the URL for streaming the video, including specifying the expiration time. You can then used a canned policy or a custom policy to determine how to manage access to your content. For more information about which one to choose, see the Decide to use canned or custom policies for signed URLs section. Create a canned policy The following example code constructs a canned policy statement for the signature. Note The $expires variable is a date/time stamp that must be an integer, not a string. function get_canned_policy_stream_name($video_path, $private_key_filename, $key_pair_id, $expires) { // this policy is well known by CloudFront, but you still need to sign it, since it contains your parameters $canned_policy = '{"Statement":[{"Resource":"' . $video_path . '","Condition": {"DateLessThan":{"AWS:EpochTime":'. $expires . '}}}]}'; // the policy contains characters that cannot be part of a URL, so we base64 encode it $encoded_policy = url_safe_base64_encode($canned_policy); // sign the original policy, not the encoded version $signature = rsa_sha1_sign($canned_policy, $private_key_filename); // make the signature safe to be included in a URL $encoded_signature = url_safe_base64_encode($signature); // combine the above into a stream name $stream_name = create_stream_name($video_path, null, $encoded_signature, $key_pair_id, $expires); // URL-encode the query string characters return $stream_name; } Code examples for signed URLs 484 Amazon CloudFront Developer Guide For more information about canned policies, see Create a signed URL using a canned policy. Create a custom policy The following example code constructs a custom policy statement for the signature. function get_custom_policy_stream_name($video_path, $private_key_filename, $key_pair_id, $policy) { // the policy contains characters that cannot be part of a URL, so we base64 encode it $encoded_policy = url_safe_base64_encode($policy); // sign the original policy, not the encoded version $signature = rsa_sha1_sign($policy, $private_key_filename); // make the signature safe to be included in a URL $encoded_signature = url_safe_base64_encode($signature); // combine the above into a stream name $stream_name = create_stream_name($video_path, $encoded_policy, $encoded_signature, $key_pair_id, null); // URL-encode the query string characters return $stream_name; } For more information about custom policies, see Create a signed URL using a custom policy. Full code example The following example code provides a complete demonstration of creating CloudFront signed URLs with PHP. You can download the full example from the demo-php.zip file. In the following example, you can modify the $policy Condition element to allow both IPv4 and IPv6 address ranges. For an example, see Using IPv6 addresses in IAM policies in the Amazon Simple Storage Service User Guide. <?php function rsa_sha1_sign($policy, $private_key_filename) { $signature = ""; // load the private key $fp = fopen($private_key_filename, "r"); $priv_key = fread($fp, 8192); fclose($fp); Code examples for signed URLs 485 Amazon CloudFront Developer Guide $pkeyid = openssl_get_privatekey($priv_key); // compute signature openssl_sign($policy, $signature, $pkeyid); // free the key from memory openssl_free_key($pkeyid); return $signature; } function url_safe_base64_encode($value) { $encoded = base64_encode($value); // replace unsafe characters +, = and / with the safe characters -, _ and ~ return str_replace( array('+', '=', '/'), array('-', '_', '~'), $encoded); } function create_stream_name($stream, $policy, $signature, $key_pair_id, $expires) { $result = $stream; // if the stream already contains query parameters, attach the new query parameters to the end // otherwise, add the query parameters $separator = strpos($stream, '?') == FALSE ? '?' : '&'; // the presence of an expires time means we're using a canned policy if($expires) { $result .= $separator . "Expires=" . $expires . "&Signature=" . $signature . "&Key-Pair-Id=" . $key_pair_id; } // not using a canned policy, include the policy itself in the stream name else { $result .= $separator . "Policy=" . $policy . "&Signature=" . $signature . "&Key-Pair-Id=" . $key_pair_id; } // new lines would break us, so remove them return str_replace('\n', '', $result); } function get_canned_policy_stream_name($video_path, $private_key_filename, $key_pair_id, $expires) { Code examples for signed URLs 486 Amazon CloudFront Developer Guide // this policy is well known by CloudFront, but you still need to sign it, since it contains your parameters $canned_policy = '{"Statement":[{"Resource":"' . $video_path . '","Condition": {"DateLessThan":{"AWS:EpochTime":'. $expires . '}}}]}'; // the policy contains characters that cannot be part of a URL, so we base64 encode it $encoded_policy = url_safe_base64_encode($canned_policy); // sign the original policy, not the encoded version $signature = rsa_sha1_sign($canned_policy, $private_key_filename); // make the signature safe to be included in a URL $encoded_signature
AmazonCloudFront_DevGuide-186
AmazonCloudFront_DevGuide.pdf
186
so remove them return str_replace('\n', '', $result); } function get_canned_policy_stream_name($video_path, $private_key_filename, $key_pair_id, $expires) { Code examples for signed URLs 486 Amazon CloudFront Developer Guide // this policy is well known by CloudFront, but you still need to sign it, since it contains your parameters $canned_policy = '{"Statement":[{"Resource":"' . $video_path . '","Condition": {"DateLessThan":{"AWS:EpochTime":'. $expires . '}}}]}'; // the policy contains characters that cannot be part of a URL, so we base64 encode it $encoded_policy = url_safe_base64_encode($canned_policy); // sign the original policy, not the encoded version $signature = rsa_sha1_sign($canned_policy, $private_key_filename); // make the signature safe to be included in a URL $encoded_signature = url_safe_base64_encode($signature); // combine the above into a stream name $stream_name = create_stream_name($video_path, null, $encoded_signature, $key_pair_id, $expires); // URL-encode the query string characters return $stream_name; } function get_custom_policy_stream_name($video_path, $private_key_filename, $key_pair_id, $policy) { // the policy contains characters that cannot be part of a URL, so we base64 encode it $encoded_policy = url_safe_base64_encode($policy); // sign the original policy, not the encoded version $signature = rsa_sha1_sign($policy, $private_key_filename); // make the signature safe to be included in a URL $encoded_signature = url_safe_base64_encode($signature); // combine the above into a stream name $stream_name = create_stream_name($video_path, $encoded_policy, $encoded_signature, $key_pair_id, null); // URL-encode the query string characters return $stream_name; } // Path to your private key. Be very careful that this file is not accessible // from the web! $private_key_filename = '/home/test/secure/example-priv-key.pem'; $key_pair_id = 'K2JCJMDEHXQW5F'; Code examples for signed URLs 487 Amazon CloudFront Developer Guide // Make sure you have "Restrict viewer access" enabled on this path behaviour and using the above Trusted key groups (recommended). $video_path = 'https://example.com/secure/example.mp4'; $expires = time() + 300; // 5 min from now $canned_policy_stream_name = get_canned_policy_stream_name($video_path, $private_key_filename, $key_pair_id, $expires); // Get the viewer real IP from the x-forward-for header as $_SERVER['REMOTE_ADDR'] will return viewer facing IP. An alternative option is to use CloudFront-Viewer- Address header. Note that this header is a trusted CloudFront immutable header. Example format: IP:PORT ("CloudFront-Viewer-Address": "1.2.3.4:12345") $client_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; $policy = '{'. '"Statement":['. '{'. '"Resource":"'. $video_path . '",'. '"Condition":{'. '"IpAddress":{"AWS:SourceIp":"' . $client_ip . '/32"},'. '"DateLessThan":{"AWS:EpochTime":' . $expires . '}'. '}'. '}'. ']' . '}'; $custom_policy_stream_name = get_custom_policy_stream_name($video_path, $private_key_filename, $key_pair_id, $policy); ?> <html> <head> <title>CloudFront</title> </head> <body> <h1>Amazon CloudFront</h1> <h2>Canned Policy</h2> <h3>Expires at <?php echo gmdate('Y-m-d H:i:s T', $expires); ?></h3> <br /> <div id='canned'>The canned policy video will be here: <br> Code examples for signed URLs 488 Amazon CloudFront Developer Guide <video width="640" height="360" autoplay muted controls> <source src="<?php echo $canned_policy_stream_name; ?>" type="video/mp4"> Your browser does not support the video tag. </video> </div> <h2>Custom Policy</h2> <h3>Expires at <?php echo gmdate('Y-m-d H:i:s T', $expires); ?> only viewable by IP <?php echo $client_ip; ?></h3> <div id='custom'>The custom policy video will be here: <br> <video width="640" height="360" autoplay muted controls> <source src="<?php echo $custom_policy_stream_name; ?>" type="video/mp4"> Your browser does not support the video tag. </video> </div> </body> </html> For additional URL signature examples, see the following topics: • Create a URL signature using Perl • Create a URL signature using C# and the .NET Framework • Create a URL signature using Java Instead of using signed URLs to create the signature, you can use signed cookies. For more information, see Create signed cookies using PHP. Create a URL signature using C# and the .NET Framework The C# examples in this section implement an example application that demonstrates how to create the signatures for CloudFront private distributions using canned and custom policy statements. The examples include utility functions based on the AWS SDK for .NET that can be useful in .NET applications. You can also create signed URLs and signed cookies by using the SDK for .NET. In the SDK for .NET API Reference, see the following topics: • Signed URLs – AmazonCloudFrontUrlSigner Code examples for signed URLs 489 Amazon CloudFront Developer Guide • Signed cookies – AmazonCloudFrontCookieSigner To download the code, go to Signature Code in C#. Notes • The AmazonCloudFrontUrlSigner and AmazonCloudFrontCookieSigner classes have moved to a separate package. For more information about using them, see CookieSigner and UrlSigner in the AWS SDK for .NET (V4) Developer Guide. • Creating a URL signature is just one part of the process of serving private content using a signed URL. For more information, see Use signed URLs. For more information about using signed cookies, see Use signed cookies. Use an RSA key in the .NET Framework To use an RSA key in the .NET Framework, you must convert the AWS supplied .pem file to the XML format that the .NET Framework uses. After conversion, the RSA private key file is in the following format: Example : RSA private key in the XML .NET Framework format <RSAKeyValue> <Modulus> wO5IvYCP5UcoCKDo1dcspoMehWBZcyfs9QEzGi6Oe5y+ewGr1oW+vB2GPB ANBiVPcUHTFWhwaIBd3oglmF0lGQljP/jOfmXHUK2kUUnLnJp+oOBL2NiuFtqcW6h/L5lIpD8Yq+NRHg Ty4zDsyr2880MvXv88yEFURCkqEXAMPLE= </Modulus> <Exponent>AQAB</Exponent> <P> 5bmKDaTz npENGVqz4Cea8XPH+sxt+2VaAwYnsarVUoSBeVt8WLloVuZGG9IZYmH5KteXEu7fZveYd9UEXAMPLE== </P> <Q> 1v9l/WN1a1N3rOK4VGoCokx7kR2SyTMSbZgF9IWJNOugR/WZw7HTnjipO3c9dy1Ms9pUKwUF4 6d7049EXAMPLE== </Q> <DP> RgrSKuLWXMyBH+/l1Dx/I4tXuAJIrlPyo+VmiOc7b5NzHptkSHEPfR9s1 OK0VqjknclqCJ3Ig86OMEtEXAMPLE== Code examples for signed URLs 490 Amazon CloudFront </DP> <DQ> pjPjvSFw+RoaTu0pgCA/jwW/FGyfN6iim1RFbkT4 z49DZb2IM885f3vf35eLTaEYRYUHQgZtChNEV0TEXAMPLE== </DQ> <InverseQ> nkvOJTg5QtGNgWb9i Developer Guide cVtzrL/1pFEOHbJXwEJdU99N+7sMK+1066DL/HSBUCD63qD4USpnf0myc24in0EXAMPLE==</InverseQ> <D>
AmazonCloudFront_DevGuide-187
AmazonCloudFront_DevGuide.pdf
187
signed cookies, see Use signed cookies. Use an RSA key in the .NET Framework To use an RSA key in the .NET Framework, you must convert the AWS supplied .pem file to the XML format that the .NET Framework uses. After conversion, the RSA private key file is in the following format: Example : RSA private key in the XML .NET Framework format <RSAKeyValue> <Modulus> wO5IvYCP5UcoCKDo1dcspoMehWBZcyfs9QEzGi6Oe5y+ewGr1oW+vB2GPB ANBiVPcUHTFWhwaIBd3oglmF0lGQljP/jOfmXHUK2kUUnLnJp+oOBL2NiuFtqcW6h/L5lIpD8Yq+NRHg Ty4zDsyr2880MvXv88yEFURCkqEXAMPLE= </Modulus> <Exponent>AQAB</Exponent> <P> 5bmKDaTz npENGVqz4Cea8XPH+sxt+2VaAwYnsarVUoSBeVt8WLloVuZGG9IZYmH5KteXEu7fZveYd9UEXAMPLE== </P> <Q> 1v9l/WN1a1N3rOK4VGoCokx7kR2SyTMSbZgF9IWJNOugR/WZw7HTnjipO3c9dy1Ms9pUKwUF4 6d7049EXAMPLE== </Q> <DP> RgrSKuLWXMyBH+/l1Dx/I4tXuAJIrlPyo+VmiOc7b5NzHptkSHEPfR9s1 OK0VqjknclqCJ3Ig86OMEtEXAMPLE== Code examples for signed URLs 490 Amazon CloudFront </DP> <DQ> pjPjvSFw+RoaTu0pgCA/jwW/FGyfN6iim1RFbkT4 z49DZb2IM885f3vf35eLTaEYRYUHQgZtChNEV0TEXAMPLE== </DQ> <InverseQ> nkvOJTg5QtGNgWb9i Developer Guide cVtzrL/1pFEOHbJXwEJdU99N+7sMK+1066DL/HSBUCD63qD4USpnf0myc24in0EXAMPLE==</InverseQ> <D> Bc7mp7XYHynuPZxChjWNJZIq+A73gm0ASDv6At7F8Vi9r0xUlQe/v0AQS3ycN8QlyR4XMbzMLYk 3yjxFDXo4ZKQtOGzLGteCU2srANiLv26/imXA8FVidZftTAtLviWQZBVPTeYIA69ATUYPEq0a5u5wjGy UOij9OWyuEXAMPLE= </D> </RSAKeyValue> Canned policy signing method in C# The following C# code creates a signed URL that uses a canned policy by doing the following: • Creates a policy statement. • Hashes the policy statement using SHA1, and signs the result using RSA and the private key whose corresponding public key is in a trusted key group. • Base64-encodes the hashed and signed policy statement and replaces special characters to make the string safe to use as a URL request parameter. • Concatenates the values. For the complete implementation, see the example at Signature Code in C#. Note The keyId is returned when you upload a public key to CloudFront. For more information, see &Key-Pair-Id. Example : Canned policy signing method in C# public static string ToUrlSafeBase64String(byte[] bytes) { Code examples for signed URLs 491 Amazon CloudFront Developer Guide return System.Convert.ToBase64String(bytes) .Replace('+', '-') .Replace('=', '_') .Replace('/', '~'); } public static string CreateCannedPrivateURL(string urlString, string durationUnits, string durationNumber, string pathToPolicyStmnt, string pathToPrivateKey, string keyId) { // args[] 0-thisMethod, 1-resourceUrl, 2-seconds-minutes-hours-days // to expiration, 3-numberOfPreviousUnits, 4-pathToPolicyStmnt, // 5-pathToPrivateKey, 6-keyId TimeSpan timeSpanInterval = GetDuration(durationUnits, durationNumber); // Create the policy statement. string strPolicy = CreatePolicyStatement(pathToPolicyStmnt, urlString, DateTime.Now, DateTime.Now.Add(timeSpanInterval), "0.0.0.0/0"); if ("Error!" == strPolicy) return "Invalid time frame." + "Start time cannot be greater than end time."; // Copy the expiration time defined by policy statement. string strExpiration = CopyExpirationTimeFromPolicy(strPolicy); // Read the policy into a byte buffer. byte[] bufferPolicy = Encoding.ASCII.GetBytes(strPolicy); // Initialize the SHA1CryptoServiceProvider object and hash the policy data. using (SHA1CryptoServiceProvider cryptoSHA1 = new SHA1CryptoServiceProvider()) { bufferPolicy = cryptoSHA1.ComputeHash(bufferPolicy); // Initialize the RSACryptoServiceProvider object. RSACryptoServiceProvider providerRSA = new RSACryptoServiceProvider(); XmlDocument xmlPrivateKey = new XmlDocument(); // Load your private key, which you created by converting your // .pem file to the XML format that the .NET framework uses. // Several tools are available. Code examples for signed URLs 492 Amazon CloudFront Developer Guide xmlPrivateKey.Load(pathToPrivateKey); // Format the RSACryptoServiceProvider providerRSA and // create the signature. providerRSA.FromXmlString(xmlPrivateKey.InnerXml); RSAPKCS1SignatureFormatter rsaFormatter = new RSAPKCS1SignatureFormatter(providerRSA); rsaFormatter.SetHashAlgorithm("SHA1"); byte[] signedPolicyHash = rsaFormatter.CreateSignature(bufferPolicy); // Convert the signed policy to URL-safe base64 encoding and // replace unsafe characters + = / with the safe characters - _ ~ string strSignedPolicy = ToUrlSafeBase64String(signedPolicyHash); // Concatenate the URL, the timestamp, the signature, // and the key pair ID to form the signed URL. return urlString + "?Expires=" + strExpiration + "&Signature=" + strSignedPolicy + "&Key-Pair-Id=" + keyId; } } Custom policy signing method in C# The following C# code creates a signed URL that uses a custom policy by doing the following: 1. Creates a policy statement. 2. Base64-encodes the policy statement and replaces special characters to make the string safe to use as a URL request parameter. 3. Hashes the policy statement using SHA1, and encrypts the result using RSA and the private key whose corresponding public key is in a trusted key group. 4. Base64-encodes the hashed policy statement and replacing special characters to make the string safe to use as a URL request parameter. 5. Concatenates the values. For the complete implementation, see the example at Signature Code in C#. Code examples for signed URLs 493 Amazon CloudFront Note Developer Guide The keyId is returned when you upload a public key to CloudFront. For more information, see &Key-Pair-Id. Example : Custom policy signing method in C# public static string ToUrlSafeBase64String(byte[] bytes) { return System.Convert.ToBase64String(bytes) .Replace('+', '-') .Replace('=', '_') .Replace('/', '~'); } public static string CreateCustomPrivateURL(string urlString, string durationUnits, string durationNumber, string startIntervalFromNow, string ipaddress, string pathToPolicyStmnt, string pathToPrivateKey, string keyId) { // args[] 0-thisMethod, 1-resourceUrl, 2-seconds-minutes-hours-days // to expiration, 3-numberOfPreviousUnits, 4-starttimeFromNow, // 5-ip_address, 6-pathToPolicyStmt, 7-pathToPrivateKey, 8-keyId TimeSpan timeSpanInterval = GetDuration(durationUnits, durationNumber); TimeSpan timeSpanToStart = GetDurationByUnits(durationUnits, startIntervalFromNow); if (null == timeSpanToStart) return "Invalid duration units." + "Valid options: seconds, minutes, hours, or days"; string strPolicy = CreatePolicyStatement( pathToPolicyStmnt, urlString, DateTime.Now.Add(timeSpanToStart), DateTime.Now.Add(timeSpanInterval), ipaddress); // Read the policy into a byte buffer. byte[] bufferPolicy = Encoding.ASCII.GetBytes(strPolicy); // Convert the policy statement to URL-safe base64 encoding and Code examples for signed URLs 494 Amazon CloudFront Developer Guide // replace unsafe characters + = / with the safe characters - _ ~ string urlSafePolicy = ToUrlSafeBase64String(bufferPolicy); // Initialize the SHA1CryptoServiceProvider object and hash the policy data. byte[] bufferPolicyHash; using (SHA1CryptoServiceProvider cryptoSHA1 = new
AmazonCloudFront_DevGuide-188
AmazonCloudFront_DevGuide.pdf
188
= GetDuration(durationUnits, durationNumber); TimeSpan timeSpanToStart = GetDurationByUnits(durationUnits, startIntervalFromNow); if (null == timeSpanToStart) return "Invalid duration units." + "Valid options: seconds, minutes, hours, or days"; string strPolicy = CreatePolicyStatement( pathToPolicyStmnt, urlString, DateTime.Now.Add(timeSpanToStart), DateTime.Now.Add(timeSpanInterval), ipaddress); // Read the policy into a byte buffer. byte[] bufferPolicy = Encoding.ASCII.GetBytes(strPolicy); // Convert the policy statement to URL-safe base64 encoding and Code examples for signed URLs 494 Amazon CloudFront Developer Guide // replace unsafe characters + = / with the safe characters - _ ~ string urlSafePolicy = ToUrlSafeBase64String(bufferPolicy); // Initialize the SHA1CryptoServiceProvider object and hash the policy data. byte[] bufferPolicyHash; using (SHA1CryptoServiceProvider cryptoSHA1 = new SHA1CryptoServiceProvider()) { bufferPolicyHash = cryptoSHA1.ComputeHash(bufferPolicy); // Initialize the RSACryptoServiceProvider object. RSACryptoServiceProvider providerRSA = new RSACryptoServiceProvider(); XmlDocument xmlPrivateKey = new XmlDocument(); // Load your private key, which you created by converting your // .pem file to the XML format that the .NET framework uses. // Several tools are available. xmlPrivateKey.Load(pathToPrivateKey); // Format the RSACryptoServiceProvider providerRSA // and create the signature. providerRSA.FromXmlString(xmlPrivateKey.InnerXml); RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(providerRSA); RSAFormatter.SetHashAlgorithm("SHA1"); byte[] signedHash = RSAFormatter.CreateSignature(bufferPolicyHash); // Convert the signed policy to URL-safe base64 encoding and // replace unsafe characters + = / with the safe characters - _ ~ string strSignedPolicy = ToUrlSafeBase64String(signedHash); return urlString + "?Policy=" + urlSafePolicy + "&Signature=" + strSignedPolicy + "&Key-Pair-Id=" + keyId; } } Code examples for signed URLs 495 Amazon CloudFront Developer Guide Utility methods for signature generation The following methods get the policy statement from a file and parse time intervals for signature generation. Example : Utility methods for signature generation public static string CreatePolicyStatement(string policyStmnt, string resourceUrl, DateTime startTime, DateTime endTime, string ipAddress) { // Create the policy statement. FileStream streamPolicy = new FileStream(policyStmnt, FileMode.Open, FileAccess.Read); using (StreamReader reader = new StreamReader(streamPolicy)) { string strPolicy = reader.ReadToEnd(); TimeSpan startTimeSpanFromNow = (startTime - DateTime.Now); TimeSpan endTimeSpanFromNow = (endTime - DateTime.Now); TimeSpan intervalStart = (DateTime.UtcNow.Add(startTimeSpanFromNow)) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); TimeSpan intervalEnd = (DateTime.UtcNow.Add(endTimeSpanFromNow)) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); int startTimestamp = (int)intervalStart.TotalSeconds; // START_TIME int endTimestamp = (int)intervalEnd.TotalSeconds; // END_TIME if (startTimestamp > endTimestamp) return "Error!"; // Replace variables in the policy statement. strPolicy = strPolicy.Replace("RESOURCE", resourceUrl); strPolicy = strPolicy.Replace("START_TIME", startTimestamp.ToString()); strPolicy = strPolicy.Replace("END_TIME", endTimestamp.ToString()); strPolicy = strPolicy.Replace("IP_ADDRESS", ipAddress); strPolicy = strPolicy.Replace("EXPIRES", endTimestamp.ToString()); return strPolicy; } Code examples for signed URLs 496 Amazon CloudFront } Developer Guide public static TimeSpan GetDuration(string units, string numUnits) { TimeSpan timeSpanInterval = new TimeSpan(); switch (units) { case "seconds": timeSpanInterval = new TimeSpan(0, 0, 0, int.Parse(numUnits)); break; case "minutes": timeSpanInterval = new TimeSpan(0, 0, int.Parse(numUnits), 0); break; case "hours": timeSpanInterval = new TimeSpan(0, int.Parse(numUnits), 0 ,0); break; case "days": timeSpanInterval = new TimeSpan(int.Parse(numUnits),0 ,0 ,0); break; default: Console.WriteLine("Invalid time units;" + "use seconds, minutes, hours, or days"); break; } return timeSpanInterval; } private static TimeSpan GetDurationByUnits(string durationUnits, string startIntervalFromNow) { switch (durationUnits) { case "seconds": return new TimeSpan(0, 0, int.Parse(startIntervalFromNow)); case "minutes": return new TimeSpan(0, int.Parse(startIntervalFromNow), 0); case "hours": return new TimeSpan(int.Parse(startIntervalFromNow), 0, 0); case "days": return new TimeSpan(int.Parse(startIntervalFromNow), 0, 0, 0); default: return new TimeSpan(0, 0, 0, 0); } } Code examples for signed URLs 497 Amazon CloudFront Developer Guide public static string CopyExpirationTimeFromPolicy(string policyStatement) { int startExpiration = policyStatement.IndexOf("EpochTime"); string strExpirationRough = policyStatement.Substring(startExpiration + "EpochTime".Length); char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; List<char> listDigits = new List<char>(digits); StringBuilder buildExpiration = new StringBuilder(20); foreach (char c in strExpirationRough) { if (listDigits.Contains(c)) buildExpiration.Append(c); } return buildExpiration.ToString(); } See also • Create a URL signature using Perl • Create a URL signature using PHP • Create a URL signature using Java Create a URL signature using Java In addition to the following code example, you can use the CloudFrontUrlSigner utility class in the AWS SDK for Java (version 1) to create CloudFront signed URLs. For more examples, see Create signed URLs and cookies using an AWS SDK in the AWS SDK Code Examples Code Library. Note Creating a signed URL is just one part of the process of serving private content with CloudFront. For more information about the entire process, see Use signed URLs. The following example shows how to create a CloudFront signed URL. Code examples for signed URLs 498 Amazon CloudFront Developer Guide Example Java policy and signature encryption methods package org.example; import java.time.Instant; import java.time.temporal.ChronoUnit; import software.amazon.awssdk.services.cloudfront.CloudFrontUtilities; import software.amazon.awssdk.services.cloudfront.model.CannedSignerRequest; import software.amazon.awssdk.services.cloudfront.url.SignedUrl; public class Main { public static void main(String[] args) throws Exception { CloudFrontUtilities cloudFrontUtilities = CloudFrontUtilities.create(); Instant expirationDate = Instant.now().plus(7, ChronoUnit.DAYS); String resourceUrl = "https://a1b2c3d4e5f6g7.cloudfront.net"; String keyPairId = "K1UA3WV15I7JSD"; CannedSignerRequest cannedRequest = CannedSignerRequest.builder() .resourceUrl(resourceUrl) .privateKey(new java.io.File("/path/to/private_key.pem").toPath()) .keyPairId(keyPairId) .expirationDate(expirationDate) .build(); SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCannedPolicy(cannedRequest); String url = signedUrl.url(); System.out.println(url); } } See also: • Create a URL signature using Perl • Create a URL signature using PHP • Create a URL signature using C# and the .NET Framework Restrict access to an AWS origin
AmazonCloudFront_DevGuide-189
AmazonCloudFront_DevGuide.pdf
189
policy and signature encryption methods package org.example; import java.time.Instant; import java.time.temporal.ChronoUnit; import software.amazon.awssdk.services.cloudfront.CloudFrontUtilities; import software.amazon.awssdk.services.cloudfront.model.CannedSignerRequest; import software.amazon.awssdk.services.cloudfront.url.SignedUrl; public class Main { public static void main(String[] args) throws Exception { CloudFrontUtilities cloudFrontUtilities = CloudFrontUtilities.create(); Instant expirationDate = Instant.now().plus(7, ChronoUnit.DAYS); String resourceUrl = "https://a1b2c3d4e5f6g7.cloudfront.net"; String keyPairId = "K1UA3WV15I7JSD"; CannedSignerRequest cannedRequest = CannedSignerRequest.builder() .resourceUrl(resourceUrl) .privateKey(new java.io.File("/path/to/private_key.pem").toPath()) .keyPairId(keyPairId) .expirationDate(expirationDate) .build(); SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCannedPolicy(cannedRequest); String url = signedUrl.url(); System.out.println(url); } } See also: • Create a URL signature using Perl • Create a URL signature using PHP • Create a URL signature using C# and the .NET Framework Restrict access to an AWS origin You can configure CloudFront and some AWS origins in a way that provides the following benefits: Restrict access to an AWS origin 499 Amazon CloudFront Developer Guide • Restricts access to the AWS origin so that it's not publicly accessible • Makes sure that viewers (users) can access the content in the AWS origin only through the specified CloudFront distribution—preventing them from accessing the content directly from the bucket, or through an unintended CloudFront distribution To do this, configure CloudFront to send authenticated requests to your AWS origin, and configure the AWS origin to only allow access to authenticated requests from CloudFront. For more information, see following topics for compatible types of AWS origins. Topics • Restrict access to an AWS Elemental MediaPackage v2 origin • Restrict access to an AWS Elemental MediaStore origin • Restrict access to an AWS Lambda function URL origin • Restrict access to an Amazon S3 origin • Restrict access with VPC origins Restrict access to an AWS Elemental MediaPackage v2 origin CloudFront provides origin access control (OAC) for restricting access to a MediaPackage v2 origin. Note CloudFront OAC only supports MediaPackage v2. MediaPackage v1 isn't supported. Topics • Creating a new OAC • Advanced settings for origin access control Creating a new OAC Complete the steps described in the following topics to set up a new OAC in CloudFront. Topics • Prerequisites Restrict access to an AWS Elemental MediaPackage v2 origin 500 Amazon CloudFront Developer Guide • Grant CloudFront permission to access the MediaPackage v2 origin • Creating the OAC Prerequisites Before you create and set up OAC, you must have a CloudFront distribution with a MediaPackage v2 origin. For more information, see Use a MediaStore container or a MediaPackage channel. Grant CloudFront permission to access the MediaPackage v2 origin Before you create an OAC or set it up in a CloudFront distribution, make sure that CloudFront has permission to access the MediaPackage v2 origin. Do this after you create a CloudFront distribution, but before you add the OAC to the MediaPackage v2 origin in the distribution configuration. Use an IAM policy to allow the CloudFront service principal (cloudfront.amazonaws.com) to access the origin. The Condition element in the policy allows CloudFront to access the MediaPackage v2 origin only when the request is on behalf of the CloudFront distribution that contains the MediaPackage v2 origin. This is the distribution with the MediaPackage v2 origin that you want to add OAC to. Example : IAM policy that allows read-only access for a CloudFront distribution with OAC enabled The following policy allows the CloudFront distribution (E1PDK09ESKHJWT) access to the MediaPackage v2 origin. The origin is the ARN specified for the Resource element. { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowCloudFrontServicePrincipal", "Effect": "Allow", "Principal": {"Service": "cloudfront.amazonaws.com"}, "Action": "mediapackagev2:GetObject", "Resource": "arn:aws:mediapackagev2:us- east-1:123456789012:channelGroup/channel-group-name/channel/channel-name/ originEndpoint/origin_endpoint_name", "Condition": { "StringEquals": {"AWS:SourceArn": "arn:aws:cloudfront::123456789012:distribution/E1PDK09ESKHJWT"} } Restrict access to an AWS Elemental MediaPackage v2 origin 501 Amazon CloudFront } ] } Notes Developer Guide • If you enabled the MQAR feature and origin access control (OAC), add the mediapackagev2:GetHeadObject action to the IAM policy. MQAR requires this permission to send HEAD requests to the MediaPackage v2 origin. For more information about MQAR, see Media quality-aware resiliency. • If you create a distribution that doesn't have permission to your MediaPackage v2 origin, you can choose Copy policy from the CloudFront console and then choose Update endpoint permissions. You can then attach the copied permission to the endpoint. For more information, see Endpoint policy fields in the AWS Elemental MediaPackage User Guide. Creating the OAC To create an OAC, you can use the AWS Management Console, AWS CloudFormation, the AWS CLI, or the CloudFront API. Console To create an OAC 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Origin access. 3. Choose Create control setting. 4. On the Create new OAC form, do the following: a. b. Enter a Name and (optionally) a Description for the OAC. For Signing behavior, we recommend that you leave the default setting (Sign requests (recommended)). For more information, see the section called “Advanced settings for origin access control”. 5. For Origin type, choose MediaPackage V2. Restrict access to
AmazonCloudFront_DevGuide-190
AmazonCloudFront_DevGuide.pdf
190
the AWS CLI, or the CloudFront API. Console To create an OAC 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Origin access. 3. Choose Create control setting. 4. On the Create new OAC form, do the following: a. b. Enter a Name and (optionally) a Description for the OAC. For Signing behavior, we recommend that you leave the default setting (Sign requests (recommended)). For more information, see the section called “Advanced settings for origin access control”. 5. For Origin type, choose MediaPackage V2. Restrict access to an AWS Elemental MediaPackage v2 origin 502 Amazon CloudFront 6. Choose Create. Tip Developer Guide After you create the OAC, make note of the Name. You need this in the following procedure. To add an OAC to a MediaPackage v2 origin in a distribution 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. Choose a distribution with a MediaPackage V2 origin that you want to add the OAC to, then choose the Origins tab. 3. 4. 5. Select the MediaPackage v2 origin that you want to add the OAC to, then choose Edit. Select HTTPS only for your origin's Protocol. From the Origin access control dropdown, choose the OAC name that you want to use. 6. Choose Save changes. The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new configuration, it signs all requests that it sends to the MediaPackage v2 origin. CloudFormation To create an OAC with AWS CloudFormation, use the AWS::CloudFront::OriginAccessControl resource type. The following example shows the AWS CloudFormation template syntax, in YAML format, for creating an OAC. Type: AWS::CloudFront::OriginAccessControl Properties: OriginAccessControlConfig: Description: An optional description for the origin access control Name: ExampleOAC OriginAccessControlOriginType: mediapackagev2 SigningBehavior: always SigningProtocol: sigv4 For more information, see AWS::CloudFront::OriginAccessControl in the AWS CloudFormation User Guide. Restrict access to an AWS Elemental MediaPackage v2 origin 503 Amazon CloudFront CLI Developer Guide To create an origin access control with the AWS Command Line Interface (AWS CLI), use the aws cloudfront create-origin-access-control command. You can use an input file to provide the input parameters for the command, rather than specifying each individual parameter as command line input. To create an origin access control (CLI with input file) 1. Use the following command to create a file that's named origin-access- control.yaml. This file contains all of the input parameters for the create-origin-access- control command. aws cloudfront create-origin-access-control --generate-cli-skeleton yaml-input > origin-access-control.yaml 2. Open the origin-access-control.yaml file that you just created. Edit the file to add a name for the OAC, a description (optional), and change the SigningBehavior to always. Then save the file. For information about other OAC settings, see the section called “Advanced settings for origin access control”. 3. Use the following command to create the origin access control using the input parameters from the origin-access-control.yaml file. aws cloudfront create-origin-access-control --cli-input-yaml file://origin- access-control.yaml Make note of the Id value in the command output. You need it to add the OAC to a MediaPackage v2 origin in a CloudFront distribution. To attach an OAC to a MediaPackage v2 origin in an existing distribution (CLI with input file) 1. Use the following command to save the distribution configuration for the CloudFront distribution that you want to add the OAC to. The distribution must have a MediaPackage v2 origin. Restrict access to an AWS Elemental MediaPackage v2 origin 504 Amazon CloudFront Developer Guide aws cloudfront get-distribution-config --id <CloudFront distribution ID> -- output yaml > dist-config.yaml 2. Open the file that's named dist-config.yaml that you just created. Edit the file, making the following changes: • In the Origins object, add the OAC's ID to the field that's named OriginAccessControlId. • Remove the value from the field that's named OriginAccessIdentity, if one exists. • Rename the ETag field to IfMatch, but don't change the field's value. Save the file when finished. 3. Use the following command to update the distribution to use the origin access control. aws cloudfront update-distribution --id <CloudFront distribution ID> --cli- input-yaml file://dist-config.yaml The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new configuration, it signs all requests that it sends to the MediaPackage v2 origin. API To create an OAC with the CloudFront API, use CreateOriginAccessControl. For more information about the fields that you specify in this API call, see the API reference documentation for your AWS SDK or other API client. After you create an OAC you can attach it to a MediaPackage v2 origin in a distribution, using one of the following API calls: • To attach it to an existing distribution, use UpdateDistribution. • To attach it to a new distribution, use CreateDistribution. For both of these API calls, provide the OAC ID in the OriginAccessControlId field, inside
AmazonCloudFront_DevGuide-191
AmazonCloudFront_DevGuide.pdf
191
the MediaPackage v2 origin. API To create an OAC with the CloudFront API, use CreateOriginAccessControl. For more information about the fields that you specify in this API call, see the API reference documentation for your AWS SDK or other API client. After you create an OAC you can attach it to a MediaPackage v2 origin in a distribution, using one of the following API calls: • To attach it to an existing distribution, use UpdateDistribution. • To attach it to a new distribution, use CreateDistribution. For both of these API calls, provide the OAC ID in the OriginAccessControlId field, inside an origin. For more information about the other fields that you specify in these API calls, see Restrict access to an AWS Elemental MediaPackage v2 origin 505 Amazon CloudFront Developer Guide Distribution settings reference and the API reference documentation for your AWS SDK or other API client. 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 MediaPackage v2 origin. 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 MediaPackage v2 origin. Warning To use this setting, the MediaPackage v2 origin must be publicly accessible. If you use this setting with a MediaPackage v2 origin that's not publicly accessible, CloudFront can't access the origin. The MediaPackage v2 origin returns errors to CloudFront and CloudFront passes those errors on to viewers. For more information, see the example MediaPackage v2 policy for Policies and Permissions in MediaPackage in the AWS Elemental MediaPackage 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 Restrict access to an AWS Elemental MediaPackage v2 origin 506 Amazon CloudFront Developer Guide to sign origin requests only when the corresponding viewer request does not include an Authorization header. With this setting, CloudFront passes on the Authorization header from the viewer request when one is present, but signs the origin request (adding its own Authorization header) when the viewer request doesn't include an Authorization header. Warning To pass along the Authorization header from the viewer request, you must add the Authorization header to a cache policy for all cache behaviors that use MediaPackage v2 origins associated with this origin access control. Restrict access to an AWS Elemental MediaStore origin CloudFront provides origin access control (OAC) for restricting access to an AWS Elemental MediaStore origin. Topics • Create a new origin access control • Advanced settings for origin access control Create a new origin access control Complete the steps described in the following topics to set up a new origin access control in CloudFront. Topics • Prerequisites • Grant CloudFront permission to access the MediaStore origin • Create the origin access control Prerequisites Before you create and set up origin access control, you must have a CloudFront distribution with a MediaStore origin. Restrict access to an AWS Elemental MediaStore origin 507 Amazon CloudFront Developer Guide Grant CloudFront permission to access the MediaStore origin Before you create an origin access control or set it up in a CloudFront distribution, make sure that CloudFront has permission to access the MediaStore origin. Do this after creating a CloudFront distribution, but before adding the OAC to the MediaStore origin in the distribution configuration. Use a MediaStore container policy to allow the CloudFront service principal (cloudfront.amazonaws.com) to access the origin. Use a Condition element in the policy to allow CloudFront to access the MediaStore container only when the request is on behalf of the CloudFront distribution that contains the MediaStore origin. This is the distribution with the MediaStore origin that you want to add OAC to. The following are examples of MediaStore container policies that allow a CloudFront distribution to access a MediaStore origin. Example MediaStore container policy that allows read-only access for a CloudFront distribution with OAC enabled { "Version":
AmazonCloudFront_DevGuide-192
AmazonCloudFront_DevGuide.pdf
192
the distribution configuration. Use a MediaStore container policy to allow the CloudFront service principal (cloudfront.amazonaws.com) to access the origin. Use a Condition element in the policy to allow CloudFront to access the MediaStore container only when the request is on behalf of the CloudFront distribution that contains the MediaStore origin. This is the distribution with the MediaStore origin that you want to add OAC to. The following are examples of MediaStore container policies that allow a CloudFront distribution to access a MediaStore origin. Example MediaStore container policy that allows read-only access for a CloudFront distribution with OAC enabled { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowCloudFrontServicePrincipalReadOnly", "Effect": "Allow", "Principal": { "Service": "cloudfront.amazonaws.com" }, "Action": [ "mediastore:GetObject" ], "Resource": "arn:aws:mediastore:<region>:111122223333:container/<container name>/*", "Condition": { "StringEquals": { "AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/<CloudFront distribution ID>" }, "Bool": { "aws:SecureTransport": "true" } } } Restrict access to an AWS Elemental MediaStore origin 508 Amazon CloudFront ] } Developer Guide Example MediaStore container policy that allows read and write access for a CloudFront distribution with OAC enabled { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowCloudFrontServicePrincipalReadWrite", "Effect": "Allow", "Principal": { "Service": "cloudfront.amazonaws.com" }, "Action": [ "mediastore:GetObject", "mediastore:PutObject" ], "Resource": "arn:aws:mediastore:<region>:111122223333:container/<container name>/*", "Condition": { "StringEquals": { "AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/<CloudFront distribution ID>" }, "Bool": { "aws:SecureTransport": "true" } } } ] } Note To allow write access, you must configure Allowed HTTP methods to include PUT in your CloudFront distribution's behavior settings. Restrict access to an AWS Elemental MediaStore origin 509 Amazon CloudFront Create the origin access control Developer Guide To create an OAC, you can use the AWS Management Console, AWS CloudFormation, the AWS CLI, or the CloudFront API. Console To create an origin access control 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Origin access. 3. Choose Create control setting. 4. On the Create control setting form, do the following: a. b. In the Details pane, enter a Name and (optionally) a Description for the origin access control. In the Settings pane, we recommend that you leave the default setting (Sign requests (recommended)). For more information, see the section called “Advanced settings for origin access control”. 5. Choose MediaStore from the Origin type dropdown. 6. Choose Create. After the OAC is created, make note of the Name. You need this in the following procedure. To add an origin access control to a MediaStore origin in a distribution 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. Choose a distribution with a MediaStore origin that you want to add the OAC to, then choose the Origins tab. 3. 4. 5. Select the MediaStore origin that you want to add the OAC to, then choose Edit. Select HTTPS only for your origin's Protocol. From the Origin access control dropdown menu, choose the OAC that you want to use. 6. Choose Save changes. Restrict access to an AWS Elemental MediaStore origin 510 Amazon CloudFront Developer Guide The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new configuration, it signs all requests that it sends to the MediaStore bucket origin. CloudFormation To create an origin access control (OAC) with AWS CloudFormation, use the AWS::CloudFront::OriginAccessControl resource type. The following example shows the AWS CloudFormation template syntax, in YAML format, for creating an origin access control. Type: AWS::CloudFront::OriginAccessControl Properties: OriginAccessControlConfig: Description: An optional description for the origin access control Name: ExampleOAC OriginAccessControlOriginType: mediastore SigningBehavior: always SigningProtocol: sigv4 For more information, see AWS::CloudFront::OriginAccessControl in the AWS CloudFormation User Guide. CLI To create an origin access control with the AWS Command Line Interface (AWS CLI), use the aws cloudfront create-origin-access-control command. You can use an input file to provide the input parameters for the command, rather than specifying each individual parameter as command line input. To create an origin access control (CLI with input file) 1. Use the following command to create a file that's named origin-access- control.yaml. This file contains all of the input parameters for the create-origin-access- control command. aws cloudfront create-origin-access-control --generate-cli-skeleton yaml-input > origin-access-control.yaml 2. Open the origin-access-control.yaml file that you just created. Edit the file to add a name for the OAC, a description (optional), and change the SigningBehavior to always. Then save the file. Restrict access to an AWS Elemental MediaStore origin 511 Amazon CloudFront Developer Guide For information about other OAC settings, see the section called “Advanced settings for origin access control”. 3. Use the following command to create the origin access control using the input parameters from the origin-access-control.yaml file. aws cloudfront create-origin-access-control --cli-input-yaml file://origin- access-control.yaml Make note of the Id value in the command output. You need it to add the OAC to a MediaStore origin in a CloudFront distribution. To attach an OAC to a MediaStore origin in an existing distribution (CLI with input file) 1. Use the
AmazonCloudFront_DevGuide-193
AmazonCloudFront_DevGuide.pdf
193
the file. Restrict access to an AWS Elemental MediaStore origin 511 Amazon CloudFront Developer Guide For information about other OAC settings, see the section called “Advanced settings for origin access control”. 3. Use the following command to create the origin access control using the input parameters from the origin-access-control.yaml file. aws cloudfront create-origin-access-control --cli-input-yaml file://origin- access-control.yaml Make note of the Id value in the command output. You need it to add the OAC to a MediaStore origin in a CloudFront distribution. To attach an OAC to a MediaStore origin in an existing distribution (CLI with input file) 1. Use the following command to save the distribution configuration for the CloudFront distribution that you want to add the OAC to. The distribution must have a MediaStore origin. aws cloudfront get-distribution-config --id <CloudFront distribution ID> -- output yaml > dist-config.yaml 2. Open the file that's named dist-config.yaml that you just created. Edit the file, making the following changes: • In the Origins object, add the OAC's ID to the field that's named OriginAccessControlId. • Remove the value from the field that's named OriginAccessIdentity, if one exists. • Rename the ETag field to IfMatch, but don't change the field's value. Save the file when finished. 3. Use the following command to update the distribution to use the origin access control. aws cloudfront update-distribution --id <CloudFront distribution ID> --cli- input-yaml file://dist-config.yaml Restrict access to an AWS Elemental MediaStore origin 512 Amazon CloudFront Developer Guide The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new configuration, it signs all requests that it sends to the MediaStore origin. API To create an origin access control with the CloudFront API, use CreateOriginAccessControl. For more information about the fields that you specify in this API call, see the API reference documentation for your AWS SDK or other API client. After you create an origin access control you can attach it to a MediaStore origin in a distribution, using one of the following API calls: • To attach it to an existing distribution, use UpdateDistribution. • To attach it to a new distribution, use CreateDistribution. For both of these API calls, provide the origin access control ID in the OriginAccessControlId field, inside an origin. For more information about the other fields that you specify in these API calls, see Distribution settings reference and the API reference documentation for your AWS SDK or other API client. Advanced settings for origin access control The CloudFront origin access control 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. Origin access control 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 MediaStore origin. 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 origin access control for all origins in all Restrict access to an AWS Elemental MediaStore origin 513 Amazon CloudFront Developer Guide distributions that use this origin access control. This can save time and effort compared to removing an origin access control from all origins and distributions that use it, one by one. With this setting, CloudFront does not sign any requests that it sends to the MediaStore origin. Warning To use this setting, the MediaStore origin must be publicly accessible. If you use this setting with a MediaStore origin that's not publicly accessible, CloudFront cannot access the origin. The MediaStore origin returns errors to CloudFront and CloudFront passes those errors on to viewers. For more information, see the example MediaStore container policy for Public read access over HTTPS. 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 an Authorization header. With this setting, CloudFront passes on the Authorization header from the viewer request when one is present, but signs the origin request (adding its own Authorization header) when the viewer request doesn't include an Authorization header. Warning To pass along the Authorization header from the viewer request, you must add the Authorization header to a cache policy for all cache behaviors that use MediaStore origins associated with this origin access control. Restrict access to an AWS Lambda function URL origin CloudFront
AmazonCloudFront_DevGuide-194
AmazonCloudFront_DevGuide.pdf
194
you want CloudFront to sign origin requests only when the corresponding viewer request does not include an Authorization header. With this setting, CloudFront passes on the Authorization header from the viewer request when one is present, but signs the origin request (adding its own Authorization header) when the viewer request doesn't include an Authorization header. Warning To pass along the Authorization header from the viewer request, you must add the Authorization header to a cache policy for all cache behaviors that use MediaStore origins associated with this origin access control. Restrict access to an AWS Lambda function URL origin CloudFront provides origin access control (OAC) for restricting access to a Lambda function URL origin. Topics • Create a new OAC • Advanced settings for origin access control • Example template code Restrict access to an AWS Lambda function URL origin 514 Amazon CloudFront Create a new OAC Developer Guide Complete the steps described in the following topics to set up a new OAC in CloudFront. Important If you use PUT or POST methods with your Lambda function URL, your users must compute the SHA256 of the body and include the payload hash value of the request body in the x- amz-content-sha256 header when sending the request to CloudFront. Lambda doesn't support unsigned payloads. Topics • Prerequisites • Grant CloudFront permission to access the Lambda function URL • Create the OAC Prerequisites Before you create and set up OAC, you must have a CloudFront distribution with a Lambda function URL as the origin. To use OAC, you must specify AWS_IAM as the value for the AuthType parameter. For more information, see Use a Lambda function URL. Grant CloudFront permission to access the Lambda function URL Before you create an OAC or set it up in a CloudFront distribution, make sure that CloudFront 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 Restrict access to an AWS Lambda function URL origin 515 Amazon CloudFront Developer Guide 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. This is the distribution with the Lambda function URL origin that you want to add OAC to. Example : AWS CLI command to update a policy to allow read-only access for a CloudFront distribution with OAC enabled The following AWS CLI command allows the CloudFront distribution (E1PDK09ESKHJWT) access your Lambda 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-name FUNCTION_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. Console To create an OAC 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Origin access. 3. Choose Create control setting. 4. On the Create new OAC form, do the following: Restrict access to an AWS Lambda function URL origin 516 Amazon CloudFront Developer Guide a. b. Enter a Name and (optionally) a Description for the OAC. For Signing behavior, we recommend that you leave the default setting (Sign requests (recommended)). For more information, see the section called “Advanced settings for origin access control”. 5. For Origin type, choose Lambda. 6. Choose Create. Tip After you create the OAC, make note of the Name. You need this in the following procedure. To add an origin access control to a Lambda function URL in a distribution 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. Choose a distribution with a Lambda function URL that you want to add the OAC to, then choose the Origins tab. 3. 4. 5. Select the Lambda function URL that you want to add the OAC to, and then choose Edit. Select HTTPS only for your origin's Protocol. From the Origin access control dropdown, choose the OAC name that you want to use. 6. Choose Save changes. The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new
AmazonCloudFront_DevGuide-195
AmazonCloudFront_DevGuide.pdf
195
a Lambda function URL in a distribution 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. Choose a distribution with a Lambda function URL that you want to add the OAC to, then choose the Origins tab. 3. 4. 5. Select the Lambda function URL that you want to add the OAC to, and then choose Edit. Select HTTPS only for your origin's Protocol. From the Origin access control dropdown, choose the OAC name that you want to use. 6. Choose Save changes. The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new configuration, it signs all requests that it sends to the Lambda function URL. CloudFormation To create an OAC with AWS CloudFormation, use the AWS::CloudFront::OriginAccessControl resource type. The following example shows the AWS CloudFormation template syntax, in YAML format, for creating an OAC. Type: AWS::CloudFront::OriginAccessControl Properties: OriginAccessControlConfig: Description: An optional description for the origin access control Restrict access to an AWS Lambda function URL origin 517 Amazon CloudFront Developer Guide Name: ExampleOAC OriginAccessControlOriginType: lambda SigningBehavior: always SigningProtocol: sigv4 For more information, see AWS::CloudFront::OriginAccessControl in the AWS CloudFormation User Guide. CLI To create an origin access control with the AWS Command Line Interface (AWS CLI), use the aws cloudfront create-origin-access-control command. You can use an input file to provide the input parameters for the command, rather than specifying each individual parameter as command line input. To create an origin access control (CLI with input file) 1. Use the following command to create a file that's named origin-access- control.yaml. This file contains all of the input parameters for the create-origin-access- control command. aws cloudfront create-origin-access-control --generate-cli-skeleton yaml-input > origin-access-control.yaml 2. Open the origin-access-control.yaml file that you just created. Edit the file to add a name for the OAC, a description (optional), and change the SigningBehavior to always. Then save the file. For information about other OAC settings, see the section called “Advanced settings for origin access control”. 3. Use the following command to create the origin access control using the input parameters from the origin-access-control.yaml file. aws cloudfront create-origin-access-control --cli-input-yaml file://origin- access-control.yaml Make note of the Id value in the command output. You need it to add the OAC to a Lambda function URL in a CloudFront distribution. Restrict access to an AWS Lambda function URL origin 518 Amazon CloudFront Developer Guide To attach an OAC to a Lambda function URL in an existing distribution (CLI with input file) 1. Use the following command to save the distribution configuration for the CloudFront distribution that you want to add the OAC to. The distribution must have a Lambda function URL as the origin. aws cloudfront get-distribution-config --id <CloudFront distribution ID> -- output yaml > dist-config.yaml 2. Open the file that's named dist-config.yaml that you just created. Edit the file, making the following changes: • In the Origins object, add the OAC's ID to the field that's named OriginAccessControlId. • Remove the value from the field that's named OriginAccessIdentity, if one exists. • Rename the ETag field to IfMatch, but don't change the field's value. Save the file when finished. 3. Use the following command to update the distribution to use the origin access control. aws cloudfront update-distribution --id <CloudFront distribution ID> --cli- input-yaml file://dist-config.yaml The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new configuration, it signs all requests that it sends to the Lambda function URL. API To create an OAC with the CloudFront API, use CreateOriginAccessControl. For more information about the fields that you specify in this API call, see the API reference documentation for your AWS SDK or other API client. After you create an OAC you can attach it to a Lambda function URL in a distribution, using one of the following API calls: • To attach it to an existing distribution, use UpdateDistribution. • To attach it to a new distribution, use CreateDistribution. Restrict access to an AWS Lambda function URL origin 519 Amazon CloudFront Developer Guide For both of these API calls, provide the OAC ID in the OriginAccessControlId field, inside an origin. For more information about the other fields that you specify in these API calls, see and the API reference documentation for your AWS SDK or other API client. 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
AmazonCloudFront_DevGuide-196
AmazonCloudFront_DevGuide.pdf
196
API reference documentation for your AWS SDK or other API client. 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 Restrict access to an AWS Lambda function URL origin 520 Amazon CloudFront Developer Guide to sign origin requests only when the corresponding viewer request does not include an Authorization header. With this setting, CloudFront passes on the Authorization header from the viewer request when one is present, but signs the origin request (adding its own Authorization header) when the viewer request doesn't include an Authorization 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 the Authorization 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. Restrict access to an AWS Lambda function URL origin 521 Amazon CloudFront Developer Guide 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 multi-part 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) Restrict access to an AWS Lambda function URL origin 522
AmazonCloudFront_DevGuide-197
AmazonCloudFront_DevGuide.pdf
197
• Supports file uploads by using multi-part 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) Restrict access to an AWS Lambda function URL origin 522 Amazon CloudFront Developer Guide # 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 Restrict access to an AWS Lambda function URL origin 523 Amazon CloudFront ) Developer Guide # 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) Restrict access to an Amazon S3 origin CloudFront provides two ways to send authenticated requests to an Amazon S3 origin: origin access control (OAC) and origin access identity (OAI). OAC helps you secure your origins, such as for Amazon S3. We recommend using OAC because it supports: • All Amazon S3 buckets in all AWS Regions, including opt-in Regions launched after December 2022 • Amazon S3 server-side encryption with AWS KMS (SSE-KMS) • Dynamic requests (PUT and DELETE) to Amazon S3 Origin access identity (OAI) doesn't work for the scenarios in the preceding list, or it requires extra workarounds in those scenarios. The following topics describe how to use origin access control (OAC) with an Amazon S3 origin. For information about how to migrate from origin access identity (OAI) to origin access control (OAC), see the section called “Migrating from origin access identity (OAI) to origin access control (OAC)”. Restrict access to an Amazon S3 origin 524 Amazon CloudFront Notes Developer Guide • When you use CloudFront OAC with Amazon S3 bucket origins, you must set Amazon S3 Object Ownership to Bucket owner enforced, the default for new Amazon S3 buckets. If you require ACLs, use the Bucket owner preferred setting to maintain control over objects uploaded via CloudFront. • If your origin is an Amazon S3 bucket configured as a website endpoint, you must set it up with CloudFront as a custom origin. That means you can't use OAC (or OAI). OAC doesn't support origin redirect by using Lambda@Edge. Topics • the section called “Create a new origin access control” • the section called “Delete a distribution with an OAC attached to an S3 bucket” • the section called “Migrating from origin access identity (OAI) to origin access control (OAC)” • the section called “Advanced settings for origin access control” Create a new origin access control Complete the steps described in the following topics to set up a new origin access control in CloudFront. Topics • Prerequisites • Grant CloudFront permission to access the S3 bucket • Create the origin access control Prerequisites Before you create and set up origin access control (OAC), you must have a CloudFront distribution with an Amazon S3 bucket origin. This origin must be a regular S3 bucket, not a bucket configured as a website endpoint. For more information about setting up a CloudFront distribution with an S3 bucket origin, see the section called “Get started with a basic distribution”. Restrict access to an Amazon S3 origin 525 Amazon CloudFront Important Developer Guide When you use OAC to secure your Amazon S3 origin, communication between CloudFront and Amazon S3 is always through HTTPS, but only when you choose to always sign requests. You must choose Sign requests (recommended) in the console or specify always in the CloudFront API, AWS CLI, or CloudFormation. If you choose either the Do not sign requests or Do not override authorization header option instead, CloudFront uses the connection protocol that you specified in the following policies: • Viewer protocol policy • Origin protocol policy (custom orgins only) For example, if you choose Do not override authorization header and want to use HTTPS between CloudFront and your Amazon S3 origin,
AmazonCloudFront_DevGuide-198
AmazonCloudFront_DevGuide.pdf
198
between CloudFront and Amazon S3 is always through HTTPS, but only when you choose to always sign requests. You must choose Sign requests (recommended) in the console or specify always in the CloudFront API, AWS CLI, or CloudFormation. If you choose either the Do not sign requests or Do not override authorization header option instead, CloudFront uses the connection protocol that you specified in the following policies: • Viewer protocol policy • Origin protocol policy (custom orgins only) For example, if you choose Do not override authorization header and want to use HTTPS between CloudFront and your Amazon S3 origin, use Redirect HTTP to HTTPS or HTTPS only for the viewer protocol policy. Grant CloudFront permission to access the S3 bucket Before you create an origin access control (OAC) or set it up in a CloudFront distribution, make sure that CloudFront has permission to access the S3 bucket origin. Do this after creating a CloudFront distribution, but before adding the OAC to the S3 origin in the distribution configuration. Use an S3 bucket policy to allow the CloudFront service principal (cloudfront.amazonaws.com) to access the bucket. Use a Condition element in the policy to allow CloudFront to access the bucket only when the request is on behalf of the CloudFront distribution that contains the S3 origin. This is the distribution with the S3 origin that you want to add OAC to. For information about adding or modifying a bucket policy, see Adding a bucket policy using the Amazon S3 console in the Amazon S3 User Guide. The following are examples of S3 bucket policies that allow a CloudFront distribution with OAC enabled access to an S3 origin. Example S3 bucket policy that allows read-only access for a CloudFront distribution with OAC enabled { Restrict access to an Amazon S3 origin 526 Amazon CloudFront Developer Guide "Version": "2012-10-17", "Statement": { "Sid": "AllowCloudFrontServicePrincipalReadOnly", "Effect": "Allow", "Principal": { "Service": "cloudfront.amazonaws.com" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::<S3 bucket name>/*", "Condition": { "StringEquals": { "AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/<CloudFront distribution ID>" } } } } Example S3 bucket policy that allows read and write access for a CloudFront distribution with OAC enabled { "Version": "2012-10-17", "Statement": { "Sid": "AllowCloudFrontServicePrincipalReadWrite", "Effect": "Allow", "Principal": { "Service": "cloudfront.amazonaws.com" }, "Action": [ "s3:GetObject", "s3:PutObject" ], "Resource": "arn:aws:s3:::<S3 bucket name>/*", "Condition": { "StringEquals": { "AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/<CloudFront distribution ID>" } } } } Restrict access to an Amazon S3 origin 527 Amazon CloudFront SSE-KMS Developer Guide If the objects in the S3 bucket origin are encrypted using server-side encryption with AWS Key Management Service (SSE-KMS), you must make sure that the CloudFront distribution has permission to use the AWS KMS key. To give the CloudFront distribution permission to use the KMS key, add a statement to the KMS key policy. For information about how to modify a key policy, see Changing a key policy in the AWS Key Management Service Developer Guide. Example KMS key policy statement The following example shows a AWS KMS policy statement that allows the CloudFront distribution with OAC to access a KMS key for SSE-KMS. { "Sid": "AllowCloudFrontServicePrincipalSSE-KMS", "Effect": "Allow", "Principal": { "Service": [ "cloudfront.amazonaws.com" ] }, "Action": [ "kms:Decrypt", "kms:Encrypt", "kms:GenerateDataKey*" ], "Resource": "*", "Condition": { "StringEquals": { "AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/<CloudFront distribution ID>" } } } Create the origin access control To create an origin access control (OAC), you can use the AWS Management Console, AWS CloudFormation, the AWS CLI, or the CloudFront API. Restrict access to an Amazon S3 origin 528 Amazon CloudFront Console To create an origin access control Developer Guide 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Origin access. 3. Choose Create control setting. 4. On the Create control setting form, do the following: a. b. In the Details pane, enter a Name and (optionally) a Description for the origin access control. In the Settings pane, we recommend that you leave the default setting (Sign requests (recommended)). For more information, see the section called “Advanced settings for origin access control”. 5. Choose S3 from the Origin type dropdown. 6. Choose Create. After the OAC is created, make note of the Name. You need this in the following procedure. To add an origin access control to an S3 origin in a distribution 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. Choose a distribution with an S3 origin that you want to add the OAC to, then choose the Origins tab. 3. 4. 5. Select the S3 origin that you want to add the OAC to, then choose Edit. For Origin access, choose Origin access control settings (recommended). From the Origin access control dropdown menu, choose the OAC that you want to use. 6. Choose Save changes. The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new
AmazonCloudFront_DevGuide-199
AmazonCloudFront_DevGuide.pdf
199
control to an S3 origin in a distribution 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. Choose a distribution with an S3 origin that you want to add the OAC to, then choose the Origins tab. 3. 4. 5. Select the S3 origin that you want to add the OAC to, then choose Edit. For Origin access, choose Origin access control settings (recommended). From the Origin access control dropdown menu, choose the OAC that you want to use. 6. Choose Save changes. The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new configuration, it signs all requests that it sends to the S3 bucket origin. Restrict access to an Amazon S3 origin 529 Amazon CloudFront CloudFormation Developer Guide To create an origin access control (OAC) with AWS CloudFormation, use the AWS::CloudFront::OriginAccessControl resource type. The following example shows the AWS CloudFormation template syntax, in YAML format, for creating an origin access control. Type: AWS::CloudFront::OriginAccessControl Properties: OriginAccessControlConfig: Description: An optional description for the origin access control Name: ExampleOAC OriginAccessControlOriginType: s3 SigningBehavior: always SigningProtocol: sigv4 For more information, see AWS::CloudFront::OriginAccessControl in the AWS CloudFormation User Guide. CLI To create an origin access control with the AWS Command Line Interface (AWS CLI), use the aws cloudfront create-origin-access-control command. You can use an input file to provide the input parameters for the command, rather than specifying each individual parameter as command line input. To create an origin access control (CLI with input file) 1. Use the following command to create a file that's named origin-access- control.yaml. This file contains all of the input parameters for the create-origin-access- control command. aws cloudfront create-origin-access-control --generate-cli-skeleton yaml-input > origin-access-control.yaml 2. Open the origin-access-control.yaml file that you just created. Edit the file to add a name for the OAC, a description (optional), and change the SigningBehavior to always. Then save the file. For information about other OAC settings, see the section called “Advanced settings for origin access control”. Restrict access to an Amazon S3 origin 530 Amazon CloudFront Developer Guide 3. Use the following command to create the origin access control using the input parameters from the origin-access-control.yaml file. aws cloudfront create-origin-access-control --cli-input-yaml file://origin- access-control.yaml Make note of the Id value in the command output. You need it to add the OAC to an S3 bucket origin in a CloudFront distribution. To attach an OAC to an S3 bucket origin in an existing distribution (CLI with input file) 1. Use the following command to save the distribution configuration for the CloudFront distribution that you want to add the OAC to. The distribution must have an S3 bucket origin. aws cloudfront get-distribution-config --id <CloudFront distribution ID> -- output yaml > dist-config.yaml 2. Open the file that's named dist-config.yaml that you just created. Edit the file, making the following changes: • In the Origins object, add the OAC's ID to the field that's named OriginAccessControlId. • Remove the value from the field that's named OriginAccessIdentity, if one exists. • Rename the ETag field to IfMatch, but don't change the field's value. Save the file when finished. 3. Use the following command to update the distribution to use the origin access control. aws cloudfront update-distribution --id <CloudFront distribution ID> --cli- input-yaml file://dist-config.yaml The distribution starts deploying to all of the CloudFront edge locations. When an edge location receives the new configuration, it signs all requests that it sends to the S3 bucket origin. Restrict access to an Amazon S3 origin 531 Amazon CloudFront API Developer Guide To create an origin access control with the CloudFront API, use CreateOriginAccessControl. For more information about the fields that you specify in this API call, see the API reference documentation for your AWS SDK or other API client. After you create an origin access control you can attach it to an S3 bucket origin in a distribution, using one of the following API calls: • To attach it to an existing distribution, use UpdateDistribution. • To attach it to a new distribution, use CreateDistribution. For both of these API calls, provide the origin access control ID in the OriginAccessControlId field, inside an origin. For more information about the other fields that you specify in these API calls, see Distribution settings reference and the API reference documentation for your AWS SDK or other API client. Delete a distribution with an OAC attached to an S3 bucket If you need to delete a distribution with an OAC attached to an S3 bucket, you should delete the distribution before you delete the S3 bucket origin. Alternatively, include the Region in the origin domain name. If this isn't possible, you can remove the OAC from the distribution by switching to public before deletion. For more information, see Delete a distribution. Migrating from origin access identity (OAI) to origin access control (OAC) To
AmazonCloudFront_DevGuide-200
AmazonCloudFront_DevGuide.pdf
200
Distribution settings reference and the API reference documentation for your AWS SDK or other API client. Delete a distribution with an OAC attached to an S3 bucket If you need to delete a distribution with an OAC attached to an S3 bucket, you should delete the distribution before you delete the S3 bucket origin. Alternatively, include the Region in the origin domain name. If this isn't possible, you can remove the OAC from the distribution by switching to public before deletion. For more information, see Delete a distribution. Migrating from origin access identity (OAI) to origin access control (OAC) To migrate from a legacy origin access identity (OAI) to an origin access control (OAC), first update the S3 bucket origin to allow both the OAI and the distribution with OAC enabled to access the bucket's content. This makes sure that CloudFront never loses access to the bucket during the transition. To allow both OAI and the distribution with OAC enabled to access an S3 bucket, update the bucket policy to include two statements, one for each kind of principal. The following example S3 bucket policy allows both an OAI and a distribution with OAC enabled to access an S3 origin. Example S3 bucket policy that allows read-only access for an OAI and a CloudFront distribution with OAC enabled { Restrict access to an Amazon S3 origin 532 Amazon CloudFront Developer Guide "Version": "2012-10-17", "Statement": [ { "Sid": "AllowCloudFrontServicePrincipalReadOnly", "Effect": "Allow", "Principal": { "Service": "cloudfront.amazonaws.com" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::<S3 bucket name>/*", "Condition": { "StringEquals": { "AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/<CloudFront distribution ID>" } } }, { "Sid": "AllowLegacyOAIReadOnly", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity <origin access identity ID>" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::<S3 bucket name>/*" } ] } After you update the S3 origin's bucket policy to allow access to both OAI and OAC, you can update the distribution configuration to use OAC instead of OAI. For more information, see the section called “Create a new origin access control”. After the distribution is fully deployed, you can remove the statement in the bucket policy that allows access to the OAI. For more information, see the section called “Grant CloudFront permission to access the S3 bucket”. Advanced settings for origin access control The CloudFront origin access control 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. Restrict access to an Amazon S3 origin 533 Amazon CloudFront Developer Guide Origin access control 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 S3 bucket origin. 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 origin access control for all origins in all distributions that use this origin access control. This can save time and effort compared to removing an origin access control from all origins and distributions that use it, one by one. With this setting, CloudFront does not sign any requests that it sends to the S3 bucket origin. Warning To use this setting, the S3 bucket origin must be publicly accessible. If you use this setting with an S3 bucket origin that's not publicly accessible, CloudFront cannot access the origin. The S3 bucket origin returns errors to CloudFront and CloudFront passes those errors on to viewers. 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 an Authorization header. With this setting, CloudFront passes on the Authorization header from the viewer request when one is present, but signs the origin request (adding its own Authorization header) when the viewer request doesn't include an Authorization header. Restrict access to an Amazon S3 origin 534 Amazon CloudFront Developer Guide Warning To pass along the Authorization header from the viewer request, you must add the Authorization header to a cache policy for all cache behaviors that use S3 bucket origins associated with this origin access control. Use an origin access identity (legacy, not recommended) Overview of origin access identity CloudFront origin access identity (OAI) provides similar functionality as origin access control (OAC), but it doesn't work for all scenarios. This is why we recommend using OAC instead. Specifically, OAI doesn't support: • Amazon
AmazonCloudFront_DevGuide-201
AmazonCloudFront_DevGuide.pdf
201
doesn't include an Authorization header. Restrict access to an Amazon S3 origin 534 Amazon CloudFront Developer Guide Warning To pass along the Authorization header from the viewer request, you must add the Authorization header to a cache policy for all cache behaviors that use S3 bucket origins associated with this origin access control. Use an origin access identity (legacy, not recommended) Overview of origin access identity CloudFront origin access identity (OAI) provides similar functionality as origin access control (OAC), but it doesn't work for all scenarios. This is why we recommend using OAC instead. Specifically, OAI doesn't support: • Amazon S3 buckets in all AWS Regions, including opt-in Regions • Amazon S3 server-side encryption with AWS KMS (SSE-KMS) • Dynamic requests (PUT, POST, or DELETE) to Amazon S3 • New AWS Regions launched after January 2023 For information about how to migrating from OAI to OAC, see the section called “Migrating from origin access identity (OAI) to origin access control (OAC)”. Give an origin access identity permission to read files in the Amazon S3 bucket When you create an OAI or add one to a distribution with the CloudFront console, you can automatically update the Amazon S3 bucket policy to give the OAI permission to access your bucket. Alternatively, you can choose to manually create or update the bucket policy. Whichever method you use, you should still review the permissions to make sure that: • Your CloudFront OAI can access files in the bucket on behalf of viewers who are requesting them through CloudFront. • Viewers can't use Amazon S3 URLs to access your files outside of CloudFront. Restrict access to an Amazon S3 origin 535 Amazon CloudFront Important Developer Guide If you configure CloudFront to accept and forward all of the HTTP methods that CloudFront supports, make sure you give your CloudFront OAI the desired permissions. For example, if you configure CloudFront to accept and forward requests that use the DELETE method, configure your bucket policy to handle DELETE requests appropriately so viewers can delete only files that you want them to. Use Amazon S3 bucket policies You can give a CloudFront OAI access to files in an Amazon S3 bucket by creating or updating the bucket policy in the following ways: • Using the Amazon S3 bucket's Permissions tab in the Amazon S3 console. • Using PutBucketPolicy in the Amazon S3 API. • Using the CloudFront console. When you add an OAI to your origin settings in the CloudFront console, you can choose Yes, update the bucket policy to tell CloudFront to update the bucket policy on your behalf. If you update the bucket policy manually, make sure that you: • Specify the correct OAI as the Principal in the policy. • Give the OAI the permissions it needs to access objects on behalf of viewers. For more information, see the following sections. Specify an OAI as the Principal in a bucket policy To specify an OAI as the Principal in an Amazon S3 bucket policy, use the OAI's Amazon Resource Name (ARN), which includes the OAI's ID. For example: "Principal": { "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity <origin access identity ID>" } Restrict access to an Amazon S3 origin 536 Amazon CloudFront Developer Guide Find the OAI ID in the CloudFront console under Security, Origin access, Identities (legacy). Alternatively, use ListCloudFrontOriginAccessIdentities in the CloudFront API. Give permissions to an OAI To give the OAI the permissions to access objects in your Amazon S3 bucket, use actions in the policy that relate to specific Amazon S3 API operations. For example, the s3:GetObject action allows the OAI to read objects in the bucket. For more information, see the examples in the following section, or see Amazon S3 actions in the Amazon Simple Storage Service User Guide. Amazon S3 bucket policy examples The following examples show Amazon S3 bucket policies that allow CloudFront OAI to access an S3 bucket. Find the OAI ID in the CloudFront console under Security, Origin access, Identities (legacy). Alternatively, use ListCloudFrontOriginAccessIdentities in the CloudFront API. Example Amazon S3 bucket policy that gives the OAI read access The following example allows the OAI to read objects in the specified bucket (s3:GetObject). { "Version": "2012-10-17", "Id": "PolicyForCloudFrontPrivateContent", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity <origin access identity ID>" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::<S3 bucket name>/*" } ] } Example Amazon S3 bucket policy that gives the OAI read and write access The following example allows the OAI to read and write objects in the specified bucket (s3:GetObject and s3:PutObject). This allows viewers to upload files to your Amazon S3 bucket through CloudFront. Restrict access to an Amazon S3 origin 537 Amazon CloudFront Developer Guide { "Version": "2012-10-17", "Id": "PolicyForCloudFrontPrivateContent", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity <origin access
AmazonCloudFront_DevGuide-202
AmazonCloudFront_DevGuide.pdf
202
[ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity <origin access identity ID>" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::<S3 bucket name>/*" } ] } Example Amazon S3 bucket policy that gives the OAI read and write access The following example allows the OAI to read and write objects in the specified bucket (s3:GetObject and s3:PutObject). This allows viewers to upload files to your Amazon S3 bucket through CloudFront. Restrict access to an Amazon S3 origin 537 Amazon CloudFront Developer Guide { "Version": "2012-10-17", "Id": "PolicyForCloudFrontPrivateContent", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity <origin access identity ID>" }, "Action": [ "s3:GetObject", "s3:PutObject" ], "Resource": "arn:aws:s3:::<S3 bucket name>/*" } ] } Use Amazon S3 object ACLs (not recommended) Important We recommend using Amazon S3 bucket policies to give an OAI access to an S3 bucket. You can use access control lists (ACLs) as described in this section, but we don't recommend it. Amazon S3 recommends setting S3 Object Ownership to bucket owner enforced, which means that ACLs are disabled for the bucket and the objects in it. When you apply this setting for Object Ownership, you must use bucket policies to give access to the OAI (see the previous section). This following section is only for legacy use cases that require ACLs. You can give a CloudFront OAI access to files in an Amazon S3 bucket by creating or updating the file's ACL in the following ways: • Using the Amazon S3 object's Permissions tab in the Amazon S3 console. • Using PutObjectAcl in the Amazon S3 API. Restrict access to an Amazon S3 origin 538 Amazon CloudFront Developer Guide When you grant access to an OAI using an ACL, you must specify the OAI using its Amazon S3 canonical user ID. In the CloudFront console, you can find this ID under Security, Origin access, Identities (legacy). If you're using the CloudFront API, use the value of the S3CanonicalUserId element that was returned when you created the OAI, or call ListCloudFrontOriginAccessIdentities in the CloudFront API. Use an origin access identity in Amazon S3 regions that support only signature version 4 authentication Newer Amazon S3 Regions require that you use Signature Version 4 for authenticated requests. (For the signature versions supported in each Amazon S3 Region, see Amazon Simple Storage Service endpoints and quotas in the AWS General Reference.) If you're using an origin access identity and if your bucket is in one of the Regions that requires Signature Version 4, note the following: • DELETE, GET, HEAD, OPTIONS, and PATCH requests are supported without qualifications. • POST requests are not supported. Restrict access with VPC origins You can use CloudFront to deliver content from applications that are hosted in your virtual private cloud (VPC) private subnets. You can use Application Load Balancers (ALBs), Network Load Balancers (NLBs), and EC2 instances in private subnets as VPC origins. Here are some reasons why you might want to use VPC origins: • Security – VPC origins is designed to enhance the security posture of your application by placing your load balancers and EC2 instances in private subnets, making CloudFront the single point of entry. User requests go from CloudFront to the VPC origins over a private, secure connection, providing additional security for your applications. • Management – VPC origins reduces the operational overhead required for secure connectivity between CloudFront and origins. You can move your origins to private subnets with no public access, and you don’t have to implement access control lists (ACLs) or other mechanisms to restrict access to your origins. This way, you don't have to invest in undifferentiated development work to secure your web applications with CloudFront. • Scalability and performance – VPC origins helps you to secure your web applications, freeing up time to focus on growing your critical business applications while improving security and maintaining high-performance and global scalability with CloudFront. VPC origins streamlines Restrict access with VPC origins 539 Amazon CloudFront Developer Guide security management and reduces operational complexity so that you can use CloudFront as the single point of entry for your applications. Prerequisites Before you create a VPC origin for your CloudFront distribution, you must complete the following: • Create a virtual private cloud (VPC) on Amazon VPC. • Your VPC must be in the same AWS account as your CloudFront distribution. • Your VPC must be in one of the AWS Regions that are supported for VPC origins. For more information, see Supported AWS Regions for VPC origins. For information about creating a VPC, see Create a VPC plus other VPC resources in the Amazon VPC User Guide. • Include the following in your VPC: • Internet gateway – Required so that your VPC can receive traffic from the internet. The internet gateway is not used for routing traffic to
AmazonCloudFront_DevGuide-203
AmazonCloudFront_DevGuide.pdf
203
virtual private cloud (VPC) on Amazon VPC. • Your VPC must be in the same AWS account as your CloudFront distribution. • Your VPC must be in one of the AWS Regions that are supported for VPC origins. For more information, see Supported AWS Regions for VPC origins. For information about creating a VPC, see Create a VPC plus other VPC resources in the Amazon VPC User Guide. • Include the following in your VPC: • Internet gateway – Required so that your VPC can receive traffic from the internet. The internet gateway is not used for routing traffic to origins inside the subnet, and you don’t need to update the routing policies. • Private subnet with at least one available IPv4 address – CloudFront routes to your subnet by using an elastic network interface (ENI) that CloudFront creates after your define your private origin CloudFront resource. You must have at least one available IPv4 address in your private subnet so that the ENI creation process can succeed. The IPv4 address can be private, and there is no additional cost for it. • In the private subnet, launch an Application Load Balancer, a Network Load Balancer, or an EC2 instance to use as your origin. • The resource you launch must be fully deployed and in Active status before you can use it for a VPC origin. • To be used as a VPC origin, a Network Load Balancer must have a security group attached to it. • Dual-stack Network Load Balancers and Network Load Balancers with TLS listeners can't be added as origins. • Gateway Load Balancers are not supported for VPC origins. • Update the security group for your VPC private origin (Application Load Balancer, Network Load Balancer, or EC2 instance) to explicitly allow the CloudFront managed prefix list. This restricts traffic coming to the VPC origin. For more information, see Use the CloudFront managed prefix list. Restrict access with VPC origins 540 Amazon CloudFront Developer Guide • After the VPC origin is created, the security group can be further restricted to allow only traffic from your VPC origins. To do this, update the allowed traffic source from the managed prefix list to the CloudFront security group. Note WebSockets, gRPC traffic, and origin rewrite with Lambda@Edge in CloudFront is not supported for VPC origins. For more information, see Work with requests and responses in the Lambda@Edge documentation. Create a VPC origin (new distribution) The following procedure shows you how to create a VPC origin for your new CloudFront distribution in the CloudFront console. Alternatively, you can use the CreateVpcOrigin and CreateDistribution API operations with the AWS CLI or an AWS SDK. To create a VPC origin for a new CloudFront distribution 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. Choose VPC origins, Create VPC origin. 3. Fill out the required fields. For Origin ARN, select the ARN of your Application Load Balancer, Network Load Balancer, or EC2 instance. If you don’t see the ARN, you can copy your specific resource ARN and paste it here instead. 4. Choose Create VPC origin. 5. Wait for your VPC origin status to change to Deployed. This can take up to 15 minutes. 6. Choose Distributions, Create distribution. 7. For Origin domain, select your VPC origins resource from the dropdown list. If your VPC origin is an EC2 instance, copy and paste the Private IP DNS name of the instance into the Origin domain field. 8. Finish creating your distribution. For more information, see Create a CloudFront distribution in the console. Restrict access with VPC origins 541 Amazon CloudFront Developer Guide Create a VPC origin (existing distribution) The following procedure shows you how to create a VPC origin for your existing CloudFront distribution in the CloudFront console, which helps to ensure continuous availability of your applications. Alternatively, you can use the CreateVpcOrigin and UpdateDistributionWithStagingConfig API operations with the AWS CLI or an AWS SDK. Optionally, you could choose to add your VPC origin to your existing distribution without creating a staging distribution. To create a VPC origin for your existing CloudFront distribution 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. Choose VPC origins, Create VPC origin. 3. Fill out the required fields. For Origin ARN, select the ARN of your Application Load Balancer, Network Load Balancer, or EC2 instance. If you don’t see the ARN, you can copy your specific resource ARN and paste it here instead. 4. Choose Create VPC origin. 5. Wait for your VPC origin status to change to Deployed. This can take up to 15 minutes. 6. In the navigation pane, choose Distributions. 7. Choose the ID of your distribution. 8. On the General tab, under Continuous deployment, choose Create staging distribution. For more information, see Use CloudFront continuous deployment to safely test CDN configuration changes. 9. Follow
AmazonCloudFront_DevGuide-204
AmazonCloudFront_DevGuide.pdf
204
For Origin ARN, select the ARN of your Application Load Balancer, Network Load Balancer, or EC2 instance. If you don’t see the ARN, you can copy your specific resource ARN and paste it here instead. 4. Choose Create VPC origin. 5. Wait for your VPC origin status to change to Deployed. This can take up to 15 minutes. 6. In the navigation pane, choose Distributions. 7. Choose the ID of your distribution. 8. On the General tab, under Continuous deployment, choose Create staging distribution. For more information, see Use CloudFront continuous deployment to safely test CDN configuration changes. 9. Follow the steps in the Create staging distribution wizard to create a staging distribution. Include the following steps: • For Origins, choose Create origin. • For Origin domain, select your VPC origins resource from the dropdown menu. If your VPC origin is an EC2 instance, copy and paste the Private IP DNS name of the instance into the Origin domain field. • Choose Create origin. 10. In your staging distribution, test the VPC origin. 11. Promote the staging distribution configuration to your primary distribution. For more information, see Promote a staging distribution configuration. Restrict access with VPC origins 542 Amazon CloudFront Developer Guide 12. Remove public access to your VPC origin by making the subnet private. After you do this, the VPC origin won't be discoverable over the internet, but CloudFront will still have private access to it. For more information, see Associate or disassociate a subnet with a route table in the Amazon VPC User Guide. Update a VPC origin The following procedure shows you how to update a VPC origin for your CloudFront distribution in the CloudFront console. Alternatively, you can use the UpdateDistribution and UpdateVpcOrigin API operations with the AWS CLI or an AWS SDK. To update an existing VPC origin for your CloudFront distribution 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Distributions. 3. Choose the ID of your distribution. 4. Choose the Behaviors tab. 5. Make sure that the VPC origin is not the default origin for your cache behavior. 6. Choose the Origins tab. 7. Select the VPC origin that you're going to update and choose Delete. This disassociates the VPC origin from your distribution. Repeat steps 2-7 to disassociate the VPC origin from any other distributions. 8. Choose VPC origins. 9. Select the VPC origin and choose Edit. 10. Make your updates and choose Update VPC origin. 11. Wait for your VPC origin status to change to Deployed. This can take up to 15 minutes. 12. In the navigation pane, choose Distributions. 13. Choose the ID of your distribution. 14. Choose the Origins tab. 15. Choose Create origin. 16. For Origin domain, select your VPC origins resource from the dropdown menu. If your VPC origin is an EC2 instance, copy and paste the Private IP DNS name of the instance into the Origin domain field. Restrict access with VPC origins 543 Amazon CloudFront Developer Guide 17. Choose Create origin. This associates the VPC origin with your distribution again. Repeat steps 12-17 to associate the updated VPC origin with any other distributions. Supported AWS Regions for VPC origins VPC origins are currently supported in the following commercial AWS Regions. Availability Zone (AZ) exceptions are noted. Region Name US East (Ohio) Region us-east-2 US East (N. Virginia) us-east-1 (except AZ use1-az3) US West (N. California) us-west-1 (except AZ usw1-az2) US West (Oregon) Africa (Cape Town) Asia Pacific (Hong Kong) Asia Pacific (Mumbai) Asia Pacific (Hyderabad) us-west-2 af-south-1 ap-east-1 ap-south-1 ap-south-2 Asia Pacific (Jakarta) ap-southeast-3 Asia Pacific (Melbourne) ap-southeast-4 Asia Pacific (Osaka) Asia Pacific (Singapore) Asia Pacific (Sydney) Asia Pacific (Tokyo) ap-northeast-3 ap-southeast-1 ap-southeast-2 ap-northeast-1 (except AZ apne1- az3) Restrict access with VPC origins 544 Amazon CloudFront Region Name Region Developer Guide Asia Pacific (Seoul) ap-northeast-2 (except AZ apne2- az1) Canada (Central) ca-central-1 (except AZ cac1-az3) Canada West (Calgary) Europe (Frankfurt) Europe (Ireland) Europe (London) Europe (Milan) Europe (Paris) Europe (Spain) Europe (Stockholm) Europe (Zurich) Israel (Tel Aviv) Middle East (Bahrain) Middle East (UAE) ca-west-1 eu-central-1 eu-west-1 eu-west-2 eu-south-1 eu-west-3 eu-south-2 eu-north-1 eu-central-2 il-central-1 me-south-1 me-central-1 South America (São Paulo) sa-east-1 Restrict access to Application Load Balancers To prevent your application from being accessible on the public internet, you can use your Application Load Balancer with a VPC origin. For more information, see Restrict access with VPC origins. Restrict access to Application Load Balancers 545 Amazon CloudFront Developer Guide Alternatively, for a web application or other content that’s served by an internet-facing Application Load Balancer in Elastic Load Balancing, CloudFront can cache objects and serve them directly to users (viewers), reducing the load on your Application Load Balancer. An internet-facing load balancer has a publicly resolvable DNS name and routes requests from clients to targets over the internet. CloudFront can also help
AmazonCloudFront_DevGuide-205
AmazonCloudFront_DevGuide.pdf
205
being accessible on the public internet, you can use your Application Load Balancer with a VPC origin. For more information, see Restrict access with VPC origins. Restrict access to Application Load Balancers 545 Amazon CloudFront Developer Guide Alternatively, for a web application or other content that’s served by an internet-facing Application Load Balancer in Elastic Load Balancing, CloudFront can cache objects and serve them directly to users (viewers), reducing the load on your Application Load Balancer. An internet-facing load balancer has a publicly resolvable DNS name and routes requests from clients to targets over the internet. CloudFront can also help to reduce latency and even absorb some distributed denial of service (DDoS) attacks. However, if users can bypass CloudFront and access your Application Load Balancer directly, you don’t get these benefits. But you can configure Amazon CloudFront and your Application Load Balancer to prevent users from directly accessing the Application Load Balancer. This allows users to access the Application Load Balancer only through CloudFront, ensuring that you get the benefits of using CloudFront. To prevent users from directly accessing an Application Load Balancer and allow access only through CloudFront, complete these high-level steps: 1. Configure CloudFront to add a custom HTTP header to requests that it sends to the Application Load Balancer. 2. Configure the Application Load Balancer to only forward requests that contain the custom HTTP header. 3. (Optional) Require HTTPS to improve the security of this solution. For more information, see the following topics. After you complete these steps, users can only access your Application Load Balancer through CloudFront. Topics • Configure CloudFront to add a custom HTTP header to requests • Configure an Application Load Balancer to only forward requests that contain a specific header • (Optional) Improve the security of this solution • (Optional) Limit access to origin by using the AWS-managed prefix list for CloudFront Configure CloudFront to add a custom HTTP header to requests You can configure CloudFront to add a custom HTTP header to the requests that it sends to your origin (in this case, an Application Load Balancer). Configure CloudFront to add a custom HTTP header to requests 546 Amazon CloudFront Important Developer Guide This use case relies on keeping the custom header name and value secret. If the header name and value are not secret, other HTTP clients could potentially include them in requests that they send directly to the Application Load Balancer. This can cause the Application Load Balancer to behave as though the requests came from CloudFront when they did not. To prevent this, keep the custom header name and value secret. You can configure CloudFront to add a custom HTTP header to origin requests with the CloudFront console, AWS CloudFormation, or the CloudFront API. To add a custom HTTP header (CloudFront console) In the CloudFront console, use the Origin Custom Headers setting in Origin Settings. Enter the Header Name and its Value. Note In production, use randomly generated header names and values. Treat header names and values as secure credentials, like usernames and passwords. You can edit the Origin Custom Headers setting when you create or edit an origin for an existing CloudFront distribution, and when you create a new distribution. For more information, see Update a distribution and Create a distribution. To add a custom HTTP header (AWS CloudFormation) In an AWS CloudFormation template, use the OriginCustomHeaders property, as shown in the following example. Note The header name and value in this example are just for demonstration. In production, use randomly generated values. Treat the header name and value as a secure credential, like a user name and password. AWSTemplateFormatVersion: '2010-09-09' Configure CloudFront to add a custom HTTP header to requests 547 Amazon CloudFront Resources: Developer Guide TestDistribution: Type: 'AWS::CloudFront::Distribution' Properties: DistributionConfig: Origins: - DomainName: app-load-balancer.example.com Id: Example-ALB CustomOriginConfig: OriginProtocolPolicy: https-only OriginSSLProtocols: - TLSv1.2 OriginCustomHeaders: - HeaderName: X-Custom-Header HeaderValue: random-value-1234567890 Enabled: 'true' DefaultCacheBehavior: TargetOriginId: Example-ALB ViewerProtocolPolicy: allow-all CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6 PriceClass: PriceClass_All ViewerCertificate: CloudFrontDefaultCertificate: 'true' For more information, see the Origin and OriginCustomHeader properties in the AWS CloudFormation User Guide. To add a custom HTTP header (CloudFront API) In the CloudFront API, use the CustomHeaders object inside Origin. For more information, see CreateDistribution and UpdateDistribution in the Amazon CloudFront API Reference, and the documentation for your SDK or other API client. There are some header names that you can’t specify as origin custom headers. For more information, see Custom headers that CloudFront can’t add to origin requests. Configure an Application Load Balancer to only forward requests that contain a specific header After you configure CloudFront to add a custom HTTP header to the requests that it sends to your Application Load Balancer (see the previous section), you can configure the load balancer to only Configure an Application Load Balancer to only forward requests that contain a specific header
AmazonCloudFront_DevGuide-206
AmazonCloudFront_DevGuide.pdf
206
CloudFront API Reference, and the documentation for your SDK or other API client. There are some header names that you can’t specify as origin custom headers. For more information, see Custom headers that CloudFront can’t add to origin requests. Configure an Application Load Balancer to only forward requests that contain a specific header After you configure CloudFront to add a custom HTTP header to the requests that it sends to your Application Load Balancer (see the previous section), you can configure the load balancer to only Configure an Application Load Balancer to only forward requests that contain a specific header 548 Amazon CloudFront Developer Guide forward requests that contain this custom header. You do this by adding a new rule and modifying the default rule in your load balancer’s listener. Prerequisites To use the following procedures, you need an Application Load Balancer with at least one listener. If you haven’t created one yet, see Create an Application Load Balancer in the User Guide for Application Load Balancers. The following procedures modify an HTTPS listener. You can use the same process to modify an HTTP listener. To update the rules in an Application Load Balancer listener 1. Add a new rule. Use the instructions from Add a rule, with the following modifications: • Add the rule to the load balancer that is the origin for your CloudFront distribution. • For Add condition, choose Http header. Specify the HTTP header name and value that you added as an origin custom header in CloudFront. • For Add action, choose Forward to. Choose the target group where you want to forward requests. 2. Edit the default rule in your load balancer's listener. Use the instructions from Edit a rule, with the following modifications: • Edit the default rule of the load balancer that is the origin for your CloudFront distribution. • Delete the default action, and then for Add action, choose Return fixed response. • For Response code, enter 403. • For Response body, enter Access denied. After you complete these steps, your load balancer listener has two rules. One rule forwards requests that contain the HTTP header (requests that come from CloudFront). The other rule sends a fixed response to all other requests (requests that don’t come from CloudFront). You can verify that the solution works by sending a request to your CloudFront distribution and one to your Application Load Balancer. The request to CloudFront returns your web application or content, and the one sent directly to your Application Load Balancer returns a 403 response with the plain text message Access denied. Configure an Application Load Balancer to only forward requests that contain a specific header 549 Amazon CloudFront Developer Guide (Optional) Improve the security of this solution To improve the security of this solution, you can configure your CloudFront distribution to always use HTTPS when sending requests to your Application Load Balancer. Remember, this solution only works if you keep the custom header name and value secret. Using HTTPS can help prevent an eavesdropper from discovering the header name and value. We also recommend rotating the header name and value periodically. Use HTTPS for origin requests To configure CloudFront to use HTTPS for origin requests, set the Origin Protocol Policy setting to HTTPS Only. This setting is available in the CloudFront console, AWS CloudFormation, and the CloudFront API. For more information, see Protocol (custom origins only). The following also applies when you configure CloudFront to use HTTPS for origin requests: • You must configure CloudFront to forward the Host header to the origin with the origin request policy. You can use the AllViewer managed origin request policy. • Make sure that your Application Load Balancer has an HTTPS listener (as shown in the preceding section). For more information, see Create an HTTPS listener in the User Guide for Application Load Balancers. Using an HTTPS listener requires you to have an SSL/TLS certificate that matches the domain name that's routed to your Application Load Balancer. • SSL/TLS certificates for CloudFront can only be requested (or imported) in the us-east-1 AWS Region in AWS Certificate Manager (ACM). Because CloudFront is a global service, it automatically distributes the certificate from the us-east-1 Region to all Regions associated with your CloudFront distribution. • For example, if you have an Application Load Balancer (ALB) in the ap-southeast-2 Region, you must configure SSL/TLS certificates in both the ap-southeast-2 Region (for using HTTPS between CloudFront and the ALB origin) and the us-east-1 Region (for using HTTPS between viewers and CloudFront). Both certificates should match the domain name that is routed to your Application Load Balancer. For more information, see AWS Region for AWS Certificate Manager. • If the end users (also known as viewers, or clients) of your web application can use HTTPS, you can also configure CloudFront to
AmazonCloudFront_DevGuide-207
AmazonCloudFront_DevGuide.pdf
207
Regions associated with your CloudFront distribution. • For example, if you have an Application Load Balancer (ALB) in the ap-southeast-2 Region, you must configure SSL/TLS certificates in both the ap-southeast-2 Region (for using HTTPS between CloudFront and the ALB origin) and the us-east-1 Region (for using HTTPS between viewers and CloudFront). Both certificates should match the domain name that is routed to your Application Load Balancer. For more information, see AWS Region for AWS Certificate Manager. • If the end users (also known as viewers, or clients) of your web application can use HTTPS, you can also configure CloudFront to prefer (or even require) HTTPS connections from the end users. To do this, use the Viewer Protocol Policy setting. You can set it to redirect end users from HTTP to HTTPS, or to reject requests that use HTTP. This setting is available in the CloudFront console, AWS CloudFormation, and the CloudFront API. For more information, see Viewer protocol policy. (Optional) Improve the security of this solution 550 Amazon CloudFront Developer Guide Rotate the header name and value In addition to using HTTPS, we also recommend rotating the header name and value periodically. The high-level steps for doing this are as follows: 1. Configure CloudFront to add an additional custom HTTP header to requests that it sends to the Application Load Balancer. 2. Update the Application Load Balancer listener rule to forward requests that contain this additional custom HTTP header. 3. Configure CloudFront to stop adding the original custom HTTP header to requests that it sends to the Application Load Balancer. 4. Update the Application Load Balancer listener rule to stop forwarding requests that contain the original custom HTTP header. For more information about accomplishing these steps, see the preceding sections. (Optional) Limit access to origin by using the AWS-managed prefix list for CloudFront To further restrict access to your Application Load Balancer, you can configure the security group associated with the Application Load Balancer so that it only accept traffic from CloudFront when the service is using an AWS-managed prefix list. This prevents traffic that doesn't originate from CloudFront from reaching your Application Load Balancer at the network layer (layer 3) or transport layer (layer 4). For more information, see the Limit access to your origins using the AWS-managed prefix list for Amazon CloudFront blog post. Restrict the geographic distribution of your content You can use geographic restrictions, sometimes known as geo blocking, to prevent users in specific geographic locations from accessing content that you're distributing through an Amazon CloudFront distribution. To use geographic restrictions, you have two options: • Use the CloudFront geographic restrictions feature. Use this option to restrict access to all of the files that are associated with a distribution and to restrict access at the country level. (Optional) Limit access to origin by using the AWS-managed prefix list for CloudFront 551 Amazon CloudFront Developer Guide • Use a third-party geolocation service. Use this option to restrict access to a subset of the files that are associated with a distribution or to restrict access at a finer granularity than the country level. Topics • Use CloudFront geographic restrictions • Use a third-party geolocation service Use CloudFront geographic restrictions When a user requests your content, CloudFront typically serves the requested content regardless of where the user is located. If you need to prevent users in specific countries from accessing your content, you can use the CloudFront geographic restrictions feature to do one of the following: • Grant permission to your users to access your content only if they’re in one of the approved countries on your allowlist. • Prevent your users from accessing your content if they’re in one of the banned countries on your denylist. For example, if a request comes from a country where you are not authorized to distribute your content, you can use CloudFront geographic restrictions to block the request. Note CloudFront determines the location of your users by using a third-party database. The accuracy of the mapping between IP addresses and countries varies by Region. Based on recent tests, the overall accuracy is 99.8%. If CloudFront can’t determine a user’s location, CloudFront serves the content that the user has requested. Here’s how geographic restrictions work: 1. Suppose you have rights to distribute your content only in Liechtenstein. You update your CloudFront distribution to add an allowlist that contains only Liechtenstein. (Alternatively, you could add a denylist that contains every country except Liechtenstein.) Use CloudFront geographic restrictions 552 Amazon CloudFront Developer Guide 2. A user in Monaco requests your content, and DNS routes the request to a CloudFront edge location in Milan, Italy. 3. The edge location in Milan looks up your distribution and determines that the user in Monaco does not have permission to download your content. 4. CloudFront returns an HTTP status
AmazonCloudFront_DevGuide-208
AmazonCloudFront_DevGuide.pdf
208
restrictions work: 1. Suppose you have rights to distribute your content only in Liechtenstein. You update your CloudFront distribution to add an allowlist that contains only Liechtenstein. (Alternatively, you could add a denylist that contains every country except Liechtenstein.) Use CloudFront geographic restrictions 552 Amazon CloudFront Developer Guide 2. A user in Monaco requests your content, and DNS routes the request to a CloudFront edge location in Milan, Italy. 3. The edge location in Milan looks up your distribution and determines that the user in Monaco does not have permission to download your content. 4. CloudFront returns an HTTP status code 403 (Forbidden) to the user. You can optionally configure CloudFront to return a custom error message to the user, and you can specify how long you want CloudFront to cache the error response for the requested file. The default value is 10 seconds. For more information, see Create a custom error page for specific HTTP status codes. Geographic restrictions apply to an entire distribution. If you need to apply one restriction to part of your content and a different restriction (or no restriction) to another part of your content, you must create separate CloudFront distributions or use a third-party geolocation service. If you enable CloudFront standard logs (access logs), you can identify the requests that CloudFront rejected by searching for the log entries in which the value of sc-status (the HTTP status code) is 403. However, using only the standard logs, you can’t distinguish a request that CloudFront rejected based on the location of the user from a request that CloudFront rejected because the user didn’t have permission to access the file for another reason. If you have a third-party geolocation service such as Digital Element or MaxMind, you can identify the location of requests based on the IP address in the c-ip (client IP) column in the access logs. For more information about CloudFront standard logs, see Standard logging (access logs). The following procedure explains how to use the CloudFront console to add geographic restrictions to an existing distribution. For information about how to use the console to create a distribution, see Create a distribution. To add geographic restrictions to your CloudFront web distribution (console) 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Distributions, then choose the distribution that you want to update. 3. Choose the Security tab, then choose Geographic restrictions. 4. Choose Edit. Use CloudFront geographic restrictions 553 Amazon CloudFront Developer Guide 5. Select Allow list to create a list of allowed countries, or Block list to create a list of blocked countries. 6. Add the desired countries to the list, then choose Save changes. Use a third-party geolocation service With the CloudFront geographic restrictions feature, you control distribution of your content at the country level for all files that you're distributing with a given web distribution. If you have a use case for geographic restrictions where the restrictions don't follow country boundaries, or if you want to restrict access to only some of the files that you're serving by a given distribution, you can combine CloudFront with a third-party geolocation service. This provides you with control over your content based not only on country but also based on city, ZIP, or postal code, or even latitude and longitude. When you're using a third-party geolocation service, we recommend that you use CloudFront signed URLs, with which you can specify an expiration date and time after which the URL is no longer valid. In addition, we recommend that you use an Amazon S3 bucket as your origin because you can then use a CloudFront origin access control to prevent users from accessing your content directly from the origin. For more information about signed URLs and origin access control, see Serve private content with signed URLs and signed cookies. The following steps explain how to control access to your files by using a third-party geolocation service. To use a third-party geolocation service to restrict access to files in a CloudFront distribution 1. Get an account with a geolocation service. 2. Upload your content to an Amazon S3 bucket. 3. Configure Amazon CloudFront and Amazon S3 to serve private content. For more information, see Serve private content with signed URLs and signed cookies. 4. Write your web application to do the following: • Send the IP address for each user request to the geolocation service. • Evaluate the return value from the geolocation service to determine whether the user is in a location where you want CloudFront to distribute your content. • If you want to distribute your content to the user’s location, generate a signed URL for your CloudFront content. If you don’t want to distribute content to that location, return HTTP Use a
AmazonCloudFront_DevGuide-209
AmazonCloudFront_DevGuide.pdf
209
S3 to serve private content. For more information, see Serve private content with signed URLs and signed cookies. 4. Write your web application to do the following: • Send the IP address for each user request to the geolocation service. • Evaluate the return value from the geolocation service to determine whether the user is in a location where you want CloudFront to distribute your content. • If you want to distribute your content to the user’s location, generate a signed URL for your CloudFront content. If you don’t want to distribute content to that location, return HTTP Use a third-party geolocation service 554 Amazon CloudFront Developer Guide status code 403 (Forbidden) to the user. Alternatively, you can configure CloudFront to return a custom error message. For more information, see the section called “Create a custom error page for specific HTTP status codes”. For more information, refer to the documentation for the geolocation service that you’re using. You can use a web server variable to get the IP addresses of the users who are visiting your website. Note the following caveats: • If your web server is not connected to the internet through a load balancer, you can use a web server variable to get the remote IP address. However, this IP address isn’t always the user’s IP address. It can also be the IP address of a proxy server, depending on how the user is connected to the internet. • If your web server is connected to the internet through a load balancer, a web server variable might contain the IP address of the load balancer, not the IP address of the user. In this configuration, we recommend that you use the last IP address in the X-Forwarded-For HTTP header. This header typically contains more than one IP address, most of which are for proxies or load balancers. The last IP address in the list is the one most likely to be associated with the user’s geographic location. If your web server is not connected to a load balancer, we recommend that you use web server variables instead of the X-Forwarded-For header to avoid IP address spoofing. Use field-level encryption to help protect sensitive data With Amazon CloudFront, you can enforce secure end-to-end connections to origin servers by using HTTPS. Field-level encryption adds an additional layer of security that lets you protect specific data throughout system processing so that only certain applications can see it. Field-level encryption allows you to enable your users to securely upload sensitive information to your web servers. The sensitive information provided by your users is encrypted at the edge, close to the user, and remains encrypted throughout your entire application stack. This encryption ensures that only applications that need the data—and have the credentials to decrypt it—are able to do so. Use field-level encryption to help protect sensitive data 555 Amazon CloudFront Developer Guide To use field-level encryption, when you configure your CloudFront distribution, specify the set of fields in POST requests that you want to be encrypted, and the public key to use to encrypt them. You can encrypt up to 10 data fields in a request. (You can’t encrypt all of the data in a request with field-level encryption; you must specify individual fields to encrypt.) When the HTTPS request with field-level encryption is forwarded to the origin, and the request is routed throughout your origin application or subsystem, the sensitive data is still encrypted, reducing the risk of a data breach or accidental data loss of the sensitive data. Components that need access to the sensitive data for business reasons, such as a payment processing system needing access to a credit number, can use the appropriate private key to decrypt and access the data. Note To use field-level encryption, your origin must support chunked encoding. CloudFront field-level encryption uses asymmetric encryption, also known as public key encryption. You provide a public key to CloudFront, and all sensitive data that you specify is encrypted automatically. The key you provide to CloudFront cannot be used to decrypt the encrypted values; only your private key can do that. Use field-level encryption to help protect sensitive data 556 Amazon CloudFront Developer Guide Topics • Overview of field-level encryption • Set up field-level encryption • Decrypt data fields at your origin Overview of field-level encryption The following steps provide an overview of setting up field-level encryption. For specific steps, see Set up field-level encryption. 1. Get a public key-private key pair. You must obtain and add the public key before you start setting up field-level encryption in CloudFront. 2. Create a field-level encryption profile. Field-level encryption profiles, which you create in CloudFront, define the fields that you want to be encrypted. 3. Create a field-level encryption configuration. A configuration specifies the profiles to use, based on
AmazonCloudFront_DevGuide-210
AmazonCloudFront_DevGuide.pdf
210
of field-level encryption • Set up field-level encryption • Decrypt data fields at your origin Overview of field-level encryption The following steps provide an overview of setting up field-level encryption. For specific steps, see Set up field-level encryption. 1. Get a public key-private key pair. You must obtain and add the public key before you start setting up field-level encryption in CloudFront. 2. Create a field-level encryption profile. Field-level encryption profiles, which you create in CloudFront, define the fields that you want to be encrypted. 3. Create a field-level encryption configuration. A configuration specifies the profiles to use, based on the content type of the request or a query argument, for encrypting specific data fields. You can also choose the request-forwarding behavior options that you want for different scenarios. For example, you can set the behavior for when the profile name specified by the query argument in a request URL doesn’t exist in CloudFront. 4. Link to a cache behavior. Link the configuration to a cache behavior for a distribution, to specify when CloudFront should encrypt data. Overview of field-level encryption 557 Amazon CloudFront Developer Guide Set up field-level encryption Follow these steps to get started using field-level encryption. To learn about quotas (formerly known as limits) on field-level encryption, see Quotas. • Step 1: Create an RSA key pair • Step 2: Add your public key to CloudFront • Step 3: Create a profile for field-level encryption • Step 4: Create a configuration • Step 5: Add a configuration to a cache behavior Step 1: Create an RSA key pair To get started, you must create an RSA key pair that includes a public key and a private key. The public key enables CloudFront to encrypt data, and the private key enables components at your origin to decrypt the fields that have been encrypted. You can use OpenSSL or another tool to create a key pair. The key size must be 2048 bits. For example, if you’re using OpenSSL, you can use the following command to generate a key pair with a length of 2048 bits and save it in the file private_key.pem: openssl genrsa -out private_key.pem 2048 The resulting file contains both the public and the private key. To extract the public key from that file, run the following command: openssl rsa -pubout -in private_key.pem -out public_key.pem The public key file (public_key.pem) contains the encoded key value that you paste in the following step. Step 2: Add your public key to CloudFront After you get your RSA key pair, add your public key to CloudFront. To add your public key to CloudFront (console) 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. Set up field-level encryption 558 Amazon CloudFront Developer Guide 2. In the navigation pane, choose Public key. 3. Choose Add public key. 4. 5. 6. For Key name, type a unique name for the key. The name can't have spaces and can include only alphanumeric characters, underscores (_), and hyphens (-). The maximum number of characters is 128. For Key value, paste the encoded key value for your public key, including the -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY----- lines. For Comment, add an optional comment. For example, you could include the expiration date for the public key. 7. Choose Add. You can add more keys to use with CloudFront by repeating the steps in the procedure. Step 3: Create a profile for field-level encryption After you add at least one public key to CloudFront, create a profile that tells CloudFront which fields to encrypt. To create a profile for field-level encryption (console) 1. In the navigation pane, choose Field-level encryption. 2. Choose Create profile. 3. Fill in the following fields: Profile name Type a unique name for the profile. The name can't have spaces and can include only alphanumeric characters, underscores (_), and hyphens (-). The maximum number of characters is 128. Public key name In the drop-down list, choose the name of a public key that you added to CloudFront in step 2. CloudFront uses the key to encrypt the fields that you specify in this profile. Provider name Type a phrase to help identify the key, such as the provider where you got the key pair. This information, along with the private key, is needed when applications decrypt data fields. Set up field-level encryption 559 Amazon CloudFront Developer Guide The provider name can't have spaces and can include only alphanumeric characters, colons (:), underscores (_), and hyphens (-). The maximum number of characters is 128. Field name pattern to match Type the names of the data fields, or patterns that identify data field names in the request, that you want CloudFront to encrypt. Choose the + option to add all the fields that you want to
AmazonCloudFront_DevGuide-211
AmazonCloudFront_DevGuide.pdf
211
such as the provider where you got the key pair. This information, along with the private key, is needed when applications decrypt data fields. Set up field-level encryption 559 Amazon CloudFront Developer Guide The provider name can't have spaces and can include only alphanumeric characters, colons (:), underscores (_), and hyphens (-). The maximum number of characters is 128. Field name pattern to match Type the names of the data fields, or patterns that identify data field names in the request, that you want CloudFront to encrypt. Choose the + option to add all the fields that you want to encrypt with this key. For the field name pattern, you can type the entire name of the data field, like DateOfBirth, or just the first part of the name with a wildcard character (*), like CreditCard*. The field name pattern must include only alphanumeric characters, square brackets ([ and ]), periods (.), underscores (_), and hyphens (-), in addition to the optional wildcard character (*). Make sure that you don’t use overlapping characters for different field name patterns. For example, if you have a field name pattern of ABC*, you can’t add another field name pattern that is AB*. In addition, field names are case-sensitive and the maximum number of characters that you can use is 128. Comment (Optional) Type a comment about this profile. The maximum number of characters that you can use is 128. 4. After you fill in the fields, choose Create profile. 5. If you want to add more profiles, choose Add profile. Step 4: Create a configuration After you create one or more field-level encryption profiles, create a configuration that specifies the content type of the request that includes the data to be encrypted, the profile to use for encryption, and other options that specify how you want CloudFront to handle encryption. For example, when CloudFront can’t encrypt the data, you can specify whether CloudFront should block or forward a request to your origin in the following scenarios: • When a request’s content type isn’t in a configuration – If you haven’t added a content type to a configuration, you can specify whether CloudFront should forward the request with that content type to the origin without encrypting data fields, or block the request and return an error. Set up field-level encryption 560 Amazon CloudFront Note Developer Guide If you add a content type to a configuration but haven’t specified a profile to use with that type, CloudFront always forwards requests with that content type to the origin. • When the profile name provided in a query argument is unknown – When you specify the fle-profile query argument with a profile name that doesn’t exist for your distribution, you can specify whether CloudFront should send the request to the origin without encrypting data fields, or block the request and return an error. In a configuration, you can also specify whether providing a profile as a query argument in a URL overrides a profile that you’ve mapped to the content type for that query. By default, CloudFront uses the profile that you’ve mapped to a content type, if you specify one. This lets you have a profile that’s used by default but decide for certain requests that you want to enforce a different profile. So, for example, you might specify (in your configuration) SampleProfile as the query argument profile to use. Then you could use the URL https://d1234.cloudfront.net?fle- profile=SampleProfile instead of https://d1234.cloudfront.net, to have CloudFront use SampleProfile for this request, instead of the profile you’d set up for the content type of the request. You can create up to 10 configurations for a single account, and then associate one of the configurations to the cache behavior of any distribution for the account. To create a configuration for field-level encryption (console) 1. On the Field-level encryption page, choose Create configuration. Note: If you haven’t created at least one profile, you won’t see the option to create a configuration. 2. Fill in the following fields to specify the profile to use. (Some fields can’t be changed.) Content type (can’t be changed) The content type is set to application/x-www-form-urlencoded and can’t be changed. Set up field-level encryption 561 Amazon CloudFront Developer Guide Default profile ID (optional) In the drop-down list, choose the profile that you want to map to the content type in the Content type field. Content format (can’t be changed) The content format is set to URLencoded and can’t be changed. 3. If you want to change the CloudFront default behavior for the following options, select the appropriate check box. Forward request to origin when request’s content type is not configured Select the check box if you want to allow the request to go to your origin if you have not specified a profile to use for the
AmazonCloudFront_DevGuide-212
AmazonCloudFront_DevGuide.pdf
212
Developer Guide Default profile ID (optional) In the drop-down list, choose the profile that you want to map to the content type in the Content type field. Content format (can’t be changed) The content format is set to URLencoded and can’t be changed. 3. If you want to change the CloudFront default behavior for the following options, select the appropriate check box. Forward request to origin when request’s content type is not configured Select the check box if you want to allow the request to go to your origin if you have not specified a profile to use for the content type of the request. Override the profile for a content type with a provided query argument Select the check box if you want to allow a profile provided in a query argument to override the profile that you’ve specified for a content type. 4. If you select the check box to allow a query argument to override the default profile, you must complete the following additional fields for the configuration. You can create up to five of these query argument mappings to use with queries. Query argument Type the value that you want to include in URLs for the fle-profile query argument. This value tells CloudFront to use the profile ID (that you specify in the next field) associated with this query argument for field-level encryption for this query. The maximum number of characters that you can use is 128. The value can’t include spaces, and must use only alphanumeric or the following characters: dash (-), period (.), underscore (_), asterisk (*), plus-sign (+), percent (%). Profile ID In the drop-down list, choose the profile that you want to associate with the value that you typed for Query argument. Set up field-level encryption 562 Amazon CloudFront Developer Guide Forward request to origin when the profile specified in a query argument does not exist Select the check box if you want to allow the request to go to your origin if the profile specified in a query argument isn't defined in CloudFront. Step 5: Add a configuration to a cache behavior To use field-level encryption, link a configuration to a cache behavior for a distribution by adding the configuration ID as a value for your distribution. Important To link a field-level encryption configuration to a cache behavior, the distribution must be configured to always use HTTPS, and to accept HTTP POST and PUT requests from viewers. That is, the following must be true: • The cache behavior’s Viewer Protocol Policy must be set to Redirect HTTP to HTTPS or HTTPS Only. (In AWS CloudFormation or the CloudFront API, ViewerProtocolPolicy must be set to redirect-to-https or https-only.) • The cache behavior’s Allowed HTTP Methods must be set to GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE. (In AWS CloudFormation or the CloudFront API, AllowedMethods must be set to GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE. These can be specified in any order.) • The origin setting’s Origin Protocol Policy must be set to Match Viewer or HTTPS Only. (In AWS CloudFormation or the CloudFront API, OriginProtocolPolicy must be set to match-viewer or https-only.) For more information, see Distribution settings reference. Decrypt data fields at your origin CloudFront encrypts data fields by using the AWS Encryption SDK. The data remains encrypted throughout your application stack and can be accessed only by applications that have the credentials to decrypt it. Decrypt data fields at your origin 563 Amazon CloudFront Developer Guide After encryption, the ciphertext is base64 encoded. When your applications decrypt the text at the origin, they must first decode the ciphertext, and then use the AWS Encryption SDK to decrypt the data. The following code example illustrates how applications can decrypt data at your origin. Note the following: • To simplify the example, this sample loads public and private keys (in DER format) from files in the working directory. In practice, you would store the private key in a secure offline location, such as an offline hardware security module, and distribute the public key to your development team. • CloudFront uses specific information while encrypting the data, and the same set of parameters should be used at the origin to decrypt it. Parameters CloudFront uses while initializing the MasterKey include the following: • PROVIDER_NAME: You specified this value when you created a field-level encryption profile. Use the same value here. • KEY_NAME: You created a name for your public key when you uploaded it to CloudFront, and then specified the key name in the profile. Use the same value here. • ALGORITHM: CloudFront uses RSA/ECB/OAEPWithSHA-256AndMGF1Padding as the algorithm for encrypting, so you must use the same algorithm to decrypt the data. • If you run the following sample program with ciphertext as input, the decrypted data is output to your console. For
AmazonCloudFront_DevGuide-213
AmazonCloudFront_DevGuide.pdf
213
Parameters CloudFront uses while initializing the MasterKey include the following: • PROVIDER_NAME: You specified this value when you created a field-level encryption profile. Use the same value here. • KEY_NAME: You created a name for your public key when you uploaded it to CloudFront, and then specified the key name in the profile. Use the same value here. • ALGORITHM: CloudFront uses RSA/ECB/OAEPWithSHA-256AndMGF1Padding as the algorithm for encrypting, so you must use the same algorithm to decrypt the data. • If you run the following sample program with ciphertext as input, the decrypted data is output to your console. For more information, see the Java Example Code in the AWS Encryption SDK. Sample code import java.nio.file.Files; import java.nio.file.Paths; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import org.apache.commons.codec.binary.Base64; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoResult; Decrypt data fields at your origin 564 Amazon CloudFront Developer Guide import com.amazonaws.encryptionsdk.jce.JceMasterKey; /** * Sample example of decrypting data that has been encrypted by CloudFront field-level encryption. */ public class DecryptExample { private static final String PRIVATE_KEY_FILENAME = "private_key.der"; private static final String PUBLIC_KEY_FILENAME = "public_key.der"; private static PublicKey publicKey; private static PrivateKey privateKey; // CloudFront uses the following values to encrypt data, and your origin must use same values to decrypt it. // In your own code, for PROVIDER_NAME, use the provider name that you specified when you created your field-level // encryption profile. This sample uses 'DEMO' for the value. private static final String PROVIDER_NAME = "DEMO"; // In your own code, use the key name that you specified when you added your public key to CloudFront. This sample // uses 'DEMOKEY' for the key name. private static final String KEY_NAME = "DEMOKEY"; // CloudFront uses this algorithm when encrypting data. private static final String ALGORITHM = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"; public static void main(final String[] args) throws Exception { final String dataToDecrypt = args[0]; // This sample uses files to get public and private keys. // In practice, you should distribute the public key and save the private key in secure storage. populateKeyPair(); System.out.println(decrypt(debase64(dataToDecrypt))); } private static String decrypt(final byte[] bytesToDecrypt) throws Exception { // You can decrypt the stream only by using the private key. // 1. Instantiate the SDK final AwsCrypto crypto = new AwsCrypto(); Decrypt data fields at your origin 565 Amazon CloudFront Developer Guide // 2. Instantiate a JCE master key final JceMasterKey masterKey = JceMasterKey.getInstance( publicKey, privateKey, PROVIDER_NAME, KEY_NAME, ALGORITHM); // 3. Decrypt the data final CryptoResult <byte[], ? > result = crypto.decryptData(masterKey, bytesToDecrypt); return new String(result.getResult()); } // Function to decode base64 cipher text. private static byte[] debase64(final String value) { return Base64.decodeBase64(value.getBytes()); } private static void populateKeyPair() throws Exception { final byte[] PublicKeyBytes = Files.readAllBytes(Paths.get(PUBLIC_KEY_FILENAME)); final byte[] privateKeyBytes = Files.readAllBytes(Paths.get(PRIVATE_KEY_FILENAME)); publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(PublicKeyBytes)); privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes)); } } Decrypt data fields at your origin 566 Amazon CloudFront Developer Guide Video on demand and live streaming video with CloudFront You can use CloudFront to deliver video on demand (VOD) or live streaming video by using any HTTP origin. One way you can set up video workflows in the cloud is by using CloudFront together with AWS Media Services. Topics • About streaming video • Deliver video on demand with CloudFront • Deliver video streaming with CloudFront and AWS Media Services • Media quality-aware resiliency About streaming video You must use an encoder to package video content before CloudFront can distribute the content. The packaging process creates segments that contain your audio, video, and captions content. It also generates manifest files, which describe in a specific order what segments to play and when. Common package formats are MPEG DASH, Apple HLS, Microsoft Smooth Streaming, and CMAF. VOD streaming For VOD streaming, your video content is stored on a server and viewers can watch it at any time. To make an asset that viewers can stream, use an encoder, such as AWS Elemental MediaConvert, to format and package your media files. After your video is packaged into the right formats, you can store it on a server or in an Amazon S3 bucket, and then deliver it with CloudFront as viewers request it. Live video streaming For live video streaming, your video content is streamed real time as live events happen, or is set up as a 24x7 live channel. To create live outputs for broadcast and streaming delivery, use an encoder such as AWS Elemental MediaLive, to compress the video and format it for viewing devices. About streaming video 567 Amazon CloudFront Developer Guide After your video is encoded, you can store it in AWS Elemental MediaStore or convert it into different delivery formats by using AWS Elemental MediaPackage. Use either of these origins to set up a CloudFront distribution to deliver the content. For specific steps and guidance for creating distributions that work together with these services,
AmazonCloudFront_DevGuide-214
AmazonCloudFront_DevGuide.pdf
214
events happen, or is set up as a 24x7 live channel. To create live outputs for broadcast and streaming delivery, use an encoder such as AWS Elemental MediaLive, to compress the video and format it for viewing devices. About streaming video 567 Amazon CloudFront Developer Guide After your video is encoded, you can store it in AWS Elemental MediaStore or convert it into different delivery formats by using AWS Elemental MediaPackage. Use either of these origins to set up a CloudFront distribution to deliver the content. For specific steps and guidance for creating distributions that work together with these services, see Serve video by using AWS Elemental MediaStore as the origin and Serve live video formatted with AWS Elemental MediaPackage. Wowza and Unified Streaming also provide tools that you can use for streaming video with CloudFront. For more information about using Wowza with CloudFront, see Bring your Wowza Streaming Engine license to CloudFront live HTTP streaming on the Wowza documentation website. For information about using Unified Streaming with CloudFront for VOD streaming, see CloudFront on the Unified Streaming documentation website. Deliver video on demand with CloudFront To deliver video on demand (VOD) streaming with CloudFront, use the following services: • Amazon S3 to store the content in its original format and to store the transcoded video. • An encoder (such as AWS Elemental MediaConvert) to transcode the video into streaming formats. • CloudFront to deliver the transcoded video to viewers. For Microsoft Smooth Streaming, see Configure video on demand for Microsoft Smooth Streaming. To create a VOD solution with CloudFront 1. Upload your content to an Amazon S3 bucket. To learn more about working with Amazon S3, see the Amazon Simple Storage Service User Guide. 2. Transcode your content by using a MediaConvert job. The job converts your video into the formats required by the players that your viewers use. You can also use the job to create assets that vary in resolution and bitrate. These assets are used for adaptive bitrate (ABR) streaming, which adjusts the viewing quality depending on the viewer’s available bandwidth. MediaConvert stores the transcoded video in an S3 bucket. 3. Deliver your converted content by using a CloudFront distribution. Viewers can watch the content on any device, at any time. Deliver video on demand 568 Amazon CloudFront Developer Guide Configure video on demand for Microsoft Smooth Streaming You have the following options for using CloudFront to distribute video on demand (VOD) content that you’ve transcoded into the Microsoft Smooth Streaming format: • Specify a web server that runs Microsoft IIS and supports Smooth Streaming as the origin for your distribution. • Enable Smooth Streaming in the cache behaviors of a CloudFront distribution. Because you can use multiple cache behaviors in a distribution, you can use one distribution for Smooth Streaming media files as well as other content. Important If you specify a web server running Microsoft IIS as your origin, do not enable Smooth Streaming in the cache behaviors of your CloudFront distribution. CloudFront can’t use a Microsoft IIS server as an origin if you enable Smooth Streaming as a cache behavior. If you enable Smooth Streaming in a cache behavior (that is, you do not have a server that is running Microsoft IIS), note the following: • You can still distribute other content using the same cache behavior if the content matches the value of Path Pattern for that cache behavior. • CloudFront can use either an Amazon S3 bucket or a custom origin for Smooth Streaming media files. CloudFront cannot use a Microsoft IIS Server as an origin if you enable Smooth Streaming for the cache behavior. • You cannot invalidate media files in the Smooth Streaming format. If you want to update files before they expire, you must rename them. For more information, see Add, remove, or replace content that CloudFront distributes. For information about Smooth Streaming clients, see Smooth Streaming on the Microsoft documentation website. To use CloudFront to distribute Smooth Streaming files when a Microsoft IIS web server isn’t the origin 1. Transcode your media files into Smooth Streaming fragmented MP4 format. Configure video on demand for Microsoft Smooth Streaming 569 Amazon CloudFront 2. Do one of the following: Developer Guide • If you’re using the CloudFront console: When you create or update a distribution, enable Smooth Streaming in one or more of the distribution’s cache behaviors. • If you’re using the CloudFront API: Add the SmoothStreaming element to the DistributionConfig complex type for one or more of the distribution’s cache behaviors. 3. Upload the Smooth Streaming files to your origin. 4. Create either a clientaccesspolicy.xml or a crossdomainpolicy.xml file, and add it to a location that is accessible at the root of your distribution, for example, https:// d111111abcdef8.cloudfront.net/clientaccesspolicy.xml. The following is an example policy: <?xml version="1.0" encoding="utf-8"?> <access-policy> <cross-domain-access>
AmazonCloudFront_DevGuide-215
AmazonCloudFront_DevGuide.pdf
215
Guide • If you’re using the CloudFront console: When you create or update a distribution, enable Smooth Streaming in one or more of the distribution’s cache behaviors. • If you’re using the CloudFront API: Add the SmoothStreaming element to the DistributionConfig complex type for one or more of the distribution’s cache behaviors. 3. Upload the Smooth Streaming files to your origin. 4. Create either a clientaccesspolicy.xml or a crossdomainpolicy.xml file, and add it to a location that is accessible at the root of your distribution, for example, https:// d111111abcdef8.cloudfront.net/clientaccesspolicy.xml. The following is an example policy: <?xml version="1.0" encoding="utf-8"?> <access-policy> <cross-domain-access> <policy> <allow-from http-request-headers="*"> <domain uri="*"/> </allow-from> <grant-to> <resource path="/" include-subpaths="true"/> </grant-to> </policy> </cross-domain-access> </access-policy> For more information, see Making a Service Available Across Domain Boundaries on the Microsoft Developer Network website. 5. For links in your application (for example, a media player), specify the URL for the media file in the following format: https://d111111abcdef8.cloudfront.net/video/presentation.ism/Manifest Configure video on demand for Microsoft Smooth Streaming 570 Amazon CloudFront Developer Guide Deliver video streaming with CloudFront and AWS Media Services To use AWS Media Services with CloudFront to deliver live content to a global audience, see the following guidance. Use AWS Elemental MediaLive to encode live video streams in real time. To encode a large video stream, MediaLive compresses it into smaller versions (encodes) that can be distributed to your viewers. After you compress a live video stream, you can use either of the following two main options to prepare and serve the content: • Convert your content into required formats, and then serve it – If you require content in multiple formats, use AWS Elemental MediaPackage to package the content for different device types. When you package the content, you can also implement extra features and add digital rights management (DRM) to prevent unauthorized use of your content. For step-by-step instructions for using CloudFront to serve content that MediaPackage formatted, see Serve live video formatted with AWS Elemental MediaPackage. • Store and serve your content using scalable origin – If MediaLive encoded content in the formats required by all of the devices that your viewers use, use a highly scalable origin like AWS Elemental MediaStore to serve the content. For step-by-step instructions for using CloudFront to serve content that is stored in a MediaStore container, see Serve video by using AWS Elemental MediaStore as the origin. After you’ve set up your origin by using one of these options, you can distribute live streaming video to viewers by using CloudFront. Tip You can learn about an AWS solution that automatically deploys services for building a highly available real-time viewing experience. To see the steps to automatically deploy this solution, see Live Streaming Automated Deployment. Topics • Serve video by using AWS Elemental MediaStore as the origin Deliver video streaming 571 Amazon CloudFront Developer Guide • Serve live video formatted with AWS Elemental MediaPackage • Serve video-on-demand content with AWS Elemental MediaPackage Serve video by using AWS Elemental MediaStore as the origin If you have video stored in an AWS Elemental MediaStore container, you can create a CloudFront distribution to serve the content. To get started, you grant CloudFront access to your MediaStore container. Then you create a CloudFront distribution and configure it to work with MediaStore. To serve content from an AWS Elemental MediaStore container 1. Follow the procedure at Allowing Amazon CloudFront to access your AWS Elemental MediaStore container, and then return to these steps to create your distribution. 2. Create a distribution with the following settings: a. Origin domain – The data endpoint that is assigned to your MediaStore container. From the dropdown list, choose the MediaStore container for your live video. b. Origin path – The folder structure in the MediaStore container where your objects are stored. For more information, see the section called “Origin path”. c. Add custom header – Add header names and values if you want CloudFront to add custom headers when it forwards requests to your origin. d. Viewer protocol policy – Choose Redirect HTTP to HTTPS. For more information, see the section called “Viewer protocol policy”. e. Cache policy and Origin request policy • For Cache policy, choose Create policy, and then create a cache policy that’s appropriate for your caching needs and segment durations. After you create the policy, refresh the list of cache policies and choose the policy that you just created. • For Origin request policy, choose CORS-CustomOrigin from the dropdown list. For the other settings, you can set specific values based on other technical requirements or the needs of your business. For a list of all the options for distributions and information about setting them, see the section called “Distribution settings”. Serve video by using AWS Elemental MediaStore as the origin 572 Amazon CloudFront Developer Guide 3. For links in your application
AmazonCloudFront_DevGuide-216
AmazonCloudFront_DevGuide.pdf
216
that’s appropriate for your caching needs and segment durations. After you create the policy, refresh the list of cache policies and choose the policy that you just created. • For Origin request policy, choose CORS-CustomOrigin from the dropdown list. For the other settings, you can set specific values based on other technical requirements or the needs of your business. For a list of all the options for distributions and information about setting them, see the section called “Distribution settings”. Serve video by using AWS Elemental MediaStore as the origin 572 Amazon CloudFront Developer Guide 3. For links in your application (for example, a media player), specify the name of the media file in the same format that you use for other objects that you’re distributing using CloudFront. Serve live video formatted with AWS Elemental MediaPackage If you formatted a live stream by using AWS Elemental MediaPackage, you can create a CloudFront distribution and configure cache behaviors to serve the live stream. The following process assumes that you have already created a channel and added endpoints for your live video using MediaPackage. To create a CloudFront distribution for MediaPackage manually, follow these steps: Step 1: Create and configure a CloudFront distribution Complete the following procedure to set up a CloudFront distribution for the live video channel that you created with MediaPackage. To create a distribution for your live video channel 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Choose Create distribution. 3. Choose the settings for the distribution, including the following: Origin domain The origin where your MediaPackage live video channel and endpoints are. Choose the text field, then from the dropdown list, choose the MediaPackage origin domain for your live video. You can map one domain to several origin endpoints. If you created your origin domain using another AWS account, type the origin URL value into the field. The origin must be an HTTPS URL. For example, for an HLS endpoint like https://3ae97e9482b0d011.mediapackage.us-west-2.amazonaws.com/out/v1/ abc123/index.m3u8, the origin domain is 3ae97e9482b0d011.mediapackage.us- west-2.amazonaws.com. For more information, see the section called “Origin domain”. Serve live video formatted with AWS Elemental MediaPackage 573 Amazon CloudFront Origin path Developer Guide The path to the MediaPackage endpoint from where the content is served. For more information about how an origin path works, see the section called “Origin path”. Important The wildcard path * is required to route somewhere in the CloudFront distribution. To prevent requests not matching an explicit path from routing to the real origin, create a "dummy" origin for that wildcard path. Example : Creating a "dummy" origin In the following example, the endpoints abc123 and def456 route to the "real" origin, but requests for any other endpoint's video content route to mediapackage.us- west-2.amazonaws.com without the proper subdomain, which results in an HTTP 404 error. MediaPackage endpoints: https://3ae97e9482b0d011.mediapackage.us-west-2.amazonaws.com/out/v1/abc123/ index.m3u8 https://3ae97e9482b0d011.mediapackage.us-west-2.amazonaws.com/out/v1/def456/ index.m3u8 CloudFront Origin A: Domain: 3ae97e9482b0d011.mediapackage.us-west-2.amazonaws.com Path: None CloudFront Origin B: Domain: mediapackage.us-west-2.amazonaws.com Path: None CloudFront cache behavior: Serve live video formatted with AWS Elemental MediaPackage 574 Amazon CloudFront Developer Guide 1. Path: /out/v1/abc123/* forward to Origin A 2. Path: /out/v1/def456/* forward to Origin A 3. Path: * forward to Origin B For the other distribution settings, set specific values based on other technical requirements or the needs of your business. For a list of all the options for distributions and information about setting them, see the section called “Distribution settings”. When you finish choosing the other distribution settings, choose Create distribution. 4. Choose the distribution that you just created, then choose Behaviors. 5. Select the default cache behavior, then choose Edit. Specify the correct cache behavior settings for the channel that you chose for the origin. Later, you’ll add one or more additional origins and edit cache behavior settings for them. 6. Go to the CloudFront distributions page. 7. Wait until the value of the Last modified column for your distribution has changed from Deploying to a date and time, indicating that CloudFront has created your distribution. Step 2: Add Origins for the domains of your MediaPackage endpoints Repeat the steps here to add each of your MediaPackage channel endpoints to your distribution, keeping in mind the need to create a "dummy" origin. To add other endpoints as origins 1. On the CloudFront console, choose the distribution that you created for your channel. 2. Choose Origins, then choose Create origin. 3. 4. For Origin domain, in the dropdown list, choose a MediaPackage endpoint for your channel. For the other settings, set the values based on other technical requirements or the needs of your business. For more information, see the section called “Origin settings”. 5. Choose Create origin. Step 3: Configure cache behaviors for all endpoints For each endpoint, you must configure cache behaviors to add path patterns that route requests correctly. The path patterns that
AmazonCloudFront_DevGuide-217
AmazonCloudFront_DevGuide.pdf
217
other endpoints as origins 1. On the CloudFront console, choose the distribution that you created for your channel. 2. Choose Origins, then choose Create origin. 3. 4. For Origin domain, in the dropdown list, choose a MediaPackage endpoint for your channel. For the other settings, set the values based on other technical requirements or the needs of your business. For more information, see the section called “Origin settings”. 5. Choose Create origin. Step 3: Configure cache behaviors for all endpoints For each endpoint, you must configure cache behaviors to add path patterns that route requests correctly. The path patterns that you specify depend on the video format that you’re serving. The Serve live video formatted with AWS Elemental MediaPackage 575 Amazon CloudFront Developer Guide following procedure includes the path pattern information to use for Apple HLS, CMAF, DASH, and Microsoft Smooth Streaming formats. You typically set up two cache behaviors for each endpoint: • The parent manifest, which is the index to your files. • The segments, which are the files of the video content. To create a cache behavior for an endpoint 1. On the CloudFront console, choose the distribution that you created for your channel. 2. Choose Behaviors, then choose Create behavior. 3. For Path pattern, use a specific MediaPackage OriginEndpoint GUID as a path prefix. Path patterns For an HLS endpoint like https://3ae97e9482b0d011.mediapackage.us- west-2.amazonaws.com/out/v1/abc123/index.m3u8, create the following two cache behaviors: • For parent and child manifests, use /out/v1/abc123/*.m3u8. • For the content segments, use /out/v1/abc123/*.ts. For a CMAF endpoint like https://3ae97e9482b0d011.mediapackage.us- west-2.amazonaws.com/out/v1/abc123/index.m3u8, create the following two cache behaviors: • For parent and child manifests, use /out/v1/abc123/*.m3u8. • For the content segments, use /out/v1/abc123/*.mp4. For a DASH endpoint like https://3ae97e9482b0d011.mediapackage.us- west-2.amazonaws.com/out/v1/abc123/index.mpd, create the following two cache behaviors: • For the parent manifest, use /out/v1/abc123/*.mpd. • For the content segments, use /out/v1/abc123/*.mp4. For a Microsoft Smooth Streaming endpoint like https://3ae97e9482b0d011.mediapackage.us-west-2.amazonaws.com/out/ Serve live video formatted with AWS Elemental MediaPackage 576 Amazon CloudFront Developer Guide v1/abc123/index.ism, only a manifest is served, so you create only one cache behavior: out/v1/abc123/index.ism/*. 4. For each cache behavior, specify values for the following settings: Viewer protocol policy Choose Redirect HTTP to HTTPS. Cache policy and origin request policy For Cache policy, choose Create policy. For your new cache policy, specify the following settings: Minimum TTL Set to 5 seconds or less, to help prevent serving stale content. Query strings For Query strings (in Cache key settings), choose Include specified query strings. For Allow, add the following values by typing them and then choosing Add item: • Add m as a query string parameter that you want CloudFront to use as the basis for caching. The MediaPackage response always includes the tag ?m=### to capture the modified time of the endpoint. If content is already cached with a different value for this tag, CloudFront requests a new manifest instead of serving the cached version. • If you’re using the time-shifted viewing functionality in MediaPackage, specify start and end as additional query string parameters on the cache behavior for manifest requests (*.m3u8, *.mpd, and index.ism/*). This way, content is served that’s specific to the requested time period in the manifest request. For more information about time-shifted viewing and formatting content start and end request parameters, see Time-shifted viewing in the AWS Elemental MediaPackage User Guide. • If you’re using the manifest filtering feature in MediaPackage, specify aws.manifestfilter as an additional query string parameter for the cache policy that you use with the cache behavior for manifest requests (*.m3u8, *.mpd, and index.ism/*). This configures your distribution to forward the aws.manifestfilter query string to your MediaPackage origin, which is required for the manifest filtering feature to work. For more information, see Manifest filtering in the AWS Elemental MediaPackage User Guide. Serve live video formatted with AWS Elemental MediaPackage 577 Amazon CloudFront Developer Guide • If you're using low-latency HLS (LL-HLS), specify _HLS_msn and _HLS_part as additional query string parameters for the cache policy that you use with the cache behavior for manifest requests (*.m3u8). This configures your distribution to forward the _HLS_msn and _HLS_part query strings to your MediaPackage origin, which is required for the LL-HLS blocking playlist request feature to work. 5. Choose Create. 6. After you create the cache policy, go back to the cache behavior creation workflow. Refresh the list of cache policies, and choose the policy that you just created. 7. Choose Create behavior. 8. If your endpoint is not a Microsoft Smooth Streaming endpoint, repeat these steps to create a second cache behavior. Step 4: Enable header-based MediaPackage CDN Authorization We recommend enabling header-based MediaPackage CDN Authorization between MediaPackage endpoints and the CloudFront distribution. For more information, see Enable CDN authorization in MediaPackage in the AWS Elemental MediaPackage User Guide. Step 5: Use CloudFront to serve the live stream channel After you create the
AmazonCloudFront_DevGuide-218
AmazonCloudFront_DevGuide.pdf
218
the cache policy, go back to the cache behavior creation workflow. Refresh the list of cache policies, and choose the policy that you just created. 7. Choose Create behavior. 8. If your endpoint is not a Microsoft Smooth Streaming endpoint, repeat these steps to create a second cache behavior. Step 4: Enable header-based MediaPackage CDN Authorization We recommend enabling header-based MediaPackage CDN Authorization between MediaPackage endpoints and the CloudFront distribution. For more information, see Enable CDN authorization in MediaPackage in the AWS Elemental MediaPackage User Guide. Step 5: Use CloudFront to serve the live stream channel After you create the distribution, add the origins, create the cache behaviors, and enable header- based CDN authorization, you can serve the live stream channel using CloudFront. CloudFront routes requests from viewers to the correct MediaPackage endpoints based on the settings that you configured for the cache behaviors. For links in your application (for example, a media player), specify the URL for the media file in the standard format for CloudFront URLs. For more information, see the section called “Customize file URLs”. Serve video-on-demand content with AWS Elemental MediaPackage If you originate your video-on-demand (VOD) content from an AWS Elemental MediaPackage origin, you can create a CloudFront distribution and configure optimized cache behaviors to serve the VOD content to viewers. The following process assumes that you have already created a packaging group with a packaging configuration and ingested an asset with MediaPackage. To create a CloudFront distribution for MediaPackage manually, follow these steps: Serve video-on-demand content with AWS Elemental MediaPackage 578 Amazon CloudFront Developer Guide Step 1: Create and configure a CloudFront distribution Complete the following procedure to set up a CloudFront distribution for the packaging group that you created with MediaPackage. To create a distribution for your VOD content 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Choose Create distribution. 3. Choose the settings for the distribution, including the following: Origin domain The origin for your MediaPackage packaging group. Type the origin URL value into the text field. The origin must be an HTTPS URL. For example, for an HLS endpoint like https://3ae97e9482b0d011.egress.mediapackage-vod.us- west-2.amazonaws.com/out/v1/abc123/def456/ghi789/index.m3u8, the origin domain is 3ae97e9482b0d011.egress.mediapackage-vod.us- west-2.amazonaws.com. For more information, see the section called “Origin domain”. Origin path The path from where the content is served. For more information about how an origin path works, see the section called “Origin path”. Important The wildcard path * is required to route somewhere in the CloudFront distribution. To prevent requests not matching an explicit path from routing to the real origin, create a "dummy" origin for that wildcard path. Serve video-on-demand content with AWS Elemental MediaPackage 579 Amazon CloudFront Developer Guide Example : Creating a "dummy" origin In the following example, the packaging configurations def456 and 321xyz route to the "real" origin, but requests for any other video content route to mediapackage-vod.us- west-2.amazonaws.com without the proper subdomain, which results in an HTTP 404 error. MediaPackage content URLs for a single asset for a packaging group with two packaging configurations: https://3ae97e9482b0d011.egress.mediapackage-vod.us-west-2.amazonaws.com/out/v1/ abc123/def456/ghi789/index.m3u8 https://3ae97e9482b0d011.egress.mediapackage-vod.us-west-2.amazonaws.com/out/v1/ abc123/321xyz/654uvw/index.m3u8 CloudFront Origin A: Domain: 3ae97e9482b0d011.egress.mediapackage-vod.us-west-2.amazonaws.com Path: None CloudFront Origin B: Domain: mediapackage-vod.us-west-2.amazonaws.com Path: None CloudFront cache behavior: 1. Path: /out/v1/*/def456/* forward to Origin A 2. Path: /out/v1/*/321xyz/* forward to Origin A 3. Path: * forward to Origin B For the other distribution settings, set specific values based on other technical requirements or the needs of your business. For a list of all the options for distributions and information about setting them, see the section called “Distribution settings”. When you finish choosing the other distribution settings, choose Create distribution. 4. Choose the distribution that you just created, then choose Behaviors. Serve video-on-demand content with AWS Elemental MediaPackage 580 Amazon CloudFront Developer Guide 5. Select the default cache behavior, then choose Edit. Specify the correct cache behavior settings for the packaging configuration that you chose for the origin. Later, you'll add one or more additional origins and edit cache behavior settings for them. 6. Go to the CloudFront distributions page. 7. Wait until the value of the Last modified column for your distribution has changed from Deploying to a date and time, indicating that CloudFront has created your distribution. Step 2: Add Origins for the domains of your MediaPackage packaging groups Repeat the steps here to add each of your MediaPackage packaging groups to your distribution, keeping in mind the need to create a "dummy" origin. To add other packaging groups as origins 1. On the CloudFront console, choose the distribution that you created for your channel. 2. Choose Origins, then choose Create origin. 3. 4. For Origin domain, type in the URL for the MediaPackage packaging group. For the other settings, set the values based on other technical requirements or the needs of your business. For more information, see the section
AmazonCloudFront_DevGuide-219
AmazonCloudFront_DevGuide.pdf
219
Origins for the domains of your MediaPackage packaging groups Repeat the steps here to add each of your MediaPackage packaging groups to your distribution, keeping in mind the need to create a "dummy" origin. To add other packaging groups as origins 1. On the CloudFront console, choose the distribution that you created for your channel. 2. Choose Origins, then choose Create origin. 3. 4. For Origin domain, type in the URL for the MediaPackage packaging group. For the other settings, set the values based on other technical requirements or the needs of your business. For more information, see the section called “Origin settings”. 5. Choose Create origin. Step 3: Configure cache behaviors for all packaging configurations For each packaging configuration, you must configure cache behaviors to add path patterns that route requests correctly. The path patterns that you specify depend on the video format that you’re serving. The following procedure includes the path pattern information to use for Apple HLS, CMAF, DASH, and Microsoft Smooth Streaming formats. You typically set up multiple cache behaviors for each packaging configuration: • The parent manifest, which is the index to your files. • The segments, which are the files of the video content. A format might use more than one extension for content, depending on your configuration. A cache behavior is needed for each extension. Serve video-on-demand content with AWS Elemental MediaPackage 581 Amazon CloudFront Developer Guide To create a cache behavior for a packaging configuration 1. On the CloudFront console, choose the distribution that you created for your channel. 2. Choose Behaviors, then choose Create behavior. 3. For Path pattern, use a specific MediaPackage VOD packaging configuration GUID as a path prefix. This is the second GUID in a MediaPackage VOD path. Path patterns For HLS content like https://3ae97e9482b0d011.egress.mediapackage-vod.us- west-2.amazonaws.com/out/v1/abc123/def456/ghi789/index.m3u8, create the following cache behaviors: • For parent and child manifests, use /out/v1/*/def456/*.m3u8. • For the content segments, use /out/v1/*/def456/*.ts and repeat for all needed segment extensions. For CMAF content like https://3ae97e9482b0d011.egress.mediapackage-vod.us- west-2.amazonaws.com/out/v1/abc123/def456/ghi789/index.m3u8, create the following cache behaviors: • For parent and child manifests, use /out/v1/*/def456/*.m3u8. • For the content segments, use /out/v1/*/def456/*.mp4 and repeat for all needed segment extensions. For DASH content like https://3ae97e9482b0d011.egress.mediapackage-vod.us- west-2.amazonaws.com/out/v1/abc123/def456/ghi789/index.mpd, create the following cache behaviors: • For the parent manifest, use /out/v1/*/def456/*.mpd. • For the content segments, use /out/v1/*/def456/*.mp4. For a Microsoft Smooth Streaming endpoint like https://3ae97e9482b0d011.egress.mediapackage-vod.us- west-2.amazonaws.com/out/v1/abc123/def456/ghi789/index.ism/Manifest, only a manifest is served, so you create only one cache behavior: out/v1/*/def456/*/ index.ism/*. 4. For each cache behavior, specify values for the following settings: Serve video-on-demand content with AWS Elemental MediaPackage 582 Amazon CloudFront Viewer protocol policy Choose Redirect HTTP to HTTPS. Cache policy and origin request policy Developer Guide For Cache policy, choose Create policy. For your new cache policy, specify the following settings: Minimum TTL Set to 5 seconds or less, to help prevent serving stale content. Query strings For Query strings (in Cache key settings), choose Include specified query strings. For Allow, add the following values by typing them and then choosing Add item: • If you’re using the manifest filtering feature in MediaPackage, specify aws.manifestfilter as an additional query string parameter for the cache policy that you use with the cache behavior for manifest requests (*.m3u8, *.mpd, and index.ism/*). This configures your distribution to forward the aws.manifestfilter query string to your MediaPackage origin, which is required for the manifest filtering feature to work. For more information, see Manifest filtering in the AWS Elemental MediaPackage User Guide. 5. Choose Create. 6. After you create the cache policy, go back to the cache behavior creation workflow. Refresh the list of cache policies, and choose the policy that you just created. 7. Choose Create behavior. 8. If your endpoint is not a Microsoft Smooth Streaming endpoint, repeat these steps to create a second cache behavior. Step 4: Enable header-based MediaPackage CDN Authorization We recommend enabling header-based MediaPackage CDN Authorization between MediaPackage VOD content and the CloudFront distribution. For more information, see Enable CDN authorization in MediaPackage in the AWS Elemental MediaPackage User Guide. Serve video-on-demand content with AWS Elemental MediaPackage 583 Amazon CloudFront Developer Guide Step 5: Use CloudFront to serve the VOD content After you create the distribution, add the origins, create the cache behaviors, and enable header- based CDN authorization, you can serve the VOD content using CloudFront. CloudFront routes requests from viewers to the correct MediaPackage VOD content based on the settings that you configured for the cache behaviors. For links in your application (for example, a media player), specify the URL for the media file in the standard format for CloudFront URLs. For more information, see the section called “Customize file URLs”. Media quality-aware resiliency Media quality-aware resiliency (MQAR) is an integrated capability between Amazon CloudFront and AWS Media Services. MQAR provides automated cross-Region origin selection based on Media Quality Confidence Score
AmazonCloudFront_DevGuide-220
AmazonCloudFront_DevGuide.pdf
220
and enable header- based CDN authorization, you can serve the VOD content using CloudFront. CloudFront routes requests from viewers to the correct MediaPackage VOD content based on the settings that you configured for the cache behaviors. For links in your application (for example, a media player), specify the URL for the media file in the standard format for CloudFront URLs. For more information, see the section called “Customize file URLs”. Media quality-aware resiliency Media quality-aware resiliency (MQAR) is an integrated capability between Amazon CloudFront and AWS Media Services. MQAR provides automated cross-Region origin selection based on Media Quality Confidence Score (MQCS). MQCS is synthesized by AWS Elemental MediaLive based on parameters that affect media quality experience perceived by viewers. You can configure CloudFront and AWS Media Services to deliver your live event streaming with high resiliency by using multiple options that you can specify in the CloudFront origin group failover criteria. When you enable the MQAR feature for your distribution, you authorize CloudFront to automatically select the origin that is deemed to have the highest quality score. The quality score represents perceived media streaming quality issues from your origins, such as black frames, frozen or dropped frames, or repeated frames. For example, if your AWS Elemental MediaPackage v2 origins are deployed in two different AWS Regions, and one reports a higher media quality score than the other, CloudFront will automatically switch to the origin that reports the higher score. To achieve this, CloudFront does the following: 1. CloudFront forwards a GET request to the primary MediaPackage origin, and also initiates a HEAD request to the secondary MediaPackage origin at the same time. CloudFront receives the media quality score in the response headers from each origin. 2. Next, CloudFront tracks the score for each origin and uses this information to determine the origin with the higher score when a new request arrives. The media quality score for your origins can change in real time. CloudFront determines this by consuming the MQCS changes, and switches between origins to ensure that viewers see the Media quality-aware resiliency 584 Amazon CloudFront Developer Guide higher media quality content. For more information, see Leveraging media quality scores with MediaPackage in the AWS Elemental MediaPackage V2 User Guide. MQAR helps CloudFront determine, as early as possible, whether there’s an issue that could potentially impact customers. For example, issues such as network connection, video processing, audio loss or drops, encoder speed problems can affect the media quality score for your viewers. MQAR provides seamless switching between origins, so that you can deploy a resilient, cross- Region end-to-end media delivery workflow on AWS, and provide quality content for your viewers. Note Currently, this feature only supports MediaPackage v2 origins. To enable this feature for your distribution, complete the following steps: 1. If you haven't already, create your MediaPackage v2 origins and enable this feature in your endpoint configuration. For a cross-region deployment, create a secondary channel in a different AWS Region with the same settings. For more information, see the following topics in the see the AWS Elemental MediaPackage V2 User Guide: • Create a channel and endpoint • Enable the media quality score 2. To use your MediaPackage v2 origins for CloudFront, create or update a CloudFront distribution. See Create a distribution and Update a distribution. 3. Create an origin group, and select your two origins as the primary and secondary. In your origin group, enable the Media quality score option. For more information, see Create an origin group. 4. In your cache behavior for your distribution, select the origin group that you created. We recommend that the cache behavior match the channel path pattern. If CloudFront determines that both MediaPackage v2 origins have the same score, then it forwards the request to the primary origin as listed in the origin group. If the initially selected origin responds with an error code matching the failover criteria you specified in your origin group, then CloudFront retries the request to the alternative origin in your origin group regardless of its media quality score. Media quality-aware resiliency 585 Amazon CloudFront Notes Developer Guide • CloudFront tracks the quality score for each cache behavior that utilizes an origin group enabled for media quality score. If the same origin group is used for multiple channels that emit a media quality score, create a separate cache behavior for each channel's path pattern to avoid mixing their scores. For more information about origin group quotas, see General quotas on distributions. • Currently, MQAR isn't available when you use a Lambda@Edge function in origin-facing triggers (origin request and origin response) that is associated with your distribution's cache behavior. For more information, see Cache behavior settings. • If you enabled the MQAR feature and origin access control (OAC), add the mediapackagev2:GetHeadObject action to the IAM policy. MQAR
AmazonCloudFront_DevGuide-221
AmazonCloudFront_DevGuide.pdf
221
quality score. If the same origin group is used for multiple channels that emit a media quality score, create a separate cache behavior for each channel's path pattern to avoid mixing their scores. For more information about origin group quotas, see General quotas on distributions. • Currently, MQAR isn't available when you use a Lambda@Edge function in origin-facing triggers (origin request and origin response) that is associated with your distribution's cache behavior. For more information, see Cache behavior settings. • If you enabled the MQAR feature and origin access control (OAC), add the mediapackagev2:GetHeadObject action to the IAM policy. MQAR requires this permission to send HEAD requests to the MediaPackage v2 origin. For more information about OAC, see Restrict access to an AWS Elemental MediaPackage v2 origin. MQAR log fields CloudFront provides the following fields in real-time logs to reflect the quality score and the selected origin. You can enable these fields in your CloudFront real-time logs: • r-host • sr-reason • x-edge-mqcs For more information, see Fields 65-67. MQAR log fields 586 Amazon CloudFront Developer Guide Customize at the edge with functions With Amazon CloudFront, you can write your own code to customize how your CloudFront distributions process HTTP requests and responses. The code runs close to your viewers (users) to minimize latency, and you don’t have to manage servers or other infrastructure. You can write code to manipulate the requests and responses that flow through CloudFront, perform basic authentication and authorization, generate HTTP responses at the edge, and more. The code that you write and attach to your CloudFront distribution is called an edge function. CloudFront provides two ways to write and manage edge functions: CloudFront Functions You can write lightweight functions in JavaScript for high-scale, latency-sensitive CDN customizations. The CloudFront Functions runtime environment offers submillisecond startup times, scales immediately to handle millions of requests per second, and is highly secure. CloudFront Functions is a native feature of CloudFront, which means you can build, test, and deploy your code entirely within CloudFront. Lambda@Edge Lambda@Edge is an extension of AWS Lambda that offers powerful and flexible computing for complex functions and full application logic closer to your viewers, and is highly secure. Lambda@Edge functions run in a Node.js or Python runtime environment. You publish them to a single AWS Region, but when you associate the function with a CloudFront distribution, Lambda@Edge automatically replicates your code around the world. If you run AWS WAF on CloudFront, you can use AWS WAF inserted headers for both CloudFront Functions and Lambda@Edge. This works for viewer and origin requests and responses. Topics • Differences between CloudFront Functions and Lambda@Edge • Customize at the edge with CloudFront Functions • Customize at the edge with Lambda@Edge • Restrictions on edge functions 587 Amazon CloudFront Developer Guide Differences between CloudFront Functions and Lambda@Edge CloudFront Functions and Lambda@Edge both provide a way to run code in response to CloudFront events. CloudFront Functions is ideal for lightweight, short-running functions for the following use cases: • Cache key normalization – Transform HTTP request attributes (headers, query strings, cookies, and even the URL path) to create an optimal cache key, which can improve your cache hit ratio. • Header manipulation – Insert, modify, or delete HTTP headers in the request or response. For example, you can add a True-Client-IP header to every request. • URL redirects or rewrites – Redirect viewers to other pages based on information in the request, or rewrite all requests from one path to another. • Request authorization – Validate hashed authorization tokens, such as JSON web tokens (JWT), by inspecting authorization headers or other request metadata. To get started with CloudFront Functions, see Customize at the edge with CloudFront Functions. Lambda@Edge is ideal for the following use cases: • Functions that take several milliseconds or more to complete • Functions that require adjustable CPU or memory • Functions that depend on third-party libraries (including the AWS SDK, for integration with other AWS services) • Functions that require network access to use external services for processing • Functions that require file system access or access to the body of HTTP requests To get started with Lambda@Edge, see Customize at the edge with Lambda@Edge. To help you choose the option for your use case, use the following table to understand the differences between CloudFront Functions and Lambda@Edge. Programming languages CloudFront Functions Lambda@Edge JavaScript (ECMAScript 5.1 compliant) Node.js and Python Differences between CloudFront Functions and Lambda@Edge 588 Amazon CloudFront Developer Guide CloudFront Functions Lambda@Edge Event sources • Viewer request • Viewer request • Viewer response • Viewer response • Origin request • Origin response Supports Amazon CloudFront KeyValueStore Yes No CloudFront KeyValueS tore only supports JavaScript runtime 2.0 Scale 10,000,000 requests per second or more Up to 10,000 requests per second per Region Function duration Submillisecond Maximum function
AmazonCloudFront_DevGuide-222
AmazonCloudFront_DevGuide.pdf
222
choose the option for your use case, use the following table to understand the differences between CloudFront Functions and Lambda@Edge. Programming languages CloudFront Functions Lambda@Edge JavaScript (ECMAScript 5.1 compliant) Node.js and Python Differences between CloudFront Functions and Lambda@Edge 588 Amazon CloudFront Developer Guide CloudFront Functions Lambda@Edge Event sources • Viewer request • Viewer request • Viewer response • Viewer response • Origin request • Origin response Supports Amazon CloudFront KeyValueStore Yes No CloudFront KeyValueS tore only supports JavaScript runtime 2.0 Scale 10,000,000 requests per second or more Up to 10,000 requests per second per Region Function duration Submillisecond Maximum function memory size 2 MB Up to 5 seconds (viewer request and viewer response) Up to 30 seconds (origin request and origin response) 128 MB (viewer request and viewer response) 10,240 MB (10 GB) (origin request and origin response) For more informati on, see Quotas on Lambda@Edge. Differences between CloudFront Functions and Lambda@Edge 589 Amazon CloudFront Developer Guide CloudFront Functions Lambda@Edge Maximum size of the function code and included libraries 10 KB Network access File system access Access to the request body No No No Access to geolocation and device data Yes 50 MB (viewer request and viewer response) 50 MB (origin request and origin response) Yes Yes Yes No (viewer request and viewer response) Yes (origin request and origin response) Can build and test entirely within CloudFront Function logging and metrics Yes Yes No Yes Pricing Free tier available; charged per request No free tier; charged per request and function duration Customize at the edge with CloudFront Functions With CloudFront Functions, you can write lightweight functions in JavaScript for high-scale, latency-sensitive CDN customizations. Your functions can manipulate the requests and responses that flow through CloudFront, perform basic authentication and authorization, generate HTTP responses at the edge, and more. The CloudFront Functions runtime environment offers submillisecond startup times, scales immediately to handle millions of requests per second, and is highly secure. CloudFront Functions is a native feature of CloudFront, which means you can build, test, and deploy your code entirely within CloudFront. Customize with CloudFront Functions 590 Amazon CloudFront Developer Guide When you associate a CloudFront function with a CloudFront distribution, CloudFront intercepts requests and responses at CloudFront edge locations and passes them to your function. You can invoke CloudFront Functions when the following events occur: • When CloudFront receives a request from a viewer (viewer request) • Before CloudFront returns the response to the viewer (viewer response) For more information about CloudFront Functions, see the following topics: Topics • Tutorial: Create a simple function with CloudFront Functions • Tutorial: Create a CloudFront function that includes key values • Write function code • Create functions • Test functions • Update functions • Publish functions • Associate functions with distributions • Amazon CloudFront KeyValueStore Tutorial: Create a simple function with CloudFront Functions This tutorial shows you how to get started with CloudFront Functions. You can create a simple function that redirects the viewer to a different URL, and that also returns a custom response header. Contents • Prerequisites • Create the function • Verify the function Tutorial: Create a simple CloudFront function 591 Amazon CloudFront Prerequisites Developer Guide To use CloudFront Functions, you need a CloudFront distribution. If you don’t have one, see Get started with a basic CloudFront distribution. Create the function You can use the CloudFront console to create a simple function that redirects the viewer to a different URL, and also returns a custom response header. To create a CloudFront function 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Functions, and then choose Create function. 3. On the Create function page, for Name, enter a function name such as MyFunctionName. 4. (Optional) For Description, enter a description for the function such as Simple test function. 5. For Runtime, keep the default selected JavaScript version. 6. Choose Create function. 7. Copy the following function code. This function code redirects the viewer to a different URL, and also returns a custom response header. function handler(event) { // NOTE: This example function is for a viewer request event trigger. // Choose viewer request for event trigger when you associate this function with a distribution. var response = { statusCode: 302, statusDescription: 'Found', headers: { 'cloudfront-functions': { value: 'generated-by-CloudFront-Functions' }, 'location': { value: 'https://aws.amazon.com/cloudfront/' } } }; return response; } 8. For Function code, paste the code into the code editor to replace the default code. Tutorial: Create a simple CloudFront function 592 Amazon CloudFront 9. Choose Save changes. Developer Guide 10. (Optional) You can test the function before you publish it. This tutorial doesn’t describe how to test a function. For more information, see Test functions. 11. Choose the Publish tab and then choose Publish function. You must
AmazonCloudFront_DevGuide-223
AmazonCloudFront_DevGuide.pdf
223
associate this function with a distribution. var response = { statusCode: 302, statusDescription: 'Found', headers: { 'cloudfront-functions': { value: 'generated-by-CloudFront-Functions' }, 'location': { value: 'https://aws.amazon.com/cloudfront/' } } }; return response; } 8. For Function code, paste the code into the code editor to replace the default code. Tutorial: Create a simple CloudFront function 592 Amazon CloudFront 9. Choose Save changes. Developer Guide 10. (Optional) You can test the function before you publish it. This tutorial doesn’t describe how to test a function. For more information, see Test functions. 11. Choose the Publish tab and then choose Publish function. You must publish the function before you can associate it with your CloudFront distribution. 12. Next, you can associate the function with a distribution or cache behavior. On the MyFunctionName page, choose the Publish tab. Warning In the following steps, choose a distribution or a cache behavior that’s used for testing. Don’t associate this test function with a distribution or cache behavior that’s used in production. 13. Choose Add association. 14. On the Associate dialog box, choose a distribution and/or a cache behavior. For Event type, keep the default value. 15. Choose Add association. The Associated distributions table shows the associated distribution. 16. Wait a few minutes for the associated distribution to finish deploying. To check the distribution’s status, select the distribution in the Associated distributions table and then choose View distribution. When the distribution’s status is Deployed, you’re ready to verify that the function works. Verify the function After you deploy the function, you can verify that it's working for your distribution. To verify the function 1. In your web browser, navigate to your distribution’s domain name (for example, https:// d111111abcdef8.cloudfront.net). The function returns a redirect to the browser, so the browser automatically goes to https:// aws.amazon.com/cloudfront/. Tutorial: Create a simple CloudFront function 593 Amazon CloudFront Developer Guide 2. In a command line window, you can use a tool like curl to send a request to your distribution’s domain name. curl -v https://d111111abcdef8.cloudfront.net/ In the response, you see the redirect response (302 Found) and the custom response headers that the function added. Your response might look like the following example. Example curl -v https://d111111abcdef8.cloudfront.net/ > GET / HTTP/1.1 > Host: d111111abcdef8.cloudfront.net > User-Agent: curl/7.64.1 > Accept: */* > < HTTP/1.1 302 Found < Server: CloudFront < Date: Tue, 16 Mar 2021 18:50:48 GMT < Content-Length: 0 < Connection: keep-alive < Location: https://aws.amazon.com/cloudfront/ < Cloudfront-Functions: generated-by-CloudFront-Functions < X-Cache: FunctionGeneratedResponse from cloudfront < Via: 1.1 3035b31bddaf14eded329f8d22cf188c.cloudfront.net (CloudFront) < X-Amz-Cf-Pop: PHX50-C2 < X-Amz-Cf-Id: ULZdIz6j43uGBlXyob_JctF9x7CCbwpNniiMlmNbmwzH1YWP9FsEHg== Tutorial: Create a CloudFront function that includes key values This tutorial shows you how to include key values with CloudFront function. Key values are part of a key-value pair. You include the name (from the key-value pair) in the function code. When the function runs, CloudFront replaces the name with the value. Key-value pairs are variables that are stored in a key value store. When you use a key in your function (instead of hard-coded values), your function is more flexible. You can change the value of the key without having to deploy code changes. Key-value pairs can also reduce the size of your function. For more information, see ???. Contents Tutorial: Create a CloudFront function that uses key values 594 Amazon CloudFront • Prerequisites • Create the key value store • Add key-value pairs to the key value store • Associate the key value store with the function • Test and publish the function code Prerequisites Developer Guide If you're new to CloudFront Functions functions and the key value store, we recommend that you follow the tutorial in the section called “Tutorial: Create a simple CloudFront function”. After you complete that tutorial, you can follow this tutorial to extend the function that you created. For this tutorial, we recommend that you create the key value store first. Create the key value store First, create the key value store to use for your function. To create the key value store 1. Plan the key-value pairs you want to include in the function. Make a note of key names. The key-value pairs that you want to use in a function must be in a single key value store. 2. Decide about the order of work. There are two ways to proceed: • Create a key value store, and add key-value pairs to the store. Then create (or modify) the function and incorporate the key names. • Or, create (or modify) the function and incorporate the key names you want to use. Then create a key value store, and add the key-value pairs. 3. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 4. In the navigation pane, choose Functions, and then choose the KeyValueStores tab. 5. Choose Create KeyValueStore and enter the following fields: •
AmazonCloudFront_DevGuide-224
AmazonCloudFront_DevGuide.pdf
224
the order of work. There are two ways to proceed: • Create a key value store, and add key-value pairs to the store. Then create (or modify) the function and incorporate the key names. • Or, create (or modify) the function and incorporate the key names you want to use. Then create a key value store, and add the key-value pairs. 3. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 4. In the navigation pane, choose Functions, and then choose the KeyValueStores tab. 5. Choose Create KeyValueStore and enter the following fields: • Enter a name and (optional) description for the store. • Leave S3 URI blank. In this tutorial you will enter the key-value pairs manually. 6. Choose Create. The details page for the new key value store appears. This page includes a Key value pairs section that is currently empty. Tutorial: Create a CloudFront function that uses key values 595 Amazon CloudFront Developer Guide Add key-value pairs to the key value store Next, manually add a list of key-value pairs to the key value store that you previously created. To add key-value pairs to the key value store 1. In the Key value pairs section, choose Add key value pairs. 2. Choose Add pair and then enter a key and value. Choose the check mark to confirm your changes and repeat this step to add more. 3. When you're finished, choose Save changes to save the key-value pairs in the key value store. On the confirmation dialog, choose Done. You now have a key value store that contains a group of key-value pairs. Associate the key value store with the function You have now created the key value store. And you have created or modified a function that includes the key names from the key value store. You can now associate the key value store and the function. You create that association from within the function. To associate the key value store with the function 1. In the navigation pane, choose Functions. The Functions tab appears on top, by default. 2. Choose the function name and in the Associated KeyValueStore section, choose Associate Existing KeyValueStore. 3. Select the key value store and choose Associate KeyValueStore. Note You can associate only one key value store with each function. Test and publish the function code After you associate the key value store with your function, you can test and publish the function code. You should always test the function code every time you modify it, including when you do the following: Tutorial: Create a CloudFront function that uses key values 596 Amazon CloudFront Developer Guide • Associate a key value store with the function. • Modify the function and its key value store to include a new key-value pair. • Change the value of a key-value pair. To test and publish the function code 1. For information about how to test a function, see the section called “Test functions”. Make sure that you choose to test the function in the DEVELOPMENT stage. 2. Publish the function when you're ready to use the function (with the new or revised key value pairs) in a LIVE environment. When you publish, CloudFront copies the version of the function from the DEVELOPMENT stage over to the live stage. The function has the new code and is associated with the key value store. (There is no need to perform the association again, in the live stage.) For information about how to publish the function, see the section called “Publish functions”. Write function code You can use CloudFront Functions to write lightweight functions in JavaScript for high-scale, latency-sensitive CDN customizations. Your function code can manipulate the requests and responses that flow through CloudFront, perform basic authentication and authorization, generate HTTP responses at the edge, and more. To help you write function code for CloudFront Functions, see the following topics. For code examples, see CloudFront Functions examples for CloudFront and the amazon-cloudfront- functions repository on GitHub. Topics • Determine function purpose • CloudFront Functions event structure • JavaScript runtime features for CloudFront Functions • Helper methods for key value stores • Helper methods for origin modification • Helper methods for CloudFront SaaS Manager properties Write function code 597 Amazon CloudFront • Use async and await Determine function purpose Developer Guide Before you write your function code, determine the purpose of your function. Most functions in CloudFront Functions have one of the following purposes. Topics • Modify the HTTP request in a viewer request event type • Generate an HTTP response in a viewer request event type • Modify the HTTP response in a viewer response event type • Related information Regardless of your function’s purpose, the handler is the entry point for any function. It takes a single argument called
AmazonCloudFront_DevGuide-225
AmazonCloudFront_DevGuide.pdf
225
CloudFront SaaS Manager properties Write function code 597 Amazon CloudFront • Use async and await Determine function purpose Developer Guide Before you write your function code, determine the purpose of your function. Most functions in CloudFront Functions have one of the following purposes. Topics • Modify the HTTP request in a viewer request event type • Generate an HTTP response in a viewer request event type • Modify the HTTP response in a viewer response event type • Related information Regardless of your function’s purpose, the handler is the entry point for any function. It takes a single argument called event, which is passed to the function by CloudFront. The event is a JSON object that contains a representation of the HTTP request (and the response, if your function modifies the HTTP response). Modify the HTTP request in a viewer request event type Your function can modify the HTTP request that CloudFront receives from the viewer (client), and return the modified request to CloudFront for continued processing. For example, your function code might normalize the cache key or modify request headers. After you create and publish a function that modifies the HTTP request, make sure to add an association for the viewer request event type. For more information, see Create the function. This makes the function run each time that CloudFront receives a request from a viewer, before checking to see whether the requested object is in the CloudFront cache. Example Example The following pseudocode shows the structure of a function that modifies the HTTP request. function handler(event) { var request = event.request; // Modify the request object here. Write function code 598 Amazon CloudFront Developer Guide return request; } The function returns the modified request object to CloudFront. CloudFront continues processing the returned request by checking the CloudFront cache for a cache hit, and sending the request to the origin if necessary. Generate an HTTP response in a viewer request event type Your function can generate an HTTP response at the edge and return it directly to the viewer (client) without checking for a cached response or any further processing by CloudFront. For example, your function code might redirect the request to a new URL, or check for authorization and return a 401 or 403 response to unauthorized requests. When you create a function that generates an HTTP response, make sure to choose the viewer request event type. This means that the function runs each time CloudFront receives a request from a viewer, before CloudFront does any further processing of the request. Example Example The following pseudocode shows the structure of a function that generates an HTTP response. function handler(event) { var request = event.request; var response = ...; // Create the response object here, // using the request properties if needed. return response; } The function returns a response object to CloudFront, which CloudFront immediately returns to the viewer without checking the CloudFront cache or sending a request to the origin. Modify the HTTP response in a viewer response event type Your function can modify the HTTP response before CloudFront sends it to the viewer (client), regardless of whether the response comes from the CloudFront cache or the origin. For example, your function code might add or modify response headers, status codes, and body content. Write function code 599 Amazon CloudFront Developer Guide When you create a function that modifies the HTTP response, make sure to choose the viewer response event type. This means that the function runs before CloudFront returns a response to the viewer, regardless of whether the response comes from the CloudFront cache or the origin. Example Example The following pseudocode shows the structure of a function that modifies the HTTP response. function handler(event) { var request = event.request; var response = event.response; // Modify the response object here, // using the request properties if needed. return response; } The function returns the modified response object to CloudFront, which CloudFront immediately returns to the viewer. Related information For more information about working with CloudFront Functions, see the following topics: • Event structure • JavaScript runtime features • CloudFront Functions examples • Restrictions on edge functions CloudFront Functions event structure CloudFront Functions passes an event object to your function code as input when it runs the function. When you test a function, you create the event object and pass it to your function. When you create an event object for testing a function, you can omit the distributionDomainName, distributionId, and requestId fields in the context object. Make sure that the names of headers are lowercase, which is always the case in the event object that CloudFront Functions passes to your function in production. The following shows an overview of the structure of this event object. Write function code 600 Amazon CloudFront Developer Guide { "version": "1.0",
AmazonCloudFront_DevGuide-226
AmazonCloudFront_DevGuide.pdf
226
to your function code as input when it runs the function. When you test a function, you create the event object and pass it to your function. When you create an event object for testing a function, you can omit the distributionDomainName, distributionId, and requestId fields in the context object. Make sure that the names of headers are lowercase, which is always the case in the event object that CloudFront Functions passes to your function in production. The following shows an overview of the structure of this event object. Write function code 600 Amazon CloudFront Developer Guide { "version": "1.0", "context": { <context object> }, "viewer": { <viewer object> }, "request": { <request object> }, "response": { <response object> } } For more information, see the following topics: Topics • Version field • Context object • Viewer object • Request object • Response object • Status code and body • Structure for a query string, header, or cookie • Example response object • Example event object Version field The version field contains a string that specifies the version of the CloudFront Functions event object. The current version is 1.0. Context object The context object contains contextual information about the event. It includes the following fields: Write function code 601 Amazon CloudFront distributionDomainName Developer Guide The CloudFront domain name (for example, d111111abcdef8.cloudfront.net) of the standard distribution that's associated with the event. The distributionDomainName field only appears when your function is invoked for standard distributions. endpoint The CloudFront domain name (for example, d111111abcdef8.cloudfront.net) of the connection group that's associated with the event. The endpoint field only appears when your function is invoked for multi-tenant distributions. distributionId The ID of the distribution (for example, EDFDVBD6EXAMPLE) that's associated with the event. eventType The event type, either viewer-request or viewer-response. requestId A string that uniquely identifies a CloudFront request (and its associated response). Viewer object The viewer object contains an ip field whose value is the IP address of the viewer (client) that sent the request. If the viewer request came through an HTTP proxy or a load balancer, the value is the IP address of the proxy or load balancer. Request object The request object contains a representation of a viewer-to-CloudFront HTTP request. In the event object that's passed to your function, the request object represents the actual request that CloudFront received from the viewer. If your function code returns a request object to CloudFront, it must use this same structure. The request object contains the following fields: Write function code 602 Amazon CloudFront method Developer Guide The HTTP method of the request. If your function code returns a request, it can't modify this field. This is the only read-only field in the request object. uri The relative path of the requested object. Note If your function modifies the uri value, the following applies: • The new uri value must begin with a forward slash (/). • When a function changes the uri value, it changes the object that the viewer is requesting. • When a function changes the uri value, it doesn't change the cache behavior for the request or the origin that an origin request is sent to. querystring An object that represents the query string in the request. If the request doesn't include a query string, the request object still includes an empty querystring object. The querystring object contains one field for each query string parameter in the request. headers An object that represents the HTTP headers in the request. If the request contains any Cookie headers, those headers are not part of the headers object. Cookies are represented separately in the cookies object. The headers object contains one field for each header in the request. Header names are converted to ASCII-lowercase in the event object, and header names must be ASCII-lowercase when they're added by your function code. When CloudFront Functions converts the event object back into an HTTP request, the first letter of each word in header names is capitalized, if it's an ASCII-letter. CloudFront Functions doesn't apply any changes to non-ASCII symbols in header names. For example, TÈst-header will become tÈst-header inside the function. The non-ASCII symbol È is unchanged. Write function code 603 Amazon CloudFront Developer Guide Words are separated by a hyphen (-). For example, if your function code adds a header named example-header-name, CloudFront converts this to Example-Header-Name in the HTTP request. cookies An object that represents the cookies in the request (Cookie headers). The cookies object contains one field for each cookie in the request. For more information about the structure of query strings, headers, and cookies, see Structure for a query string, header, or cookie. For an example event object, see Example event object. Response object The response object contains a representation of a CloudFront-to-viewer HTTP response. In the event object that's passed
AmazonCloudFront_DevGuide-227
AmazonCloudFront_DevGuide.pdf
227
Words are separated by a hyphen (-). For example, if your function code adds a header named example-header-name, CloudFront converts this to Example-Header-Name in the HTTP request. cookies An object that represents the cookies in the request (Cookie headers). The cookies object contains one field for each cookie in the request. For more information about the structure of query strings, headers, and cookies, see Structure for a query string, header, or cookie. For an example event object, see Example event object. Response object The response object contains a representation of a CloudFront-to-viewer HTTP response. In the event object that's passed to your function, the response object represents CloudFront's actual response to a viewer request. If your function code returns a response object, it must use this same structure. The response object contains the following fields: statusCode The HTTP status code of the response. This value is an integer, not a string. Your function can generate or modify the statusCode. statusDescription The HTTP status description of the response. If your function code generates a response, this field is optional. headers An object that represents the HTTP headers in the response. If the response contains any Set- Cookie headers, those headers are not part of the headers object. Cookies are represented separately in the cookies object. Write function code 604 Amazon CloudFront Developer Guide The headers object contains one field for each header in the response. Header names are converted to lowercase in the event object, and header names must be lowercase when they're added by your function code. When CloudFront Functions converts the event object back into an HTTP response, the first letter of each word in header names is capitalized. Words are separated by a hyphen (-). For example, if your function code adds a header named example- header-name, CloudFront converts this to Example-Header-Name in the HTTP response. cookies An object that represents the cookies in the response (Set-Cookie headers). The cookies object contains one field for each cookie in the response. body Adding the body field is optional, and it will not be present in the response object unless you specify it in your function. Your function does not have access to the original body returned by the CloudFront cache or origin. If you don't specify the body field in your viewer response function, the original body returned by the CloudFront cache or origin is returned to viewer. If you want CloudFront to return a custom body to the viewer, specify the body content in the data field, and the body encoding in the encoding field. You can specify the encoding as plain text ("encoding": "text") or as Base64-encoded content ("encoding": "base64"). As a shortcut, you can also specify the body content directly in the body field ("body": "<specify the body content here>"). When you do this, omit the data and encoding fields. CloudFront treats the body as plain text in this case. encoding The encoding for the body content (data field). The only valid encodings are text and base64. If you specify encoding as base64 but the body is not valid base64, CloudFront returns an error. data The body content. For more information about modified status codes and body content, see Status code and body. Write function code 605 Amazon CloudFront Developer Guide For more information about the structure of headers and cookies, see Structure for a query string, header, or cookie. For an example response object, see Example response object. Status code and body With CloudFront Functions, you can update the viewer response status code, replace the entire response body with a new one, or remove the response body. Some common scenarios for updating the viewer response after evaluating aspects of the response from the CloudFront cache or origin include the following: • Changing the status to set an HTTP 200 status code and creating static body content to return to the viewer. • Changing the status to set an HTTP 301 or 302 status code to redirect the user to another website. • Deciding whether to serve or drop the body of the viewer response. Note If the origin returns an HTTP error of 400 and above, the CloudFront Function will not run. For more information see Restrictions on all edge functions. When you're working with the HTTP response, CloudFront Functions does not have access to the response body. You can replace the body content by setting it to the desired value, or you can remove the body by setting the value to be empty. If you don't update the body field in your function, the original body returned by the CloudFront cache or origin is returned back to viewer. Tip When using CloudFront Functions to replace a body, be sure to align the corresponding headers, such as content-encoding, content-type, or content-length, to the new body
AmazonCloudFront_DevGuide-228
AmazonCloudFront_DevGuide.pdf
228
see Restrictions on all edge functions. When you're working with the HTTP response, CloudFront Functions does not have access to the response body. You can replace the body content by setting it to the desired value, or you can remove the body by setting the value to be empty. If you don't update the body field in your function, the original body returned by the CloudFront cache or origin is returned back to viewer. Tip When using CloudFront Functions to replace a body, be sure to align the corresponding headers, such as content-encoding, content-type, or content-length, to the new body content. For example, if the CloudFront origin or cache returns content-encoding: gzip but the viewer response function sets a body that's plain text, the function also needs to change the content-encoding and content-type headers accordingly. Write function code 606 Amazon CloudFront Developer Guide If your CloudFront Function is configured to return an HTTP error of 400 or above, your viewer will not see a custom error page that you have specified for the same status code. Structure for a query string, header, or cookie Query strings, headers, and cookies share the same structure. Query strings can appear in requests. Headers appear in requests and responses. Cookies appear in requests and responses. Each query string, header, or cookie is a unique field within the parent querystring, headers, or cookies object. The field name is the name of the query string, header, or cookie. Each field contains a value property with the value of the query string, header, or cookie. Contents • Query strings values or query string objects • Special considerations for headers • Duplicate query strings, headers, and cookies (multiValue array) • Cookie attributes Query strings values or query string objects A function can return a query string value in addition to a query string object. The query string value can be used to arrange the query string parameters in any custom order. Example Example To modify a query string in your function code, use code like the following. var request = event.request; request.querystring = 'ID=42&Exp=1619740800&TTL=1440&NoValue=&querymv=val1&querymv=val2,val3'; Special considerations for headers For headers only, the header names are converted to lowercase in the event object, and header names must be lowercase when they're added by your function code. When CloudFront Functions converts the event object back into an HTTP request or response, the first letter of each word in header names is capitalized. Words are separated by a hyphen (-). For example, if your function code adds a header named example-header-name, CloudFront converts this to Example- Header-Name in the HTTP request or response. Write function code 607 Amazon CloudFront Example Example Developer Guide Consider the following Host header in an HTTP request. Host: video.example.com This header is represented as follows in the request object: "headers": { "host": { "value": "video.example.com" } } To access the Host header in your function code, use code like the following: var request = event.request; var host = request.headers.host.value; To add or modify a header in your function code, use code like the following (this code adds a header named X-Custom-Header with the value example value): var request = event.request; request.headers['x-custom-header'] = {value: 'example value'}; Duplicate query strings, headers, and cookies (multiValue array) An HTTP request or response can contain more than one query string, header, or cookie with the same name. In this case, the duplicate query strings, headers, or cookies are collapsed into one field in the request or response object, but this field contains an extra property named multiValue. The multiValue property contains an array with the values of each of the duplicate query strings, headers, or cookies. Example Example Consider an HTTP request with the following Accept headers. Accept: application/json Write function code 608 Amazon CloudFront Accept: application/xml Accept: text/html Developer Guide These headers are represented as follows in the request object. "headers": { "accept": { "value": "application/json", "multiValue": [ { "value": "application/json" }, { "value": "application/xml" }, { "value": "text/html" } ] } } Note The first header value (in this case, application/json) is repeated in both the value and multiValue properties. This allows you to access all the values by looping through the multiValue array. If your function code modifies a query string, header, or cookie that has a multiValue array, CloudFront Functions uses the following rules to apply the changes: 1. If the multiValue array exists and has any modification, then that modification is applied. The first element in the value property is ignored. 2. Otherwise, any modification to the value property is applied, and subsequent values (if they exist) remain unchanged. The multiValue property is used only when the HTTP request or response contains duplicate query strings, headers, or cookies with the same name, as shown in the preceding example. Write function code 609 Amazon CloudFront Developer Guide
AmazonCloudFront_DevGuide-229
AmazonCloudFront_DevGuide.pdf
229
a query string, header, or cookie that has a multiValue array, CloudFront Functions uses the following rules to apply the changes: 1. If the multiValue array exists and has any modification, then that modification is applied. The first element in the value property is ignored. 2. Otherwise, any modification to the value property is applied, and subsequent values (if they exist) remain unchanged. The multiValue property is used only when the HTTP request or response contains duplicate query strings, headers, or cookies with the same name, as shown in the preceding example. Write function code 609 Amazon CloudFront Developer Guide However, if there are multiple values in a single query string, header, or cookie, the multiValue property is not used. Example Example Consider a request with one Accept header that contains three values. Accept: application/json, application/xml, text/html This header is represented as follows in the request object. "headers": { "accept": { "value": "application/json, application/xml, text/html" } } Cookie attributes In a Set-Cookie header in an HTTP response, the header contains the name–value pair for the cookie and optionally a set of attributes separated by semicolons. Example Example Set-Cookie: cookie1=val1; Secure; Path=/; Domain=example.com; Expires=Wed, 05 Apr 2021 07:28:00 GMT In the response object, these attributes are represented in the attributes property of the cookie field. For example, the preceding Set-Cookie header is represented as follows: "cookie1": { "value": "val1", "attributes": "Secure; Path=/; Domain=example.com; Expires=Wed, 05 Apr 2021 07:28:00 GMT" } Example response object The following example shows a response object — the output of a viewer response function — in which the body has been replaced by a viewer response function. Write function code 610 Developer Guide Amazon CloudFront { "response": { "statusCode": 200, "statusDescription": "OK", "headers": { "date": { "value": "Mon, 04 Apr 2021 18:57:56 GMT" }, "server": { "value": "gunicorn/19.9.0" }, "access-control-allow-origin": { "value": "*" }, "access-control-allow-credentials": { "value": "true" }, "content-type": { "value": "text/html" }, "content-length": { "value": "86" } }, "cookies": { "ID": { "value": "id1234", "attributes": "Expires=Wed, 05 Apr 2021 07:28:00 GMT" }, "Cookie1": { "value": "val1", "attributes": "Secure; Path=/; Domain=example.com; Expires=Wed, 05 Apr 2021 07:28:00 GMT", "multiValue": [ { "value": "val1", "attributes": "Secure; Path=/; Domain=example.com; Expires=Wed, 05 Apr 2021 07:28:00 GMT" }, { "value": "val2", "attributes": "Path=/cat; Domain=example.com; Expires=Wed, 10 Jan 2021 07:28:00 GMT" Write function code 611 Amazon CloudFront } ] } }, Developer Guide // Adding the body field is optional and it will not be present in the response object // unless you specify it in your function. // Your function does not have access to the original body returned by the CloudFront // cache or origin. // If you don't specify the body field in your viewer response function, the original // body returned by the CloudFront cache or origin is returned to viewer. "body": { "encoding": "text", "data": "<!DOCTYPE html><html><body><p>Here is your custom content.</p></body></ html>" } } } Example event object The following example shows a complete event object. This is an example invocation for a standard distribution, and not for a multi-tenant distribution. For multi-tenant distributions, the endpoint field is used instead of distributionDomainName The value of endpoint is the CloudFront domain name (for example, d111111abcdef8.cloudfront.net) of the connection group that’s associated with the event. Note The event object is the input to your function. Your function returns only the request or response object, not the complete event object. { "version": "1.0", "context": { "distributionDomainName": "d111111abcdef8.cloudfront.net", "distributionId": "EDFDVBD6EXAMPLE", Write function code 612 Amazon CloudFront Developer Guide "eventType": "viewer-response", "requestId": "EXAMPLEntjQpEXAMPLE_SG5Z-EXAMPLEPmPfEXAMPLEu3EqEXAMPLE==" }, "viewer": {"ip": "198.51.100.11"}, "request": { "method": "GET", "uri": "/media/index.mpd", "querystring": { "ID": {"value": "42"}, "Exp": {"value": "1619740800"}, "TTL": {"value": "1440"}, "NoValue": {"value": ""}, "querymv": { "value": "val1", "multiValue": [ {"value": "val1"}, {"value": "val2,val3"} ] } }, "headers": { "host": {"value": "video.example.com"}, "user-agent": {"value": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0"}, "accept": { "value": "application/json", "multiValue": [ {"value": "application/json"}, {"value": "application/xml"}, {"value": "text/html"} ] }, "accept-language": {"value": "en-GB,en;q=0.5"}, "accept-encoding": {"value": "gzip, deflate, br"}, "origin": {"value": "https://website.example.com"}, "referer": {"value": "https://website.example.com/videos/12345678? action=play"}, "cloudfront-viewer-country": {"value": "GB"} }, "cookies": { "Cookie1": {"value": "value1"}, "Cookie2": {"value": "value2"}, "cookie_consent": {"value": "true"}, "cookiemv": { Write function code 613 Amazon CloudFront Developer Guide "value": "value3", "multiValue": [ {"value": "value3"}, {"value": "value4"} ] } } }, "response": { "statusCode": 200, "statusDescription": "OK", "headers": { "date": {"value": "Mon, 04 Apr 2021 18:57:56 GMT"}, "server": {"value": "gunicorn/19.9.0"}, "access-control-allow-origin": {"value": "*"}, "access-control-allow-credentials": {"value": "true"}, "content-type": {"value": "application/json"}, "content-length": {"value": "701"} }, "cookies": { "ID": { "value": "id1234", "attributes": "Expires=Wed, 05 Apr 2021 07:28:00 GMT" }, "Cookie1": { "value": "val1", "attributes": "Secure; Path=/; Domain=example.com; Expires=Wed, 05 Apr 2021 07:28:00 GMT", "multiValue": [ { "value": "val1", "attributes": "Secure; Path=/; Domain=example.com; Expires=Wed, 05 Apr 2021 07:28:00 GMT" }, { "value": "val2", "attributes": "Path=/cat; Domain=example.com; Expires=Wed, 10 Jan 2021 07:28:00 GMT" } ] } } } Write function code 614 Amazon CloudFront }
AmazonCloudFront_DevGuide-230
AmazonCloudFront_DevGuide.pdf
230
"response": { "statusCode": 200, "statusDescription": "OK", "headers": { "date": {"value": "Mon, 04 Apr 2021 18:57:56 GMT"}, "server": {"value": "gunicorn/19.9.0"}, "access-control-allow-origin": {"value": "*"}, "access-control-allow-credentials": {"value": "true"}, "content-type": {"value": "application/json"}, "content-length": {"value": "701"} }, "cookies": { "ID": { "value": "id1234", "attributes": "Expires=Wed, 05 Apr 2021 07:28:00 GMT" }, "Cookie1": { "value": "val1", "attributes": "Secure; Path=/; Domain=example.com; Expires=Wed, 05 Apr 2021 07:28:00 GMT", "multiValue": [ { "value": "val1", "attributes": "Secure; Path=/; Domain=example.com; Expires=Wed, 05 Apr 2021 07:28:00 GMT" }, { "value": "val2", "attributes": "Path=/cat; Domain=example.com; Expires=Wed, 10 Jan 2021 07:28:00 GMT" } ] } } } Write function code 614 Amazon CloudFront } Developer Guide JavaScript runtime features for CloudFront Functions The CloudFront Functions JavaScript runtime environment is compliant with ECMAScript (ES) version 5.1 and also supports some features of ES versions 6 through 12. For the most up-to-date features, we recommend that you use JavaScript runtime 2.0. The JavaScript runtime 2.0 features has the following changes compared to 1.0: • Buffer module methods are available • The following non-standard string prototype methods are not available: • String.prototype.bytesFrom() • String.prototype.fromBytes() • String.prototype.fromUTF8() • String.prototype.toBytes() • String.prototype.toUTF8() • The cryptographic module has the following changes: • hash.digest() – Return type is changed to Buffer if no encoding is provided • hmac.digest() – Return type is changed to Buffer if no encoding is provided • For more information about additional new features, see JavaScript runtime 2.0 features for CloudFront Functions. Topics • JavaScript runtime 1.0 features for CloudFront Functions • JavaScript runtime 2.0 features for CloudFront Functions JavaScript runtime 1.0 features for CloudFront Functions The CloudFront Functions JavaScript runtime environment is compliant with ECMAScript (ES) version 5.1 and also supports some features of ES versions 6 through 9. It also provides some nonstandard methods that are not part of the ES specifications. The following topics list all the supported language features. Write function code 615 Developer Guide Amazon CloudFront Topics • Core features • Primitive objects • Built-in objects • Error types • Globals • Built-in modules • Restricted features Core features The following core features of ES are supported. Types All ES 5.1 types are supported. This includes Boolean values, numbers, strings, objects, arrays, functions, function constructors, and regular expressions. Operators All ES 5.1 operators are supported. The ES 7 exponentiation operator (**) is supported. Statements Note The const and let statements are not supported. The following ES 5.1 statements are supported: • break • catch • continue • do-while • else Write function code 616 Amazon CloudFront Developer Guide • finally • for • for-in • if • return • switch • throw • try • var • while • Labeled statements Literals ES 6 template literals are supported: multiline strings, expression interpolation, and nesting templates. Functions All ES 5.1 function features are supported. ES 6 arrow functions are supported, and ES 6 rest parameter syntax is supported. Unicode Source text and string literals can contain Unicode-encoded characters. Unicode code point escape sequences of six characters (for example, \uXXXX) are also supported. Strict mode Functions operate in strict mode by default, so you don’t need to add a use strict statement in your function code. This cannot be changed. Primitive objects The following primitive objects of ES are supported. Object The following ES 5.1 methods on objects are supported: Write function code 617 Amazon CloudFront Developer Guide • create (without properties list) • defineProperties • defineProperty • freeze • getOwnPropertyDescriptor • getOwnPropertyNames • getPrototypeOf • hasOwnProperty • isExtensible • isFrozen • prototype.isPrototypeOf • isSealed • keys • preventExtensions • prototype.propertyIsEnumerable • seal • prototype.toString • prototype.valueOf The following ES 6 methods on objects are supported: • assign • is • prototype.setPrototypeOf The following ES 8 methods on objects are supported: • entries • values String The following ES 5.1 methods on strings are supported: Write function code 618 Amazon CloudFront Developer Guide • fromCharCode • prototype.charAt • prototype.concat • prototype.indexOf • prototype.lastIndexOf • prototype.match • prototype.replace • prototype.search • prototype.slice • prototype.split • prototype.substr • prototype.substring • prototype.toLowerCase • prototype.trim • prototype.toUpperCase The following ES 6 methods on strings are supported: • fromCodePoint • prototype.codePointAt • prototype.endsWith • prototype.includes • prototype.repeat • prototype.startsWith The following ES 8 methods on strings are supported: • prototype.padStart • prototype.padEnd The following ES 9 methods on strings are supported: • prototype.trimStart Write function code 619 Amazon CloudFront • prototype.trimEnd Developer Guide The following nonstandard methods on strings are supported: • prototype.bytesFrom(array | string, encoding) Creates a byte string from an array of octets or an encoded string. The string encoding options are hex, base64, and base64url. • prototype.fromBytes(start[, end]) Creates a Unicode string from a byte string where each byte is replaced with the corresponding Unicode code point. • prototype.fromUTF8(start[, end]) Creates a Unicode string from a UTF-8 encoded byte string. If the encoding is incorrect, it
AmazonCloudFront_DevGuide-231
AmazonCloudFront_DevGuide.pdf
231
prototype.padStart • prototype.padEnd The following ES 9 methods on strings are supported: • prototype.trimStart Write function code 619 Amazon CloudFront • prototype.trimEnd Developer Guide The following nonstandard methods on strings are supported: • prototype.bytesFrom(array | string, encoding) Creates a byte string from an array of octets or an encoded string. The string encoding options are hex, base64, and base64url. • prototype.fromBytes(start[, end]) Creates a Unicode string from a byte string where each byte is replaced with the corresponding Unicode code point. • prototype.fromUTF8(start[, end]) Creates a Unicode string from a UTF-8 encoded byte string. If the encoding is incorrect, it returns null. • prototype.toBytes(start[, end]) Creates a byte string from a Unicode string. All characters must be in the [0,255] range. If not, it returns null. • prototype.toUTF8(start[, end]) Creates a UTF-8 encoded byte string from a Unicode string. Number All ES 5.1 methods on numbers are supported. The following ES 6 methods on numbers are supported: • isFinite • isInteger • isNaN • isSafeInteger • parseFloat • parseInt • prototype.toExponential • prototype.toFixed Write function code 620 Amazon CloudFront Developer Guide • prototype.toPrecision • EPSILON • MAX_SAFE_INTEGER • MAX_VALUE • MIN_SAFE_INTEGER • MIN_VALUE • NEGATIVE_INFINITY • NaN • POSITIVE_INFINITY Built-in objects The following built-in objects of ES are supported. Math All ES 5.1 math methods are supported. Note In the CloudFront Functions runtime environment, the Math.random() implementation uses OpenBSD arc4random seeded with the timestamp of when the function runs. The following ES 6 math methods are supported: • acosh • asinh • atanh • cbrt • clz32 • cosh • expm1 Write function code 621 Developer Guide Amazon CloudFront • fround • hypot • imul • log10 • log1p • log2 • sign • sinh • tanh • trunc • E • LN10 • LN2 • LOG10E • LOG2E • PI • SQRT1_2 • SQRT2 Date All ES 5.1 Date features are supported. Note For security reasons, Date always returns the same value—the function’s start time —during the lifetime of a single function run. For more information, see Restricted features. Function The apply, bind, and call methods are supported. Write function code 622 Amazon CloudFront Developer Guide Function constructors are not supported. Regular expressions All ES 5.1 regular expression features are supported. The regular expression language is Perl compatible. ES 9 named capture groups are supported. JSON All ES 5.1 JSON features are supported, including parse and stringify. Array The following ES 5.1 methods on arrays are supported: • isArray • prototype.concat • prototype.every • prototype.filter • prototype.forEach • prototype.indexOf • prototype.join • prototype.lastIndexOf • prototype.map • prototype.pop • prototype.push • prototype.reduce • prototype.reduceRight • prototype.reverse • prototype.shift • prototype.slice • prototype.some • prototype.sort • prototype.splice Write function code 623 Amazon CloudFront • prototype.unshift The following ES 6 methods on arrays are supported: Developer Guide • of • prototype.copyWithin • prototype.fill • prototype.find • prototype.findIndex The following ES 7 methods on arrays are supported: • prototype.includes Typed arrays The following ES 6 typed arrays are supported: • Int8Array • Uint8Array • Uint8ClampedArray • Int16Array • Uint16Array • Int32Array • Uint32Array • Float32Array • Float64Array • prototype.copyWithin • prototype.fill • prototype.join • prototype.set • prototype.slice • prototype.subarray • prototype.toString Write function code 624 Developer Guide Amazon CloudFront ArrayBuffer The following methods on ArrayBuffer are supported: • prototype.isView • prototype.slice Promise The following methods on promises are supported: • reject • resolve • prototype.catch • prototype.finally • prototype.then Crypto The cryptographic module provides standard hashing and hash-based message authentication code (HMAC) helpers. You can load the module using require('crypto'). The module exposes the following methods that behave exactly as their Node.js counterparts: • createHash(algorithm) • hash.update(data) • hash.digest([encoding]) • createHmac(algorithm, secret key) • hmac.update(data) • hmac.digest([encoding]) For more information, see Crypto (hash and HMAC) in the built-in modules section. Console This is a helper object for debugging. It only supports the log() method, to record log messages. Note CloudFront Functions doesn't support comma syntax, such as console.log('a', 'b'). Instead, use the console.log('a' + ' ' + 'b') format. Write function code 625 Amazon CloudFront Error types The following error objects are supported: Developer Guide • Error • EvalError • InternalError • MemoryError • RangeError • ReferenceError • SyntaxError • TypeError • URIError Globals The globalThis object is supported. The following ES 5.1 global functions are supported: • decodeURI • decodeURIComponent • encodeURI • encodeURIComponent • isFinite • isNaN • parseFloat • parseInt The following global constants are supported: • NaN • Infinity Write function code 626 Developer Guide Amazon CloudFront • undefined Built-in modules The following built-in modules are supported. Modules • Crypto (hash and HMAC) • Query string Crypto (hash and HMAC) The cryptographic module (crypto) provides standard hashing and hash-based message authentication code (HMAC) helpers. You can load the module using require('crypto'). The module provides the following methods that behave
AmazonCloudFront_DevGuide-232
AmazonCloudFront_DevGuide.pdf
232
Globals The globalThis object is supported. The following ES 5.1 global functions are supported: • decodeURI • decodeURIComponent • encodeURI • encodeURIComponent • isFinite • isNaN • parseFloat • parseInt The following global constants are supported: • NaN • Infinity Write function code 626 Developer Guide Amazon CloudFront • undefined Built-in modules The following built-in modules are supported. Modules • Crypto (hash and HMAC) • Query string Crypto (hash and HMAC) The cryptographic module (crypto) provides standard hashing and hash-based message authentication code (HMAC) helpers. You can load the module using require('crypto'). The module provides the following methods that behave exactly as their Node.js counterparts. Hashing methods crypto.createHash(algorithm) Creates and returns a hash object that you can use to generate hash digests using the given algorithm: md5, sha1, or sha256. hash.update(data) Updates the hash content with the given data. hash.digest([encoding]) Calculates the digest of all of the data passed using hash.update(). The encoding can be hex, base64, or base64url. HMAC methods crypto.createHmac(algorithm, secret key) Creates and returns an HMAC object that uses the given algorithm and secret key. The algorithm can be md5, sha1, or sha256. hmac.update(data) Updates the HMAC content with the given data. Write function code 627 Amazon CloudFront hmac.digest([encoding]) Developer Guide Calculates the digest of all of the data passed using hmac.update(). The encoding can be hex, base64, or base64url. Query string Note The CloudFront Functions event object automatically parses URL query strings for you. That means that in most cases you don’t need to use this module. The query string module (querystring) provides methods for parsing and formatting URL query strings. You can load the module using require('querystring'). The module provides the following methods. querystring.escape(string) URL-encodes the given string, returning an escaped query string. The method is used by querystring.stringify() and should not be used directly. querystring.parse(string[, separator[, equal[, options]]]) Parses a query string (string) and returns an object. The separator parameter is a substring for delimiting key and value pairs in the query string. By default it is &. The equal parameter is a substring for delimiting keys and values in the query string. By default it is =. The options parameter is an object with the following keys: decodeURIComponent function A function to decode percent-encoded characters in the query string. By default it is querystring.unescape(). maxKeys number The maximum number of keys to parse. By default it is 1000. Use a value of 0 to remove the limitations for counting keys. Write function code 628 Amazon CloudFront Developer Guide By default, percent-encoded characters within the query string are assumed to use the UTF-8 encoding. Invalid UTF-8 sequences are replaced with the U+FFFD replacement character. For example, for the following query string: 'name=value&abc=xyz&abc=123' The return value of querystring.parse() is: { name: 'value', abc: ['xyz', '123'] } querystring.decode() is an alias for querystring.parse(). querystring.stringify(object[, separator[, equal[, options]]]) Serializes an object and returns a query string. The separator parameter is a substring for delimiting key and value pairs in the query string. By default it is &. The equal parameter is a substring for delimiting keys and values in the query string. By default it is =. The options parameter is an object with the following keys: encodeURIComponent function The function to use for converting URL-unsafe characters to percent-encoding in the query string. By default it is querystring.escape(). By default, characters that require percent-encoding within the query string are encoded as UTF-8. To use a different encoding, specify the encodeURIComponent option. For example, for the following code: querystring.stringify({ name: 'value', abc: ['xyz', '123'], anotherName: '' }); The return value is: Write function code 629 Amazon CloudFront Developer Guide 'name=value&abc=xyz&abc=123&anotherName=' querystring.encode() is an alias for querystring.stringify(). querystring.unescape(string) Decodes URL percent-encoded characters in the given string, returning an unescaped query string. This method is used by querystring.parse() and should not be used directly. Restricted features The following JavaScript language features are either unsupported or restricted due to security concerns. Dynamic code evaluation Dynamic code evaluation is not supported. Both eval() and Function constructors throw an error if attempted. For example, const sum = new Function('a', 'b', 'return a + b') throws an error. Timers The setTimeout(), setImmediate(), and clearTimeout() functions are not supported. There is no provision to defer or yield within a function run. Your function must synchronously run to completion. Date and timestamps For security reasons, there is no access to high-resolution timers. All Date methods to query the current time always return the same value during the lifetime of a single function run. The returned timestamp is the time when the function started running. Consequently, you cannot measure elapsed time in your function. File system access There is no file system access. For example, there is no fs module for file system access like there is in Node.js. Process access There is no process access. For
AmazonCloudFront_DevGuide-233
AmazonCloudFront_DevGuide.pdf
233
or yield within a function run. Your function must synchronously run to completion. Date and timestamps For security reasons, there is no access to high-resolution timers. All Date methods to query the current time always return the same value during the lifetime of a single function run. The returned timestamp is the time when the function started running. Consequently, you cannot measure elapsed time in your function. File system access There is no file system access. For example, there is no fs module for file system access like there is in Node.js. Process access There is no process access. For example, there is no process global object for processing information access like there is in Node.js. Write function code 630 Amazon CloudFront Environment variables There is no access to environment variables. Developer Guide Instead, you can use CloudFront KeyValueStore to create a centralized datastore of key-value pairs for your CloudFront Functions. CloudFront KeyValueStore enables dynamic updates to your configuration data without needing to deploy code changes. You must use JavaScript runtime 2.0 to use CloudFront KeyValueStore. For more information, see Amazon CloudFront KeyValueStore. Network access There is no support for network calls. For example, XHR, HTTP(S), and socket are not supported. JavaScript runtime 2.0 features for CloudFront Functions The CloudFront Functions JavaScript runtime environment is compliant with ECMAScript (ES) version 5.1 and also supports some features of ES versions 6 through 12. It also provides some nonstandard methods that are not part of the ES specifications. The following topics list all supported features in this runtime. Topics • Core features • Primitive objects • Built-in objects • Error types • Globals • Built-in modules • Restricted features Core features The following core features of ES are supported. Types All ES 5.1 types are supported. This includes boolean values, numbers, strings, objects, arrays, functions, and regular expressions. Write function code 631 Amazon CloudFront Operators All ES 5.1 operators are supported. The ES 7 exponentiation operator (**) is supported. Statements The following ES 5.1 statements are supported: Developer Guide • break • catch • continue • do-while • else • finally • for • for-in • if • label • return • switch • throw • try • var • while The following ES 6 statements are supported: • async • await • const • let Note async, await, const, and let are supported in JavaScript runtime 2.0. Write function code 632 Amazon CloudFront Developer Guide await can be used inside async functions only. async arguments and closures are not supported. Literals ES 6 template literals are supported: multiline strings, expression interpolation, and nesting templates. Functions All ES 5.1 function features are supported. ES 6 arrow functions are supported, and ES 6 rest parameter syntax is supported. Unicode Source text and string literals can contain Unicode-encoded characters. Unicode code point escape sequences of six characters (for example, \uXXXX) are also supported. Strict mode Functions operate in strict mode by default, so you don’t need to add a use strict statement in your function code. This cannot be changed. Primitive objects The following primitive objects of ES are supported. Object The following ES 5.1 methods on objects are supported: • Object.create() (without properties list) • Object.defineProperties() • Object.defineProperty() • Object.freeze() • Object.getOwnPropertyDescriptor() • Object.getOwnPropertyDescriptors() • Object.getOwnPropertyNames() Write function code 633 Amazon CloudFront Developer Guide • Object.getPrototypeOf() • Object.isExtensible() • Object.isFrozen() • Object.isSealed() • Object.keys() • Object.preventExtensions() • Object.seal() The following ES 6 methods on objects are supported: • Object.assign() The following ES 8 methods on objects are supported: • Object.entries() • Object.values() The following ES 5.1 prototype methods on objects are supported: • Object.prototype.hasOwnProperty() • Object.prototype.isPrototypeOf() • Object.prototype.propertyIsEnumerable() • Object.prototype.toString() • Object.prototype.valueOf() The following ES 6 prototype methods on objects are supported: • Object.prototype.is() • Object.prototype.setPrototypeOf() String The following ES 5.1 methods on strings are supported: • String.fromCharCode() The following ES 6 methods on strings are supported: • String.fromCodePoint() Write function code 634 Amazon CloudFront Developer Guide The following ES 5.1 prototype methods on strings are supported: • String.prototype.charAt() • String.prototype.concat() • String.prototype.indexOf() • String.prototype.lastIndexOf() • String.prototype.match() • String.prototype.replace() • String.prototype.search() • String.prototype.slice() • String.prototype.split() • String.prototype.substr() • String.prototype.substring() • String.prototype.toLowerCase() • String.prototype.trim() • String.prototype.toUpperCase() The following ES 6 prototype methods on strings are supported: • String.prototype.codePointAt() • String.prototype.endsWith() • String.prototype.includes() • String.prototype.repeat() • String.prototype.startsWith() The following ES 8 prototype methods on strings are supported: • String.prototype.padStart() • String.prototype.padEnd() The following ES 9 prototype methods on strings are supported: • String.prototype.trimStart() • String.prototype.trimEnd() Write function code 635 Amazon CloudFront Developer Guide The following ES 12 prototype methods on strings are supported: • String.prototype.replaceAll() Note String.prototype.replaceAll() is new in JavaScript runtime 2.0. Number ALL ES 5 numbers are supported. The following ES 6 properties on numbers are supported: • Number.EPSILON • Number.MAX_SAFE_INTEGER • Number.MIN_SAFE_INTEGER • Number.MAX_VALUE • Number.MIN_VALUE • Number.NaN • Number.NEGATIVE_INFINITY • Number.POSITIVE_INFINITY
AmazonCloudFront_DevGuide-234
AmazonCloudFront_DevGuide.pdf
234
are supported: • String.prototype.codePointAt() • String.prototype.endsWith() • String.prototype.includes() • String.prototype.repeat() • String.prototype.startsWith() The following ES 8 prototype methods on strings are supported: • String.prototype.padStart() • String.prototype.padEnd() The following ES 9 prototype methods on strings are supported: • String.prototype.trimStart() • String.prototype.trimEnd() Write function code 635 Amazon CloudFront Developer Guide The following ES 12 prototype methods on strings are supported: • String.prototype.replaceAll() Note String.prototype.replaceAll() is new in JavaScript runtime 2.0. Number ALL ES 5 numbers are supported. The following ES 6 properties on numbers are supported: • Number.EPSILON • Number.MAX_SAFE_INTEGER • Number.MIN_SAFE_INTEGER • Number.MAX_VALUE • Number.MIN_VALUE • Number.NaN • Number.NEGATIVE_INFINITY • Number.POSITIVE_INFINITY The following ES 6 methods on numbers are supported: • Number.isFinite() • Number.isInteger() • Number.isNaN() • Number.isSafeInteger() • Number.parseInt() • Number.parseFloat() The following ES 5.1 prototype methods on numbers are supported: • Number.prototype.toExponential() • Number.prototype.toFixed() • Number.prototype.toPrecision() Write function code 636 Amazon CloudFront Developer Guide ES 12 numeric separators are supported. Note ES 12 numeric separators are new in JavaScript runtime 2.0. Built-in objects The following built-in objects of ES are supported. Math All ES 5.1 math methods are supported. Note In the CloudFront Functions runtime environment, the Math.random() implementation uses OpenBSD arc4random seeded with the timestamp of when the function runs. The following ES 6 math properties are supported: • Math.E • Math.LN10 • Math.LN2 • Math.LOG10E • Math.LOG2E • Math.PI • Math.SQRT1_2 • Math.SQRT2 The following ES 6 math methods are supported: • Math.abs() • Math.acos() Write function code 637 Amazon CloudFront Developer Guide • Math.acosh() • Math.asin() • Math.asinh() • Math.atan() • Math.atan2() • Math.atanh() • Math.cbrt() • Math.ceil() • Math.clz32() • Math.cos() • Math.cosh() • Math.exp() • Math.expm1() • Math.floor() • Math.fround() • Math.hypot() • Math.imul() • Math.log() • Math.log1p() • Math.log2() • Math.log10() • Math.max() • Math.min() • Math.pow() • Math.random() • Math.round() • Math.sign() • Math.sinh() Write function code 638 Amazon CloudFront Developer Guide • Math.sin() • Math.sqrt() • Math.tan() • Math.tanh() • Math.trunc() Date All ES 5.1 Date features are supported. Note For security reasons, Date always returns the same value—the function’s start time —during the lifetime of a single function run. For more information, see Restricted features. Function The following ES 5.1 prototype methods are supported: • Function.prototype.apply() • Function.prototype.bind() • Function.prototype.call() Function constructors are not supported. Regular expressions All ES 5.1 regular expression features are supported. The regular expression language is Perl compatible. The following ES 5.1 prototype accessor properties are supported: • RegExp.prototype.global • RegExp.prototype.ignoreCase • RegExp.protoype.multiline • RegExp.protoype.source Write function code 639 Amazon CloudFront Developer Guide • RegExp.prototype.sticky • RegExp.prototype.flags Note RegExp.prototype.sticky and RegExp.prototype.flags are new in JavaScript runtime 2.0. The following ES 5.1 prototype methods are supported: • RegExp.prototype.exec() • RegExp.prototype.test() • RegExp.prototype.toString() • RegExp.prototype[@@replace]() • RegExp.prototype[@@split]() Note RegExp.prototype[@@split]() is new in JavaScript runtime 2.0. The following ES 5.1 instance properties are supported: • lastIndex ES 9 named capture groups are supported. JSON The following ES 5.1 methods are supported: • JSON.parse() • JSON.stringify() Array The following ES 5.1 methods on arrays are supported: • Array.isArray() The following ES 6 methods on arrays are supported: Write function code 640 Amazon CloudFront • Array.of() The following ES 5.1 prototype methods are supported: Developer Guide • Array.prototype.concat() • Array.prototype.every() • Array.prototype.filter() • Array.prototype.forEach() • Array.prototype.indexOf() • Array.prototype.join() • Array.prototype.lastIndexOf() • Array.prototype.map() • Array.prototype.pop() • Array.prototype.push() • Array.prototype.reduce() • Array.prototype.reduceRight() • Array.prototype.reverse() • Array.prototype.shift() • Array.prototype.slice() • Array.prototype.some() • Array.prototype.sort() • Array.prototype.splice() • Array.prototype.unshift() The following ES 6 prototype methods are supported • Array.prototype.copyWithin() • Array.prototype.fill() • Array.prototype.find() • Array.prototype.findIndex() The following ES 7 prototype methods are supported: Write function code 641 Amazon CloudFront Developer Guide • Array.prototype.includes() Typed arrays The following ES 6 typed array constructors are supported: • Float32Array • Float64Array • Int8Array • Int16Array • Int32Array • Uint8Array • Uint8ClampedArray • Uint16Array • Uint32Array The following ES 6 methods are supported: • TypedArray.from() • TypedArray.of() Note TypedArray.from() and TypedArray.of() are new in JavaScript runtime 2.0. The following ES 6 prototype methods are supported: • TypedArray.prototype.copyWithin() • TypedArray.prototype.every() • TypedArray.prototype.fill() • TypedArray.prototype.filter() • TypedArray.prototype.find() • TypedArray.prototype.findIndex() • TypedArray.prototype.forEach() • TypedArray.prototype.includes() Write function code 642 Amazon CloudFront Developer Guide • TypedArray.prototype.indexOf() • TypedArray.prototype.join() • TypedArray.prototype.lastIndexOf() • TypedArray.prototype.map() • TypedArray.prototype.reduce() • TypedArray.prototype.reduceRight() • TypedArray.prototype.reverse() • TypedArray.prototype.some() • TypedArray.prototype.set() • TypedArray.prototype.slice() • TypedArray.prototype.sort() • TypedArray.prototype.subarray() • TypedArray.prototype.toString() Note TypedArray.prototype.every(), TypedArray.prototype.fill(), TypedArray.prototype.filter(), TypedArray.prototype.find(), TypedArray.prototype.findIndex(), TypedArray.prototype.forEach(), TypedArray.prototype.includes(), TypedArray.prototype.indexOf(), TypedArray.prototype.join(), TypedArray.prototype.lastIndexOf(),TypedArray.prototype.map(), TypedArray.prototype.reduce(), TypedArray.prototype.reduceRight(), TypedArray.prototype.reverse(), and TypedArray.prototype.some() are new in JavaScript runtime 2.0. ArrayBuffer The following ES 6 methods on ArrayBuffer are supported: • isView() The following ES 6 prototype methods on ArrayBuffer are supported: • ArrayBuffer.prototype.slice() Write function code 643 Amazon CloudFront Promise The following ES 6 methods on promises are supported: Developer Guide • Promise.all() • Promise.allSettled() • Promise.any() • Promise.reject() • Promise.resolve() • Promise.race() Note Promise.all(), Promise.allSettled(), Promise.any(), and Promise.race() are new in JavaScript runtime 2.0. The following ES 6 prototype methods on
AmazonCloudFront_DevGuide-235
AmazonCloudFront_DevGuide.pdf
235
TypedArray.prototype.sort() • TypedArray.prototype.subarray() • TypedArray.prototype.toString() Note TypedArray.prototype.every(), TypedArray.prototype.fill(), TypedArray.prototype.filter(), TypedArray.prototype.find(), TypedArray.prototype.findIndex(), TypedArray.prototype.forEach(), TypedArray.prototype.includes(), TypedArray.prototype.indexOf(), TypedArray.prototype.join(), TypedArray.prototype.lastIndexOf(),TypedArray.prototype.map(), TypedArray.prototype.reduce(), TypedArray.prototype.reduceRight(), TypedArray.prototype.reverse(), and TypedArray.prototype.some() are new in JavaScript runtime 2.0. ArrayBuffer The following ES 6 methods on ArrayBuffer are supported: • isView() The following ES 6 prototype methods on ArrayBuffer are supported: • ArrayBuffer.prototype.slice() Write function code 643 Amazon CloudFront Promise The following ES 6 methods on promises are supported: Developer Guide • Promise.all() • Promise.allSettled() • Promise.any() • Promise.reject() • Promise.resolve() • Promise.race() Note Promise.all(), Promise.allSettled(), Promise.any(), and Promise.race() are new in JavaScript runtime 2.0. The following ES 6 prototype methods on promises are supported: • Promise.prototype.catch() • Promise.prototype.finally() • Promise.prototype.then() DataView The following ES 6 prototype methods are supported: • DataView.prototype.getFloat32() • DataView.prototype.getFloat64() • DataView.prototype.getInt16() • DataView.prototype.getInt32() • DataView.prototype.getInt8() • DataView.prototype.getUint16() • DataView.prototype.getUint32() • DataView.prototype.getUint8() • DataView.prototype.setFloat32() Write function code 644 Amazon CloudFront Developer Guide • DataView.prototype.setFloat64() • DataView.prototype.setInt16() • DataView.prototype.setInt32() • DataView.prototype.setInt8() • DataView.prototype.setUint16() • DataView.prototype.setUint32() • DataView.prototype.setUint8() Note All Dataview ES 6 prototype methods are new in JavaScript runtime 2.0. Symbol The following ES 6 methods are supported: • Symbol.for() • Symbol.keyfor() Note All Symbol ES 6 methods are new in JavaScript runtime 2.0. Text Decoder The following prototype methods are supported: • TextDecoder.prototype.decode() The following prototype accessor properties are supported: • TextDecoder.prototype.encoding • TextDecoder.prototype.fatal • TextDecoder.prototype.ignoreBOM Text Encoder The following prototype methods are supported: • TextEncoder.prototype.encode() Write function code 645 Amazon CloudFront Developer Guide • TextEncoder.prototype.encodeInto() Error types The following error objects are supported: • Error • EvalError • InternalError • RangeError • ReferenceError • SyntaxError • TypeError • URIError Globals The globalThis object is supported. The following ES 5.1 global functions are supported: • decodeURI() • decodeURIComponent() • encodeURI() • encodeURIComponent() • isFinite() • isNaN() • parseFloat() • parseInt() The following ES 6 global functions are supported: • atob() • btoa() Write function code 646 Amazon CloudFront Note atob() and btoa() are new in JavaScript runtime 2.0. The following global constants are supported: Developer Guide • NaN • Infinity • undefined • arguments Built-in modules The following built-in modules are supported. Modules • Buffer • Query string • Crypto Buffer The module provides the following methods: • Buffer.alloc(size[, fill[, encoding]]) Allocate a Buffer. • size: Buffer size. Enter an integer. • fill: Optional. Enter a string, Buffer, Uint8Array, or integer. Default is 0. • encoding: Optional. When fill is a string, enter one of the following: utf8, hex, base64, base64url. Default is utf8. • Buffer.allocUnsafe(size) Allocate a non-initialized Buffer. Write function code 647 Amazon CloudFront • size: Enter an integer. • Buffer.byteLength(value[, encoding]) Developer Guide Return the length of a value, in bytes. • value: A string, Buffer, TypedArray, Dataview, or Arraybuffer. • encoding: Optional. When value is a string, enter one of the following: utf8, hex, base64, base64url. Default is utf8. • Buffer.compare(buffer1, buffer2) Compare two Buffers to help sort arrays. Returns 0 if they're the same, -1 if buffer1 comes first, or 1 if buffer2 comes first. • buffer1: Enter a Buffer. • buffer2: Enter a different Buffer. • Buffer.concat(list[, totalLength]) Concatenate multiple Buffers. Returns 0 if none. Returns up to totalLength. • list: Enter a list of Buffers. Note this will be truncated to totalLength. • totalLength: Optional. Enter an unsigned integer. Use sum of Buffer instances in list if blank. • Buffer.from(array) Create a Buffer from an array. • array: Enter a byte array from 0 to 255. • Buffer.from(arrayBuffer, byteOffset[, length])) Create a view from arrayBuffer, starting at offset byteOffset with length length. • arrayBuffer: Enter a Buffer array. • byteOffset: Enter an integer. • length: Optional. Enter an integer. • Buffer.from(buffer) Create a copy of the Buffer. • buffer: Enter a Buffer. • Buffer.from(object[, offsetOrEncoding[, length]]) Write function code 648 Amazon CloudFront Developer Guide Create a Buffer from an object. Returns Buffer.from(object.valueOf(), offsetOrEncoding, length) if valueOf() is not equal to the object. • object: Enter an object. • offsetOrEncoding: Optional. Enter an integer or encoding string. • length: Optional. Enter an integer. • Buffer.from(string[, encoding]) Create a Buffer from a string. • string: Enter a string. • encoding: Optional. Enter one of the following: utf8, hex, base64, base64url. Default is utf8. • Buffer.isBuffer(object) Check if object is a Buffer. Returns true or false. • object: Enter an object. • Buffer.isEncoding(encoding) Check if encoding is supported. Returns true or false. • encoding: Optional. Enter one of the following: utf8, hex, base64, base64url. Default is utf8. The module provides the following buffer prototype methods: • Buffer.prototype.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]]) Compare Buffer with target. Returns 0 if they're the same, 1 if buffer comes first, or -1 if target comes first. • target: Enter a Buffer. • targetStart: Optional. Enter an integer. Default is 0. • targetEnd: Optional. Enter an integer. Default is target length. • sourceStart: Optional. Enter an integer. Default is
AmazonCloudFront_DevGuide-236
AmazonCloudFront_DevGuide.pdf
236
or false. • object: Enter an object. • Buffer.isEncoding(encoding) Check if encoding is supported. Returns true or false. • encoding: Optional. Enter one of the following: utf8, hex, base64, base64url. Default is utf8. The module provides the following buffer prototype methods: • Buffer.prototype.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]]) Compare Buffer with target. Returns 0 if they're the same, 1 if buffer comes first, or -1 if target comes first. • target: Enter a Buffer. • targetStart: Optional. Enter an integer. Default is 0. • targetEnd: Optional. Enter an integer. Default is target length. • sourceStart: Optional. Enter an integer. Default is 0. • sourceEnd: Optional. Enter an integer. Default is Buffer length. • Buffer.prototype.copy(target[, targetStart[, sourceStart[, sourceEnd]]]) Write function code 649 Amazon CloudFront Copy buffer to target. Developer Guide • target: Enter a Buffer or Uint8Array. • targetStart: Optional. Enter an integer. Default is 0. • sourceStart: Optional. Enter an integer. Default is 0. • sourceEnd: Optional. Enter an integer. Default is Buffer length. • Buffer.prototype.equals(otherBuffer) Compare Buffer to otherBuffer. Returns true or false. • otherBuffer: Enter a string. • Buffer.prototype.fill(value[, offset[, end][, encoding]) Fill Buffer with value. • value: Enter a string, Buffer, or integer. • offset: Optional. Enter an integer. • end: Optional. Enter an integer. • encoding: Optional. Enter one of the following: utf8, hex, base64, base64url. Default is utf8. • Buffer.prototype.includes(value[, byteOffset][, encoding]) Search for value in Buffer. Returns true or false. • value: Enter a string, Buffer, Uint8Array, or integer. • byteOffset: Optional. Enter an integer. • encoding: Optional. Enter one of the following: utf8, hex, base64, base64url. Default is utf8. • Buffer.prototype.indexOf(value[, byteOffset][, encoding]) Search for first value in Buffer. Returns index if found; returns -1 if not found. • value: Enter a string, Buffer, Unit8Array, or integer from 0 to 255. • byteOffset: Optional. Enter an integer. • encoding: Optional. Enter one of the following if value is a string: utf8, hex, base64, base64url. Default is utf8. • Buffer.prototype.lastIndexOf(value[, byteOffset][, encoding]) Write function code 650 Amazon CloudFront Developer Guide Search for last value in Buffer. Returns index if found; returns -1 if not found. • value: Enter a string, Buffer, Unit8Array, or integer from 0 to 255. • byteOffset: Optional. Enter an integer. • encoding: Optional. Enter one of the following if value is a string: utf8, hex, base64, base64url. Default is utf8. • Buffer.prototype.readInt8(offset) Read Int8 at offset from Buffer. • offset: Enter an integer. • Buffer.prototype.readIntBE(offset, byteLength) Read Int as big-endian at offset from Buffer. • offset: Enter an integer. • byteLength: Optional. Enter an integer from 1 to 6. • Buffer.prototype.readInt16BE(offset) Read Int16 as big-endian at offset from Buffer. • offset: Enter an integer. • Buffer.prototype.readInt32BE(offset) Read Int32 as big-endian at offset from Buffer. • offset: Enter an integer. • Buffer.prototype.readIntLE(offset, byteLength) Read Int as little-endian at offset from Buffer. • offset: Enter an integer. • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.readInt16LE(offset) Read Int16 as little-endian at offset from Buffer. • offset: Enter an integer. • Buffer.prototype.readInt32LE(offset) Read Int32 as little-endian at offset from Buffer. Write function code 651 Developer Guide Amazon CloudFront • offset: Enter an integer. • Buffer.prototype.readUInt8(offset) Read UInt8 at offset from Buffer. • offset: Enter an integer. • Buffer.prototype.readUIntBE(offset, byteLength) Read UInt as big-endian at offset from Buffer. • offset: Enter an integer. • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.readUInt16BE(offset) Read UInt16 as big-endian at offset from Buffer. • • offset: Enter an integer. • Buffer.prototype.readUInt32BE(offset) Read UInt32 as big-endian at offset from Buffer. • offset: Enter an integer. • Buffer.prototype.readUIntLE(offset, byteLength) Read UInt as little-endian at offset from Buffer. • offset: Enter an integer. • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.readUInt16LE(offset) Read UInt16 as little-endian at offset from Buffer. • offset: Enter an integer. • Buffer.prototype.readUInt32LE(offset) Read UInt32 as little-endian at offset from Buffer. • offset: Enter an integer. • Buffer.prototype.readDoubleBE([offset]) Read a 64-bit double as big-endian at offset from Buffer. • offset: Optional. Enter an integer. Write function code 652 Amazon CloudFront Developer Guide • Buffer.prototype.readDoubleLE([offset]) Read a 64-bit double as little-endian at offset from Buffer. • offset: Optional. Enter an integer. • Buffer.prototype.readFloatBE([offset]) Read a 32-bit float as big-endian at offset from Buffer. • offset: Optional. Enter an integer. • Buffer.prototype.readFloatLE([offset]) Read a 32-bit float as little-endian at offset from Buffer. • offset: Optional. Enter an integer. • Buffer.prototype.subarray([start[, end]]) Returns a copy of Buffer that is offset and cropped with a new start and end. • start: Optional. Enter an integer. Default is 0. • end: Optional. Enter an integer. Default is buffer length. • Buffer.prototype.swap16() Swap the Buffer array byte order, treating it as an array of 16-bit numbers. Buffer length must be divisible by 2, or you will receive an error. • Buffer.prototype.swap32() Swap the Buffer array byte order,
AmazonCloudFront_DevGuide-237
AmazonCloudFront_DevGuide.pdf
237
Buffer. • offset: Optional. Enter an integer. • Buffer.prototype.readFloatLE([offset]) Read a 32-bit float as little-endian at offset from Buffer. • offset: Optional. Enter an integer. • Buffer.prototype.subarray([start[, end]]) Returns a copy of Buffer that is offset and cropped with a new start and end. • start: Optional. Enter an integer. Default is 0. • end: Optional. Enter an integer. Default is buffer length. • Buffer.prototype.swap16() Swap the Buffer array byte order, treating it as an array of 16-bit numbers. Buffer length must be divisible by 2, or you will receive an error. • Buffer.prototype.swap32() Swap the Buffer array byte order, treating it as an array of 32-bit numbers . Buffer length must be divisible by 4, or you will receive an error. • Buffer.prototype.swap64() Swap the Buffer array byte order, treating it as an array of 64-bit numbers. Buffer length must be divisible by 8, or you will receive an error. • Buffer.prototype.toJSON() Returns Buffer as a JSON. • Buffer.prototype.toString([encoding[, start[, end]]]) Convert Buffer, from start to end, to encoded string. Write function code 653 Amazon CloudFront Developer Guide • encoding: Optional. Enter one of the following: utf8, hex, base64, or base64url. Default is utf8. • start: Optional. Enter an integer. Default is 0. • end: Optional. Enter an integer. Default is buffer length. • Buffer.prototype.write(string[, offset[, length]][, encoding]) Write encoded string to Buffer if there is space, or a truncated string if there is not enough space. • string: Enter a string. • offset: Optional. Enter an integer. Default is 0. • length: Optional. Enter an integer. Default is the length of the string. • encoding: Optional. Optionally enter one of the following: utf8, hex, base64, or base64url. Default is utf8. • Buffer.prototype.writeInt8(value, offset, byteLength) Write Int8 value of byteLength at offset to Buffer. • value: Enter an integer. • offset: Enter an integer • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.writeIntBE(value, offset, byteLength) Write value at offset to Buffer, using big-endian. • value: Enter an integer. • offset: Enter an integer • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.writeInt16BE(value, offset, byteLength) Write value at offset to Buffer, using big-endian. • value: Enter an integer. • offset: Enter an integer • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.writeInt32BE(value, offset, byteLength) Write value at offset to Buffer, using big-endian. Write function code 654 Amazon CloudFront Developer Guide • value: Enter an integer. • offset: Enter an integer • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.writeIntLE(offset, byteLength) Write value at offset to Buffer, using little-endian. • offset: Enter an integer. • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.writeInt16LE(offset, byteLength) Write value at offset to Buffer, using little-endian. • offset: Enter an integer. • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.writeInt32LE(offset, byteLength) Write value at offset to Buffer, using little-endian. • offset: Enter an integer. • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.writeUInt8(value, offset, byteLength) Write UInt8 value of byteLength at offset to Buffer. • value: Enter an integer. • offset: Enter an integer • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.writeUIntBE(value, offset, byteLength) Write value at offset to Buffer, using big-endian. • value: Enter an integer. • offset: Enter an integer • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.writeUInt16BE(value, offset, byteLength) Write value at offset to Buffer, using big-endian. • value: Enter an integer. Write function code 655 Developer Guide Amazon CloudFront • offset: Enter an integer • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.writeUInt32BE(value, offset, byteLength) Write value at offset to Buffer, using big-endian. • value: Enter an integer. • offset: Enter an integer • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.writeUIntLE(value, offset, byteLength) Write value at offset to Buffer, using little-endian. • value: Enter an integer. • offset: Enter an integer • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.writeUInt16LE(value, offset, byteLength) Write value at offset to Buffer, using little-endian. • value: Enter an integer. • offset: Enter an integer • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.writeUInt32LE(value, offset, byteLength) Write value at offset to Buffer, using little-endian. • value: Enter an integer. • offset: Enter an integer • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.writeDoubleBE(value, [offset]) Write value at offset to Buffer, using big-endian. • value: Enter an integer. • offset: Optional. Enter an integer. Default is 0. • Buffer.prototype.writeDoubleLE(value, [offset]) Write value at offset to Buffer, using little-endian. Write function code 656 Developer Guide Amazon CloudFront • value: Enter an integer. • offset: Optional. Enter an integer. Default is 0. • Buffer.prototype.writeFloatBE(value, [offset]) Write value at offset to Buffer, using big-endian. • value: Enter an integer. • offset: Optional. Enter an integer. Default is 0. •
AmazonCloudFront_DevGuide-238
AmazonCloudFront_DevGuide.pdf
238
an integer. • offset: Enter an integer • byteLength: Enter an integer from 1 to 6. • Buffer.prototype.writeDoubleBE(value, [offset]) Write value at offset to Buffer, using big-endian. • value: Enter an integer. • offset: Optional. Enter an integer. Default is 0. • Buffer.prototype.writeDoubleLE(value, [offset]) Write value at offset to Buffer, using little-endian. Write function code 656 Developer Guide Amazon CloudFront • value: Enter an integer. • offset: Optional. Enter an integer. Default is 0. • Buffer.prototype.writeFloatBE(value, [offset]) Write value at offset to Buffer, using big-endian. • value: Enter an integer. • offset: Optional. Enter an integer. Default is 0. • Buffer.prototype.writeFloatLE(value, [offset]) Write value at offset to Buffer, using little-endian. • value: Enter an integer. • offset: Optional. Enter an integer. Default is 0. The following instance methods are supported: • buffer[index] Get and set octet (byte) at index in Buffer. • Get a number from 0 to 255. Or set a number from from 0 to 255. The following instance properties are supported: • buffer Get the ArrayBuffer object for the buffer. • byteOffset Get the byteOffset of the buffer's Arraybuffer object. • length Get the buffer byte count. Note All Buffer module methods are new in JavaScript runtime 2.0. Write function code 657 Amazon CloudFront Query string Note Developer Guide The CloudFront Functions event object automatically parses URL query strings for you. That means that in most cases you don’t need to use this module. The query string module (querystring) provides methods for parsing and formatting URL query strings. You can load the module using require('querystring'). The module provides the following methods. querystring.escape(string) URL-encodes the given string, returning an escaped query string. The method is used by querystring.stringify() and should not be used directly. querystring.parse(string[, separator[, equal[, options]]]) Parses a query string (string) and returns an object. The separator parameter is a substring for delimiting key and value pairs in the query string. By default it is &. The equal parameter is a substring for delimiting keys and values in the query string. By default it is =. The options parameter is an object with the following keys: decodeURIComponent function A function to decode percent-encoded characters in the query string. By default it is querystring.unescape(). maxKeys number The maximum number of keys to parse. By default it is 1000. Use a value of 0 to remove the limitations for counting keys. By default, percent-encoded characters within the query string are assumed to use the UTF-8 encoding. Invalid UTF-8 sequences are replaced with the U+FFFD replacement character. Write function code 658 Amazon CloudFront Developer Guide For example, for the following query string: 'name=value&abc=xyz&abc=123' The return value of querystring.parse() is: { name: 'value', abc: ['xyz', '123'] } querystring.decode() is an alias for querystring.parse(). querystring.stringify(object[, separator[, equal[, options]]]) Serializes an object and returns a query string. The separator parameter is a substring for delimiting key and value pairs in the query string. By default it is &. The equal parameter is a substring for delimiting keys and values in the query string. By default it is =. The options parameter is an object with the following keys: encodeURIComponent function The function to use for converting URL-unsafe characters to percent-encoding in the query string. By default it is querystring.escape(). By default, characters that require percent-encoding within the query string are encoded as UTF-8. To use a different encoding, specify the encodeURIComponent option. For example, for the following code: querystring.stringify({ name: 'value', abc: ['xyz', '123'], anotherName: '' }); The return value is: 'name=value&abc=xyz&abc=123&anotherName=' Write function code 659 Amazon CloudFront Developer Guide querystring.encode() is an alias for querystring.stringify(). querystring.unescape(string) Decodes URL percent-encoded characters in the given string, returning an unescaped query string. This method is used by querystring.parse() and should not be used directly. Crypto The cryptographic module (crypto) provides standard hashing and hash-based message authentication code (HMAC) helpers. You can load the module using require('crypto'). Hashing methods crypto.createHash(algorithm) Creates and returns a hash object that you can use to generate hash digests using the given algorithm: md5, sha1, or sha256. hash.update(data) Updates the hash content with the given data. hash.digest([encoding]) Calculates the digest of all of the data passed using hash.update(). The encoding can be hex, base64, or base64url. HMAC methods crypto.createHmac(algorithm, secret key) Creates and returns an HMAC object that uses the given algorithm and secret key. The algorithm can be md5, sha1, or sha256. hmac.update(data) Updates the HMAC content with the given data. hmac.digest([encoding]) Calculates the digest of all of the data passed using hmac.update(). The encoding can be hex, base64, or base64url. Write function code 660 Amazon CloudFront Restricted features Developer Guide The following JavaScript language features are either unsupported or restricted due to security concerns. Dynamic code evaluation Dynamic code evaluation is not supported. Both eval() and Function constructors throw an error if attempted. For example, const sum =
AmazonCloudFront_DevGuide-239
AmazonCloudFront_DevGuide.pdf
239
key) Creates and returns an HMAC object that uses the given algorithm and secret key. The algorithm can be md5, sha1, or sha256. hmac.update(data) Updates the HMAC content with the given data. hmac.digest([encoding]) Calculates the digest of all of the data passed using hmac.update(). The encoding can be hex, base64, or base64url. Write function code 660 Amazon CloudFront Restricted features Developer Guide The following JavaScript language features are either unsupported or restricted due to security concerns. Dynamic code evaluation Dynamic code evaluation is not supported. Both eval() and Function constructors throw an error if attempted. For example, const sum = new Function('a', 'b', 'return a + b') throws an error. Timers The setTimeout(), setImmediate(), and clearTimeout() functions are not supported. There is no provision to defer or yield within a function run. Your function must synchronously run to completion. Date and timestamps For security reasons, there is no access to high-resolution timers. All Date methods to query the current time always return the same value during the lifetime of a single function run. The returned timestamp is the time when the function started running. Consequently, you cannot measure elapsed time in your function. File system access There is no file system access. For example, there is no fs module for file system access like there is in Node.js. Process access There is no process access. For example, there is no process global object for processing information access like there is in Node.js. Environment variables There is no access to environment variables. Instead, you can use CloudFront KeyValueStore to create a centralized datastore of key-value pairs for your CloudFront Functions. CloudFront KeyValueStore enables dynamic updates to your configuration data without needing to deploy code changes. For more information, see Amazon CloudFront KeyValueStore. Network access There is no support for network calls. For example, XHR, HTTP(S), and socket are not supported. Write function code 661 Amazon CloudFront Developer Guide Helper methods for key value stores Note Key value store helper method calls from CloudFront Functions don't trigger an AWS CloudTrail data event. These events aren't logged in the CloudTrail event history. For more information, see Logging Amazon CloudFront API calls using AWS CloudTrail. This section applies if you use the CloudFront Key Value Store to include key values in the function that you create. CloudFront Functions has a module that provides three helper methods to read values from the key value store. To use this module in the function code, make sure that you have associated a key value store with the function. Next, include the following statements in the first lines of the function code: import cf from 'cloudfront'; const kvsHandle = cf.kvs(); get() method Use this method to return the key value for the key name that you specify. Request get("key", options); • key: The name of the key whose value needs to be fetched • options: There is one option, format. It ensures that the function parses the data correctly. Possible values: • string: (Default) UTF8 encoded • json • bytes: Raw binary data buffer Request example Write function code 662 Amazon CloudFront Developer Guide const value = await kvsHandle.get("myFunctionKey", { format: "string"}); Response The response is a promise that resolves to a value in the format requested by using options. By default, the value is returned as a string. Error handling The get() method will return an error when the key that you requested doesn't exist in the associated key value store. To manage this use case, you can add a try and catch block to your code. exists() method Use this method to identify whether or not the key exists in the key value store. Request exists("key"); Request example const exist = await kvsHandle.exists("myFunctionkey"); Response The response is a promise that returns a Boolean (true or false). This value specifies whether or not the key exists in the key value store. meta() method Use this method to return metadata about the key value store. Request meta(); Request example const meta = await kvsHandle.meta(); Write function code 663 Amazon CloudFront Response Developer Guide The response is a promise that resolves to an object with the following properties: • creationDateTime: The date and time that the key value store was created, in ISO 8601 format. • lastUpdatedDateTime: The date and time that the key value store was last synced from the source, in ISO 8601 format. The value doesn't include the propagation time to the edge. • keyCount: The total number of keys in the KVS after the last sync from the source. Response example {keyCount:3,creationDateTime:2023-11-30T23:07:55.765Z,lastUpdatedDateTime:2023-12-15T03:57:52.411Z} Helper methods for origin modification This section applies if you dynamically update or change the origin used on the request inside your CloudFront Functions code. You can update the origin on viewer request CloudFront Functions only. CloudFront Functions has a module that provides
AmazonCloudFront_DevGuide-240
AmazonCloudFront_DevGuide.pdf
240
was created, in ISO 8601 format. • lastUpdatedDateTime: The date and time that the key value store was last synced from the source, in ISO 8601 format. The value doesn't include the propagation time to the edge. • keyCount: The total number of keys in the KVS after the last sync from the source. Response example {keyCount:3,creationDateTime:2023-11-30T23:07:55.765Z,lastUpdatedDateTime:2023-12-15T03:57:52.411Z} Helper methods for origin modification This section applies if you dynamically update or change the origin used on the request inside your CloudFront Functions code. You can update the origin on viewer request CloudFront Functions only. CloudFront Functions has a module that provides helper methods to dynamically update or change the origin. To use this module, create a CloudFront function using JavaScript runtime 2.0 and include the following statement in the first line of the function code: import cf from 'cloudfront'; For more information, see JavaScript runtime 2.0 features for CloudFront Functions. Note The Test API and Test console pages don't test whether an origin modification has occurred. However, testing ensures that the function code executes without error. Choose between CloudFront Functions and Lambda@Edge You can update your origins by using either CloudFront Functions or Lambda@Edge. Write function code 664 Amazon CloudFront Developer Guide When using CloudFront Functions to update origins, you use the viewer request event trigger, which means this logic will run on every request when this function is used. When using Lambda@Edge, the origin updating capabilities are on the origin request event trigger, which means this logic only runs on cache misses. Your choice depends largely on your workload and any existing usage of CloudFront Functions and Lambda@Edge on your distributions. The following considerations can help you decide whether to use CloudFront Functions or Lambda@Edge to update your origins. CloudFront Functions is most useful in the following situations: • When your requests are dynamic (meaning they cannot be cached) and will always go to origin. CloudFront Functions provides better performance and lower overall cost. • When you already have an existing viewer request CloudFront function that will run on every request, you can add the origin updating logic into the existing function. To use CloudFront Functions to update origins, see the helper methods in the following topics. Lambda@Edge is most useful in the following situations: • When you have highly cacheable content, Lambda@Edge can be more cost-efficient because it runs only on cache misses, while CloudFront Functions runs on every request. • When you already have an existing origin request Lambda@Edge function, you can add the origin updating logic into the existing function. • When your origin update logic requires fetching data from third-party data sources, such as Amazon DynamoDB or Amazon S3. For more information about Lambda@Edge, see Customize at the edge with Lambda@Edge. updateRequestOrigin() method Use the updateRequestOrigin() method to update the origin settings for a request. You can use this method to update existing origin properties for origins that are already defined in your distribution, or to define a new origin for the request. To do so, specify the properties that you want to change. Write function code 665 Amazon CloudFront Important Developer Guide Any settings that you don't specify in the updateRequestOrigin() will inherit the same settings from the existing origin's configuration. The origin set by the updateRequestOrigin() method can be any HTTP endpoint and doesn't need to be an existing origin within your CloudFront distribution. Notes • If you're updating an origin that is part of an origin group, only the primary origin of the origin group is updated. The secondary origin remains unchanged. Any response code from the modified origin that matches the failover criteria will trigger a failover to the secondary origin. • If you are changing the origin type and have OAC enabled, make sure that the origin type in originAccessControlConfig matches the new origin type. • You can't use the updateRequestOrigin() method to update VPC origins. The request will fail. Request updateRequestOrigin({origin properties}) The origin properties can contain the following: domainName (optional) The domain name of the origin. If this is not provided, the domain name from the assigned origin is used instead. For custom origins Specify a DNS domain name, such as www.example.com. The domain name can't include a colon (:) and can't be an IP address. The domain name can be up to 253 characters. Write function code 666 Amazon CloudFront For S3 origins Developer Guide Specify the DNS domain name of the Amazon S3 bucket, such as amzn-s3-demo- bucket.s3.eu-west-1.amazonaws.com. The name can be up to 128 characters, and must be all lowercase. originPath (optional) The directory path at the origin where the request should locate content. The path should start with a forward slash (/) but shouldn't end with one. For example, it shouldn't end with example-path/. If this is not provided, then the origin path from the
AmazonCloudFront_DevGuide-241
AmazonCloudFront_DevGuide.pdf
241
(:) and can't be an IP address. The domain name can be up to 253 characters. Write function code 666 Amazon CloudFront For S3 origins Developer Guide Specify the DNS domain name of the Amazon S3 bucket, such as amzn-s3-demo- bucket.s3.eu-west-1.amazonaws.com. The name can be up to 128 characters, and must be all lowercase. originPath (optional) The directory path at the origin where the request should locate content. The path should start with a forward slash (/) but shouldn't end with one. For example, it shouldn't end with example-path/. If this is not provided, then the origin path from the assigned origin is used. For custom origins The path should be URL encoded and have a maximum length of 255 characters. customHeaders (optional) You can include custom headers with the request by specifying a header name and value pair for each custom header. The format is different than that of the request and response headers in the event structure. Use the following key-value pair syntax: {"key1": "value1", "key2": "value2", ...} You can't add headers that are disallowed, and a header with the same name can't also be present in the incoming request headers. Header name must be lowercase in your function code. When CloudFront Functions converts the event object back into an HTTP request, the first letter of each word in header names is capitalized, and words are separated by a hyphen. For example, if you function code adds a header named example-header-name, CloudFront converts this to Example-Header-Name in the HTTP request. For more information, see Custom headers that CloudFront can’t add to origin requests and Restrictions on edge functions. If this is not provided, then any custom headers from the assigned origin are used. connectionAttempts (optional) The number of times that CloudFront attempts to connect to the origin. The minimum is 1 and the maximum is 3. If this is not provided, the connection attempts from the assigned origin are used. Write function code 667 Amazon CloudFront originShield (optional) Developer Guide This enables or updates CloudFront Origin Shield. Using Origin Shield can help reduce the load on your origin. For more information, see Using Amazon CloudFront Origin Shield. If this is not provided, the Origin Shield settings from the assigned origin are used. enabled (required) Boolean expression to enable or disable Origin Shield. Accepts a true or false value. region (required when enabled) The AWS Region for Origin Shield. Specify the AWS Region that has the lowest latency to your origin. Use the Region code, not the Region name. For example, use us-east-2 to specify the US East (Ohio) Region. When you enable CloudFront Origin Shield, you must specify the AWS Region for it. For a list of available AWS Regions and help choosing the best Region for your origin, see Choosing the AWS Region for Origin Shield. originAccessControlConfig (optional) The unique identifier of an origin access control (OAC) for this origin. This is only used when the origin supports a CloudFront OAC, such as Amazon S3, Lambda function URLs, MediaStore, and MediaPackage V2. If this is not provided, then the OAC settings from the assigned origin are used. This does not support the legacy origin access identity (OAI). For more information, see Restrict access to an AWS origin. enabled (required) Boolean expression to enable or disable OAC. Accepts a true or false value. signingBehavior (required when enabled) Specifies which requests CloudFront signs (adds authentication information to). Specify always for the most common use case. For more information, see Advanced settings for origin access control. This field can have one of the following values: • always – CloudFront signs all origin requests, overwriting the Authorization header from the viewer request if one exists. Write function code 668 Amazon CloudFront Developer Guide • never – CloudFront doesn’t sign any origin requests. This value turns off origin access control for the origin. • no-override – If the viewer request doesn’t contain the Authorization header, then CloudFront signs the origin request. If the viewer request contains the Authorization header, then CloudFront doesn’t sign the origin request and instead passes along the Authorization header from the viewer request. Warning To pass along the Authorization header from the viewer request, you must add it to an origin request policy for all cache behaviors that use origins associated with this origin access control. For more information, see Control origin requests with a policy. signingProtocol (required when enabled) The signing protocol of the OAC, which determines how CloudFront signs (authenticates) requests. The only valid value is sigv4. originType (required when enabled) The type of origin for this OAC. Valid values include s3, mediapackagev2, mediastore, and lambda. timeouts (optional) Timeouts that you can specify for how long CloudFront should attempt to wait for origins to respond or send data. If this is not provided, then the timeout
AmazonCloudFront_DevGuide-242
AmazonCloudFront_DevGuide.pdf
242
to an origin request policy for all cache behaviors that use origins associated with this origin access control. For more information, see Control origin requests with a policy. signingProtocol (required when enabled) The signing protocol of the OAC, which determines how CloudFront signs (authenticates) requests. The only valid value is sigv4. originType (required when enabled) The type of origin for this OAC. Valid values include s3, mediapackagev2, mediastore, and lambda. timeouts (optional) Timeouts that you can specify for how long CloudFront should attempt to wait for origins to respond or send data. If this is not provided, then the timeout settings from the assigned origin are used. readTimeout (optional) Timeouts only apply to custom origins, not Amazon S3 origins. (S3 origin configurations will ignore these settings.) readTimeout applies to both of the following values: • How long (in seconds) CloudFront waits for a response after forwarding a request to the origin. • How long (in seconds) CloudFront waits after receiving a packet of a response from the origin and before receiving the next packet. The minimum timeout is 1 second and the maximum is 60 seconds. For more information, see Response timeout (custom and VPC origins only). Write function code 669 Amazon CloudFront Developer Guide keepAliveTimeout (optional) Timeouts only apply to custom origins, not Amazon S3 origins. (S3 origin configurations will ignore these settings.) keepAliveTimeout specifies how long CloudFront should try to maintain the connection to the origin after receiving the last packet of the response. The minimum timeout is 1 second and the maximum is 60 seconds. For more information, see Keep-alive timeout (custom and VPC origins only). connectionTimeout (optional) The number of seconds that CloudFront waits when trying to establish a connection to the origin. The minimum timeout is 1 second and the maximum is 10 seconds. For more information, see Connection timeout. customOriginConfig (optional) Use customOriginConfig to specify connection settings for origins that are not an Amazon S3 bucket. There is one exception: you can specify these settings if the S3 bucket is configured with static website hosting. (Other types of S3 bucket configurations will ignore these settings.) If customOriginConfig is not provided, then the settings from the assigned origin are used. port (required) The HTTP port that CloudFront uses to connect to the origin. Specify the HTTP port that the origin listens on. protocol (required) Specifies the protocol (HTTP or HTTPS) that CloudFront uses to connect to the origin. Valid values are as follows: • http – CloudFront always uses HTTP to connect to the origin • https – CloudFront always uses HTTPS to connect to the origin sslProtocols (required) A list that specifies the minimum SSL/TLS protocol that CloudFront uses when connecting to your origin over HTTPS. Valid values include SSLv3, TLSv1, TLSv1.1, and TLSv1.2. For more information, see Minimum origin SSL protocol. Example – Update to Amazon S3 request origin The following example changes the viewer request’s origin to an S3 bucket, enables OAC, and resets custom headers sent to the origin. Write function code 670 Amazon CloudFront Developer Guide cf.updateRequestOrigin({ "domainName" : "amzn-s3-demo-bucket-in-us-east-1.s3.us-east-1.amazonaws.com", "originAccessControlConfig": { "enabled": true, "signingBehavior": "always", "signingProtocol": "sigv4", "originType": "s3" }, // Empty object resets any header configured on the assigned origin "customHeaders": {} }); Example – Update to Application Load Balancer request origin The following example changes the viewer request’s origin to an Application Load Balancer origin and sets a custom header and timeouts. cf.updateRequestOrigin({ "domainName" : "example-1234567890.us-east-1.elb.amazonaws.com", "timeouts": { "readTimeout": 30, "connectionTimeout": 5 }, "customHeaders": { "x-stage": "production", "x-region": "us-east-1" } }); Example – Update to origin with Origin Shield enabled In the following example, the origin in the distribution has Origin Shield enabled. The function code updates only the domain name used for the origin and omits all the other optional parameters. In this case, Origin Shield will still be used with the modified origin domain name because the Origin Shield parameters were not updated. cf.updateRequestOrigin({ "domainName" : "www.example.com" }); Write function code 671 Amazon CloudFront Developer Guide selectRequestOriginById() method Use selectRequestOriginById() to update an existing origin by selecting a different origin that's already configured in your distribution. This method uses all the same settings that are defined by the updated origin. This method only accepts origins that are already defined in the same distribution used when running the function. Origins are referenced by the origin ID, which is the origin name that you defined when setting up the origin. If you have a VPC origin configured in your distribution, you can use this method to update your origin to your VPC origin. For more information, see Restrict access with VPC origins. Request selectRequestOriginById(origin_id) In the preceding example, origin_id is a string that points to the origin name of an origin in the distribution that's running the function. Example – Select Amazon S3 request origin The following
AmazonCloudFront_DevGuide-243
AmazonCloudFront_DevGuide.pdf
243
that are already defined in the same distribution used when running the function. Origins are referenced by the origin ID, which is the origin name that you defined when setting up the origin. If you have a VPC origin configured in your distribution, you can use this method to update your origin to your VPC origin. For more information, see Restrict access with VPC origins. Request selectRequestOriginById(origin_id) In the preceding example, origin_id is a string that points to the origin name of an origin in the distribution that's running the function. Example – Select Amazon S3 request origin The following example selects the origin named amzn-s3-demo-bucket-in-us-east-1 from the list of origins associated with the distribution, and applies the configuration settings of the amzn-s3-demo-bucket-in-us-east-1 origin to the request. cf.selectRequestOriginById("amzn-s3-demo-bucket-in-us-east-1"); Example – Select Application Load Balancer request origin The following example selects an Application Load Balancer origin named myALB-prod from the list of origins associated with the distribution, and applies the configuration settings of myALB- prod to the request. cf.selectRequestOriginById("myALB-prod"); createRequestOriginGroup() method Use createRequestOriginGroup() to define two origins to use as an origin group for failover in scenarios that require high availability. Write function code 672 Amazon CloudFront Developer Guide An origin group includes two origins (a primary and a secondary) and a failover criteria that you specify. You create an origin group to support origin failover in CloudFront. When you create or update an origin group using this method, you can specify the origin group instead of a single origin. CloudFront will failover from the primary origin to the secondary origin, using the failover criteria. If you have a VPC origin configured in your distribution, you can use this method to create an origin group using a VPC origin. For more information, see Restrict access with VPC origins. Request createRequestOriginGroup({origin_group_properties}) In the preceding example, the origin_group_properties can contain the following: originIds (required) Array of origin_ids, where the origin_id is a string that points to the origin name of an origin in the distribution running the function. You must provide two origins as part of the array. The first origin in the list is the primary origin and the second serves as the second origin for failover purposes. selectionCriteria (optional) Select whether to use the default origin failover criteria or to use the media-quality- score based failover logic. Valid values are as follows: • default uses the failover criteria, based on the status codes that are specified in the failoverCriteria. If you don't set selectionCriteria in the function, default will be used. • media-quality-score is used when the media aware routing capability is being used. failoverCriteria (required) An array of status codes that, when returned from the primary origin, will trigger CloudFront to failover to the secondary origin. If you overwrite an existing origin group, this array will overwrite all failover status codes that are set in the origin group's original configuration. When you use media-quality-score selectionCriteria, CloudFront will attempt to route requests based on the media quality score. If the selected origin returns an error code set in this array, CloudFront will failover to the other origin. Write function code 673 Amazon CloudFront Developer Guide Example – Create request origin group The following example creates an origin group for a request using the origin IDs. These origin IDs come from the origin group configuration for the distribution used to run this function. cf.createRequestOriginGroup({ originIds: ["us-east-1-s3-origin", "us-west-2-s3-origin"], failoverCriteria: { statusCodes: [500, 502, 503, 504] } }); Helper methods for CloudFront SaaS Manager properties Use the following helper functions for CloudFront SaaS Manager to retrieve values for your multi- tenant distributions in the function that you create. To use examples on this page, you must first create a CloudFront function by using JavaScript runtime 2.0. For more information, JavaScript runtime 2.0 features for CloudFront Functions. Topics • Connection groups • Distribution tenants Connection groups The connection group that is associated with your distribution tenants has a domain name. To get this value, use the endpoint field of the context subobject of the event object. Request const value = event.context.endpoint; Response The response is a string that contains the connection group's domain name, such as d111111abcdef8.cloudfront.net. The endpoint field only appears when your function is invoked for a multi-tenant distribution with an associated connection group. For more information, see Context object. Write function code 674 Amazon CloudFront Distribution tenants Developer Guide CloudFront Functions has a module that provides access to specific distribution tenant values. To use this module, include the following statement in the first line of your function code: import cf from 'cloudfront'; You can use the following examples only in the handler function, either directly or through any nested-call function. distributionTenant.id field Use this field to get the value of distribution tenant ID. Request const value = cf.distributionTenant.id; Response The response is
AmazonCloudFront_DevGuide-244
AmazonCloudFront_DevGuide.pdf
244
is invoked for a multi-tenant distribution with an associated connection group. For more information, see Context object. Write function code 674 Amazon CloudFront Distribution tenants Developer Guide CloudFront Functions has a module that provides access to specific distribution tenant values. To use this module, include the following statement in the first line of your function code: import cf from 'cloudfront'; You can use the following examples only in the handler function, either directly or through any nested-call function. distributionTenant.id field Use this field to get the value of distribution tenant ID. Request const value = cf.distributionTenant.id; Response The response is a string that contains the distribution tenant ID, such as dt_1a2b3c4d5e6f7. Error handling If your function is invoked for a standard distribution, specifying the distributionTenant.id field will return the distributionTenant module is not available type error. To handle this use case, you can add a try and catch block to your code. distributionTenant.parameters.get() method Use this method to return the value for the distribution tenant parameter names that you specified. distributionTenant.parameters.get("key"); key: The distribution tenant parameter name that you want to fetch the value for. Request Write function code 675 Amazon CloudFront Developer Guide const value = distributionTenant.parameters.get("key"); Response The response is a string that contains the value for the distribution tenant parameter. For example, if your key name is TenantPath, then the value for this parameter might be tenant1. Error handling You might receive the following errors: • If your function is invoked for a standard distribution, the distributionTenant.parameters.get() method will return the distributionTenant module is not available type error. • The DistributionTenantParameterKeyNotFound error is returned when the distribution tenant parameter that you specified doesn't exist. To manage these use cases, you can add a try and catch block to your code. Use async and await CloudFront Functions JavaScript runtime functions 2.0 provide async and await syntax to handle Promise objects. Promises represent delayed results that can be accessed via the await keyword in functions marked as async. Various new WebCrypto functions use Promises. For more information about Promise objects, see Promise. Note You must use JavaScript runtime 2.0 for the following code samples. await can be used inside async functions only. async arguments and closures are not supported. async function answer() { return 42; } // Note: async, await can be used only inside an async function. async arguments and closures are not supported. Write function code 676 Amazon CloudFront Developer Guide async function handler(event) { // var answer_value = answer(); // returns Promise, not a 42 value let answer_value = await answer(); // resolves Promise, 42 console.log("Answer"+answer_value); event.request.headers['answer'] = { value : ""+answer_value }; return event.request; } The following example JavaScript code shows how to view promises with the then chain method. You can use catch to view errors. async function answer() { return 42; } async function squared_answer() { return answer().then(value => value * value) } // Note: async, await can be used only inside an async function. async arguments and closures are not supported. async function handler(event) { // var answer_value = answer(); // returns Promise, not a 42 value let answer_value = await squared_answer(); // resolves Promise, 42 console.log("Answer"+answer_value); event.request.headers['answer'] = { value : ""+answer_value }; return event.request; } Create functions You create a function in two stages: 1. Create the function code as JavaScript. You can use the default example from the CloudFront console or write your own. For more information, see the following topics: • Write function code • the section called “Event structure” • CloudFront Functions examples for CloudFront 2. Use CloudFront to create the function and include your code. The code exists inside the function (not as a reference). Create functions 677 Amazon CloudFront Console To create a function Developer Guide 1. Sign in to the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/ home#/functions and choose the Functions page. 2. Choose Create function. 3. Enter a function name that is unique within the AWS account, choose the JavaScript version, and then choose Continue. The details page for the new function appears. Note To use key-value pairs in the function, you must choose JavaScript runtime 2.0. 4. In the Function code section, choose the Build tab and enter your function code. The sample code that is included in the Build tab illustrates the basic syntax for the function code. 5. Choose Save changes. 6. If the function code uses key-value pairs, you must associate a key value store. You can associate the key value store when you first create the function. Or, you can associate it later, by updating the function. To associate a key value store now, follow these steps: • • Go to the Associate KeyValueStore section and choose Associate existing KeyValueStore. Select the key value store that contains the key-value pairs in the function, and then choose Associate KeyValueStore. CloudFront immediately
AmazonCloudFront_DevGuide-245
AmazonCloudFront_DevGuide.pdf
245
that is included in the Build tab illustrates the basic syntax for the function code. 5. Choose Save changes. 6. If the function code uses key-value pairs, you must associate a key value store. You can associate the key value store when you first create the function. Or, you can associate it later, by updating the function. To associate a key value store now, follow these steps: • • Go to the Associate KeyValueStore section and choose Associate existing KeyValueStore. Select the key value store that contains the key-value pairs in the function, and then choose Associate KeyValueStore. CloudFront immediately associates the store with the function. You don't need to save the function. CLI If you use the CLI, you typically first create the function code in a file, and then create the function with the AWS CLI. Create functions 678 Amazon CloudFront To create a function Developer Guide 1. Create the function code in a file, and store it in a directory that your computer can connect to. 2. Run the command as shown in the example. This example uses the fileb:// notation to pass in the file. It also includes line breaks to make the command more readable. aws cloudfront create-function \ --name MaxAge \ --function-config '{"Comment":"Max Age 2 years","Runtime":"cloudfront- js-2.0","KeyValueStoreAssociations":{"Quantity":1,"Items": [{"KeyValueStoreARN":"arn:aws:cloudfront::111122223333:key-value-store/ a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"}]}}' \ --function-code fileb://function-max-age-v1.js Notes • Runtime – The version of JavaScript. To use key value pairs in the function, you must specify version 2.0. • KeyValueStoreAssociations – If your function uses key-value pairs, you can associate the key value store when you first create the function. Or, you can associate it later, by using update-function. The Quantity is always 1 because each function can have only one key value store associated with it. When the command is successful, you see output like the following. ETag: ETVABCEXAMPLE FunctionSummary: FunctionConfig: Comment: Max Age 2 years Runtime: cloudfront-js-2.0 KeyValueStoreAssociations= \ {Quantity=1, \ Items=[{KeyValueStoreARN='arn:aws:cloudfront::111122223333:key-value- store/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111'}]} \ FunctionMetadata: CreatedTime: '2021-04-18T20:38:56.915000+00:00' FunctionARN: arn:aws:cloudfront::111122223333:function/MaxAge Create functions 679 Amazon CloudFront Developer Guide LastModifiedTime: '2023-11-19T20:38:56.915000+00:00' Stage: DEVELOPMENT Name: MaxAge Status: UNPUBLISHED Location: https://cloudfront.amazonaws.com/2020-05-31/function/ arn:aws:cloudfront:::function/MaxAge Most of the information is repeated from the request. Other information is added by CloudFront. Notes • ETag – This value changes each time you modify the key value store. You use this value and the function name to reference the function in the future. Make sure that you always use the current ETag. • FunctionARN – The ARN for your CloudFront function. • 111122223333 – The AWS account. • Stage – The stage of the function (LIVE or DEVELOPMENT). • Status – The status of the function (PUBLISHED or UNPUBLISHED). After you create the function, it's added to the DEVELOPMENT stage. We recommend that you test your function before you publish it. After you publish your function, the function changes to the LIVE stage. Test functions Before you deploy the function to the live stage (production), you can test your function to verify that it works as intended. To test a function, you specify an event object that represents an HTTP request or response that your CloudFront distribution could receive in production. CloudFront Functions does the following: 1. Runs the function, using the provided event object as input. 2. Returns the function's result (the modified event object) along with any function logs or error messages and the function's compute utilization. For more information about compute utilization, see the section called “Understand compute utilization”. Test functions 680 Amazon CloudFront Note Developer Guide When you test a function, CloudFront only validates against function execution errors. CloudFront doesn't validate whether the request will flow through successfully once published. For example, if your function deletes a required header, the test will succeed because there isn't an issue with the code. However, if you publish the function and associate it with a distribution, the function will fail when a request was made through CloudFront. Contents • Set up the event object • Test the function • Understand compute utilization Set up the event object Before you test a function, you must set up the event object to test it with. There are several options. Option 1: Set up an event object without saving it You can set up an event object in the visual editor in the CloudFront console and not save it. You can use this event object to test the function from the CloudFront console, even though it's not saved. Option 2: Create an event object in the visual editor You can set up an event object in the visual editor in the CloudFront console and not save it. You can create 10 event objects for each function so that you can, for example, test different possible inputs. When you create the event object in this way, you can use the event object to test the function in the CloudFront console. You
AmazonCloudFront_DevGuide-246
AmazonCloudFront_DevGuide.pdf
246
editor in the CloudFront console and not save it. You can use this event object to test the function from the CloudFront console, even though it's not saved. Option 2: Create an event object in the visual editor You can set up an event object in the visual editor in the CloudFront console and not save it. You can create 10 event objects for each function so that you can, for example, test different possible inputs. When you create the event object in this way, you can use the event object to test the function in the CloudFront console. You can't use it to test the function using an AWS API or SDK. Test functions 681 Amazon CloudFront Developer Guide Option 3: Create an event object using a text editor You can use a text editor to create an event object in JSON format. For information about the structure of an event object, see Event structure. You can use this event object to test the function using the CLI. But you can't use it to test the function in the CloudFront console. To create an event object (option 1 or 2) 1. Sign in to the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home#/ functions and choose the Functions page. Choose the function that you want to test. 2. On the function details page, choose the Test tab. 3. For Event type, choose one of the following options: • Choose Viewer request if the function modifies an HTTP request or generates a response based on the request. The Request section appears. • Choose Viewer response. The Request and the Response sections appear. 4. Complete the fields to include in the event. You can choose Edit JSON to view the raw JSON. 5. (Optional) To save the event, choose Save and in the Save test event, enter a name and then choose Save. You can also choose Edit JSON and copy the raw JSON, and save it in your own file, outside of CloudFront. To create an event object (option 3) Create the event object using a text editor. Store the file in a directory that your computer can connect to. Verify that you follow these guidelines: • Omit the distributionDomainName, distributionId, and requestId fields. • The names of headers, cookies, and query strings must be lowercase. Test functions 682 Amazon CloudFront Developer Guide One option for creating an event object in this way is to create a sample using the visual editor. You can be sure that the sample is correctly formatted. You can then copy the raw JSON and paste it into a text editor and save the file. For more information about the structure of an event, see Event structure. Test the function You can test a function in the CloudFront console or with the AWS Command Line Interface (AWS CLI). Console To test the function 1. Sign in to the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/ home#/functions and choose the Functions page. 2. Choose the function that you want to test. 3. Choose the Test tab. 4. Make sure that the correct event is displayed. To switch from the currently displayed event, choose another event in the Select test event field. 5. Choose Test function. The console shows the output of the function, including function logs and compute utilization. CLI You can test a function by using the aws cloudfront test-function command. To test the function 1. Open a command line window. 2. Run the following command from the same directory that contains the specified file. This example uses the fileb:// notation to pass in the event object file. It also includes line breaks to make the command more readable. aws cloudfront test-function \ --name MaxAge \ --if-match ETVABCEXAMPLE \ Test functions 683 Amazon CloudFront Developer Guide --event-object fileb://event-maxage-test01.json \ --stage DEVELOPMENT Notes • You reference the function by its name and ETag (in the if-match parameter). You reference the event object by its location in your file system. • The stage can be DEVELOPMENT or LIVE. When the command is successful, you see output like the following. TestResult: ComputeUtilization: '21' FunctionErrorMessage: '' FunctionExecutionLogs: [] FunctionOutput: '{"response":{"headers":{"cloudfront-functions": {"value":"generated-by-CloudFront-Functions"},"location":{"value":"https:// aws.amazon.com/cloudfront/"}},"statusDescription":"Found","cookies": {},"statusCode":302}}' FunctionSummary: FunctionConfig: Comment: MaxAge function Runtime: cloudfront-js-2.0 KeyValueStoreAssociations= \ {Quantity=1, \ Items=[{KeyValueStoreARN='arn:aws:cloudfront::111122223333:key-value- store/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111'}]} \ FunctionMetadata: CreatedTime: '2021-04-18T20:38:56.915000+00:00' FunctionARN: arn:aws:cloudfront::111122223333:function/MaxAge LastModifiedTime: '2023-17-20T10:38:57.057000+00:00' Stage: DEVELOPMENT Name: MaxAge Status: UNPUBLISHED Test functions 684 Amazon CloudFront Notes Developer Guide • FunctionExecutionLogs contains a list of log lines that the function wrote in console.log() statements (if any). • ComputeUtilization contains information about running your function. See the section called “Understand compute utilization”. • FunctionOutput contains the event object that the function returned. Understand compute utilization Compute utilization is the amount of time that the function took to run as a percentage of the maximum allowed time. For example, a value of 35 means that the function completed in
AmazonCloudFront_DevGuide-247
AmazonCloudFront_DevGuide.pdf
247
\ FunctionMetadata: CreatedTime: '2021-04-18T20:38:56.915000+00:00' FunctionARN: arn:aws:cloudfront::111122223333:function/MaxAge LastModifiedTime: '2023-17-20T10:38:57.057000+00:00' Stage: DEVELOPMENT Name: MaxAge Status: UNPUBLISHED Test functions 684 Amazon CloudFront Notes Developer Guide • FunctionExecutionLogs contains a list of log lines that the function wrote in console.log() statements (if any). • ComputeUtilization contains information about running your function. See the section called “Understand compute utilization”. • FunctionOutput contains the event object that the function returned. Understand compute utilization Compute utilization is the amount of time that the function took to run as a percentage of the maximum allowed time. For example, a value of 35 means that the function completed in 35% of the maximum allowed time. If a function continuously exceeds the maximum allowed time, CloudFront throttles the function. The following list explains the likelihood of a function getting throttled based on the compute utilization value. Compute utilization value: • 1 – 50 – The function is comfortably below the maximum allowed time and should run without throttling. • 51 – 70 – The function is nearing the maximum allowed time. Consider optimizing the function code. • 71 – 100 – The function is very close to or exceeds the maximum allowed time. CloudFront is likely to throttle this function if you associate it with a distribution. Update functions You can update a function at any time. The changes are made only to the version of the function that is in the DEVELOPMENT stage. To copy the updates from the DEVELOPMENT stage to LIVE, you must publish the function. You can update a function's code in the CloudFront console or with the AWS Command Line Interface (AWS CLI). Update functions 685 Amazon CloudFront Console To update function code Developer Guide 1. Sign in to the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/ home#/functions and choose the Functions page. Choose the function to update. 2. Choose Edit and make the following changes: • Update any fields in the Details section. • Change or remove the associated key value store. For more information about key value stores, see the section called “ CloudFront KeyValueStore”. • Change the function code. Choose the Build tab, make changes, then choose Save changes to save changes to the code. CLI To update the function code 1. Open a command line window. 2. Run the following command. This example uses the fileb:// notation to pass in the file. It also includes line breaks to make the command more readable. aws cloudfront update-function \ --name MaxAge \ --function-config '{"Comment":"Max Age 2 years","Runtime":"cloudfront- js-2.0","KeyValueStoreAssociations":{"Quantity":1,"Items": [{"KeyValueStoreARN":"arn:aws:cloudfront::111122223333:key-value-store/ a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"}]}}' \ --function-code fileb://function-max-age-v1.js \ --if-match ETVABCEXAMPLE Update functions 686 Amazon CloudFront Developer Guide Notes • You can identify the function by both its name and ETag (in the if-match parameter). Make sure that you use the current ETag. You can get this value from the DescribeFunction API operation. • You must include the function-code, even if you don't want to change it. • Be careful with the function-config. You should pass everything that you want to keep in the configuration. Specifically, handle the key value store as follows: • To retain the existing key value store association (if there is one), specify the name of the existing store. • To change the association, specify the name of the new key value store. • To remove the association, omit the KeyValueStoreAssociations parameter. When the command is successful, you see output like the following. ETag: ETVXYZEXAMPLE FunctionSummary: FunctionConfig: Comment: Max Age 2 years \ Runtime: cloudfront-js-2.0 \ KeyValueStoreAssociations= \ {Quantity=1, \ Items=[{KeyValueStoreARN='arn:aws:cloudfront::111122223333:key-value- store/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111'}]} \ FunctionMetadata: \ CreatedTime: '2021-04-18T20:38:56.915000+00:00' \ FunctionARN: arn:aws:cloudfront::111122223333:function/MaxAge \ LastModifiedTime: '2023-12-19T23:41:15.389000+00:00' \ Stage: DEVELOPMENT \ Name: MaxAge \ Status: UNPUBLISHED Most of the information is repeated from the request. Other information is added by CloudFront. Update functions 687 Amazon CloudFront Notes Developer Guide • ETag – This value changes each time you modify the key value store. • FunctionARN – The ARN for your CloudFront function. • Stage – The stage for the function (LIVE or DEVELOPMENT). • Status – The status of the function (PUBLISHED or UNPUBLISHED). Publish functions When you publish your function, this copies the function from the DEVELOPMENT stage to the LIVE stage. If cache behaviors aren't associated with the function, publishing it enables you to associate it with a cache behavior. You can only associate cache behaviors with functions that are in the LIVE stage. Important • Before you publish, we recommend that you test the function. • After you publish the function, all cache behaviors that are associated with that function automatically start using the newly published copy, as soon as the distributions finish deploying. You can publish a function in the CloudFront console or with the AWS CLI. Console To publish a function 1. Sign in to the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/ home#/functions and choose the Functions page. 2. Choose the function to update. 3. Choose the Publish
AmazonCloudFront_DevGuide-248
AmazonCloudFront_DevGuide.pdf
248
behavior. You can only associate cache behaviors with functions that are in the LIVE stage. Important • Before you publish, we recommend that you test the function. • After you publish the function, all cache behaviors that are associated with that function automatically start using the newly published copy, as soon as the distributions finish deploying. You can publish a function in the CloudFront console or with the AWS CLI. Console To publish a function 1. Sign in to the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/ home#/functions and choose the Functions page. 2. Choose the function to update. 3. Choose the Publish tab and then choose Publish. If your function is already attached to one or more cache behaviors, choose Publish and update. Publish functions 688 Amazon CloudFront Developer Guide 4. (Optional) To see the distributions that are associated with the function, choose Associated CloudFront distributions to expand that section. When successful, a banner appears at the top of the page that says Function name published successfully. You can also choose the Build tab and then choose Live to see the live version of the function code. CLI To publish a function 1. Open a command line window. 2. Run the following aws cloudfront publish-function command. In the example, line breaks are provided to make the example more readable. aws cloudfront publish-function \ --name MaxAge \ --if-match ETVXYZEXAMPLE When the command is successful, you see output like the following. FunctionSummary: FunctionConfig: Comment: Max Age 2 years Runtime: cloudfront-js-2.0 FunctionMetadata: CreatedTime: '2021-04-18T21:24:21.314000+00:00' FunctionARN: arn:aws:cloudfront::111122223333:function/ExampleFunction LastModifiedTime: '2023-12-19T23:41:15.389000+00:00' Stage: LIVE Name: MaxAge Status: UNASSOCIATED Associate functions with distributions To use a function with a distribution, you associate the function with one or more cache behaviors in the distribution. You can associate a function with multiple cache behaviors in multiple distributions. Associate functions with distributions 689 Amazon CloudFront Developer Guide You can associate a function with any of the following: • An existing cache behavior • A new cache behavior in an existing distribution • A new cache behavior in a new distribution When you associate a function with a cache behavior, you must choose an event type. The event type determines when CloudFront runs the function. You can choose the following event types: • Viewer request – The function runs when CloudFront receives a request from a viewer. • Viewer response – The function runs before CloudFront returns a response to the viewer. You can't use origin-facing event types (origin request and origin response) with CloudFront Functions. Instead you can use Lambda@Edge. For more information, see CloudFront events that can trigger a Lambda@Edge function. Note Before you associate a function, you must publish it to the LIVE stage. You can associate a function with a distribution in the CloudFront console or with the AWS Command Line Interface (AWS CLI). The following procedure shows how to associate a function with an existing cache behavior. Console To associate a function with an existing cache behavior 1. Sign in to the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/ home#/functions and choose the Functions page. 2. Choose the function that you want to associate. 3. On the Function page, choose the Publish tab. 4. Choose Publish function. Associate functions with distributions 690 Amazon CloudFront Developer Guide 5. Choose Add association. On the dialog box that appears, choose a distribution, an event type, and/or a cache behavior. For the event type, choose when you want this function to run: • Viewer Request – Run the function every time CloudFront receives a request. • Viewer Response – Run the function every time CloudFront returns a response. 6. To save the configuration, choose Add association. CloudFront associates the distribution with the function. Wait a few minutes for the associated distribution to finish deploying. You can choose View distribution on the function details page to check the progress. CLI To associate a function with an existing cache behavior 1. Open a command line window. 2. Enter the following command to save the distribution configuration for the distribution whose cache behavior you want to associate with a function. This command saves the distribution configuration to a file named dist-config.yaml. To use this command, do the following: • Replace DistributionID with the distribution's ID. • Run the command on one line. In the example, line breaks are provided to make the example more readable. aws cloudfront get-distribution-config \ --id DistributionID \ --output yaml > dist-config.yaml When the command is successful, the AWS CLI returns no output. 3. Open the file named dist-config.yaml that you created. Edit the file to make the following changes. a. Rename the ETag field to IfMatch, but don't change the field's value. Associate functions with distributions 691 Amazon CloudFront Developer Guide b. In the cache behavior, find the object named FunctionAssociations. Update this object to add a function association. The YAML syntax for a
AmazonCloudFront_DevGuide-249
AmazonCloudFront_DevGuide.pdf
249
on one line. In the example, line breaks are provided to make the example more readable. aws cloudfront get-distribution-config \ --id DistributionID \ --output yaml > dist-config.yaml When the command is successful, the AWS CLI returns no output. 3. Open the file named dist-config.yaml that you created. Edit the file to make the following changes. a. Rename the ETag field to IfMatch, but don't change the field's value. Associate functions with distributions 691 Amazon CloudFront Developer Guide b. In the cache behavior, find the object named FunctionAssociations. Update this object to add a function association. The YAML syntax for a function association looks like the following example. • The following example shows a viewer request event type (trigger). To use a viewer response event type, replace viewer-request with viewer-response. • Replace arn:aws:cloudfront::111122223333:function/ExampleFunction with the Amazon Resource Name (ARN) of the function that you're associating with this cache behavior. To get the function ARN, you can use the aws cloudfront list- functions command. FunctionAssociations: Items: - EventType: viewer-request FunctionARN: arn:aws:cloudfront::111122223333:function/ExampleFunction Quantity: 1 c. After making these changes, save the file. 4. Use the following command to update the distribution, adding the function association. To use this command, do the following: • Replace DistributionID with the distribution's ID. • Run the command on one line. In the example, line breaks are provided to make the example more readable. aws cloudfront update-distribution \ --id DistributionID \ --cli-input-yaml file://dist-config.yaml When the command is successful, you see output like the following that describes the distribution that was just updated with the function association. The following example output is truncated for readability. Distribution: ARN: arn:aws:cloudfront::111122223333:distribution/EBEDLT3BGRBBW ... truncated ... DistributionConfig: Associate functions with distributions 692 Amazon CloudFront Developer Guide ... truncated ... DefaultCacheBehavior: ... truncated ... FunctionAssociations: Items: - EventType: viewer-request FunctionARN: arn:aws:cloudfront::111122223333:function/ExampleFunction Quantity: 1 ... truncated ... DomainName: d111111abcdef8.cloudfront.net Id: EDFDVBD6EXAMPLE LastModifiedTime: '2021-04-19T22:39:09.158000+00:00' Status: InProgress ETag: E2VJGGQEG1JT8S The distribution's Status changes to InProgress while the distribution is redeployed. When the new distribution configuration reaches a CloudFront edge location, that edge location starts using the associated function. When the distribution is fully deployed, the Status changes back to Deployed. This indicates that the associated CloudFront function is live in all CloudFront edge locations worldwide. This typically takes a few minutes. Amazon CloudFront KeyValueStore CloudFront KeyValueStore is a secure, global, low-latency key value datastore that allows read access from within CloudFront Functions, enabling advanced customizable logic at the CloudFront edge locations. With CloudFront KeyValueStore, you make updates to function code and updates to the data associated with a function independently of each other. This separation simplifies function code and makes it easy to update data without the need to deploy code changes. Note To use CloudFront KeyValueStore, your CloudFront function must use JavaScript runtime 2.0. The following is the general procedure for using key-value pairs: CloudFront KeyValueStore 693 Amazon CloudFront Developer Guide • Create key value stores, and populate it with a set of key-value pairs. You can add your key value stores to an Amazon S3 bucket or enter them manually. • Associate the key value stores with your CloudFront function. • Within your function code, use the name of the key to either retrieve the value associated with the key or to evaluate if a key exists. For more information about using key-value pairs in function code, and about helper methods, see the section called “Helper methods for key value stores”. Use cases You can use key-value pairs for the following examples: • URL rewrites or redirects – The key-value pair can hold the rewritten URLs or the redirect URLs. • A/B testing and feature flags – You can create a function to run experiments by assigning a percentage of traffic to a specific version of your website. • Access authorization – You can implement access control to allow or deny requests based on criteria defined by you and the data stored in a key value store. Supported formats for values You can store the value in a key-value pair in any of the following formats: • String • Byte-encoded string • JSON Security The CloudFront function and all its key value stores data are handled securely, as follows: • CloudFront encrypts each key value stores at rest and during transit (when reading or writing to the key value stores) when you call the CloudFront KeyValueStore API operations. • When the function is run, CloudFront decrypts each key-value pair in memory at the CloudFront edge locations. To get started with CloudFront KeyValueStore, see the following topics. CloudFront KeyValueStore 694 Amazon CloudFront Topics • Work with key value store • Work with key value data Developer Guide • For more information about getting started with CloudFront KeyValueStore, see the Introducing Amazon CloudFront KeyValueStore AWS blog post. Work with key value store You must create a key value