Sub topic 13
Adding security and CORS headers with response headers policies
This chapter assumes you can read a CloudFormation template and have a working distribution with an S3 origin, as built in the earlier chapters. It also assumes you know what an HTTP response header is and have seen a CORS error in a browser console.
Why S3 alone is not enough
S3 returns the headers you store with an object, such as Content-Type and Cache-Control. It does not add browser security headers like Strict-Transport-Security. It also sends CORS headers only if you configure CORS on the bucket and the request reaches S3 with an Origin header.
A response headers policy fixes both problems at the edge. It is a reusable object that tells CloudFront which headers to add to responses, or which to remove. You attach it to a cache behavior, so one policy can cover many distributions.
How a policy is applied
CloudFront adds the headers just before it sends the response to the viewer. This happens on cache hits and cache misses alike. The headers are not stored with the cached object.
Two consequences follow:
- You can change a policy without invalidating anything. Cached objects pick up the new headers once the change has propagated.
- You do not need to re-upload objects to S3 to change a header.
The three kinds of settings
A custom policy has up to four sections. All are optional.
| Section | What it controls | Example headers |
|---|---|---|
| CORS | Cross-origin permissions | `Access-Control-Allow-Origin`, `Access-Control-Allow-Methods`, `Access-Control-Max-Age` |
| Security headers | Browser hardening | `Strict-Transport-Security`, `Content-Security-Policy`, `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy` |
| Custom headers | Any header name and value you choose | `Permissions-Policy`, `Cache-Control` |
| Remove headers | Headers to strip from the origin response | `Server`, `x-amz-server-side-encryption` |
CloudFront also offers managed policies. Their names include SimpleCORS, CORS-With-Preflight, and SecurityHeadersPolicy. List them with the CLI:
aws cloudfront list-response-headers-policies --type managed \
--query "ResponseHeadersPolicyList.Items[].ResponseHeadersPolicy.{Id:Id,Name:ResponseHeadersPolicyConfig.Name}" \
--output tableManaged policies are a good start. They cannot be edited, so you create a custom policy as soon as you need your own allowed origins or a Content-Security-Policy.
The Override flag
Each header in a policy has an Override setting. It decides what happens when S3 already sent the same header.
Override: true: CloudFront replaces the origin's value with the policy's value.Override: false: CloudFront keeps the origin's value and uses the policy value only if the origin sent none.
Use true for headers you want to enforce everywhere. Use false when individual objects may legitimately set their own value. For CORS, the equivalent setting is OriginOverride.
Writing a custom policy
This CloudFormation excerpt defines a policy for a static site that is also fetched by a separate web app at https://app.example.com. The bucket SiteBucket and the distribution come from earlier chapters.
Resources:
SiteHeadersPolicy:
Type: AWS::CloudFront::ResponseHeadersPolicy
Properties:
ResponseHeadersPolicyConfig:
Name: site-security-and-cors
Comment: Security headers and CORS for the static site
CorsConfig:
AccessControlAllowCredentials: false
AccessControlAllowHeaders:
Items:
- Content-Type
AccessControlAllowMethods:
Items:
- GET
- HEAD
- OPTIONS
AccessControlAllowOrigins:
Items:
- https://app.example.com
AccessControlExposeHeaders:
Items:
- ETag
AccessControlMaxAgeSec: 600
OriginOverride: true
SecurityHeadersConfig:
StrictTransportSecurity:
AccessControlMaxAgeSec: 31536000
IncludeSubdomains: true
Preload: false
Override: true
ContentTypeOptions:
Override: true
FrameOptions:
FrameOption: DENY
Override: true
ReferrerPolicy:
ReferrerPolicy: strict-origin-when-cross-origin
Override: true
ContentSecurityPolicy:
ContentSecurityPolicy: "default-src 'self'; img-src 'self' data:"
Override: true
CustomHeadersConfig:
Items:
- Header: Permissions-Policy
Value: camera=(), microphone=(), geolocation=()
Override: true
SiteDistribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Enabled: true
DefaultRootObject: index.html
Origins:
- Id: s3-origin
DomainName: !GetAtt SiteBucket.RegionalDomainName
OriginAccessControlId: !GetAtt SiteOac.Id
S3OriginConfig:
OriginAccessIdentity: ''
DefaultCacheBehavior:
TargetOriginId: s3-origin
ViewerProtocolPolicy: redirect-to-https
AllowedMethods: [GET, HEAD, OPTIONS]
CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6
ResponseHeadersPolicyId: !Ref SiteHeadersPolicyThe only change to the behavior is the ResponseHeadersPolicyId line. Note that OPTIONS is in AllowedMethods. Without it, a CORS preflight request never reaches the policy logic.
Reading the security headers
- Strict-Transport-Security (HSTS) tells browsers to use HTTPS only for the given number of seconds. One year (31536000) is a common production value. Do not enable
Preloadunless you intend to submit the domain to the browser preload list, because removing a domain from that list is slow. - X-Content-Type-Options: nosniff stops browsers from guessing a file's type. This makes the
Content-Typeyou set at upload time matter, so check it. - X-Frame-Options controls whether other sites can embed your pages in a frame.
DENYblocks all framing.SAMEORIGINallows your own site. - Referrer-Policy limits how much of the URL is sent to other sites when a user follows a link.
- Content-Security-Policy (CSP) lists where scripts, images, and styles may load from. It is the most powerful header here and the easiest to get wrong. A policy that is too strict breaks inline scripts and third-party widgets.
CORS at the edge instead of at the bucket
You can configure CORS on the S3 bucket instead. For CloudFront to pass that through correctly, the cache policy has to include the Origin header in the cache key. Otherwise the first caller's CORS response is cached and served to everyone. Adding Origin to the cache key splits the cache by origin, which lowers the hit ratio.
A CORS section in a response headers policy avoids this. CloudFront decides on the CORS headers at response time, so Origin does not need to be in the cache key or forwarded to S3. The managed CachingOptimized policy used in this tutorial stays as it is.
Two rules keep this simple:
- Put CORS in one place, either the policy or the bucket, not both.
- If you use
*as the allowed origin, do not setAccessControlAllowCredentialsto true. Browsers reject that combination.
Verifying the result
Check headers with curl, sending an Origin header to trigger CORS:
curl -sI -H "Origin: https://app.example.com" \
https://d111111abcdef8.cloudfront.net/assets/app.jsLook for access-control-allow-origin: https://app.example.com and strict-transport-security. Then repeat with -H "Origin: https://other.example.net". The allow-origin header should be absent. To test preflight, add -X OPTIONS -H "Access-Control-Request-Method: GET".
Common errors
- Headers missing after a change. Distribution updates take a few minutes to propagate. Check the distribution status before you debug.
- Origin value wins unexpectedly. The
Overrideflag is false and S3 sent the header. Set it to true. - CORS works on a miss but fails on a hit. The bucket's CORS is in use and
Originis not in the cache key. Move CORS to the policy. - Preflight returns 403.
OPTIONSis not in the behavior's allowed methods, or the bucket's CORS is missing and the policy has no CORS section. - Page breaks after adding CSP. An inline script or an external domain is blocked. Use report-only mode first.
Policy or edge function?
A response headers policy handles static header values with no code to run or pay for. If a header value depends on the request path or the object, use a CloudFront Function or Lambda@Edge instead. For a static S3 site, a policy is almost always enough.
Exercise
Your single-page app at https://app.example.com fails to load fonts from your distribution with a CORS error. The bucket has no CORS configuration, and the cache policy does not include the Origin header. What is the least invasive fix, and why does it not hurt your cache hit ratio?
Show answer
Add a response headers policy with a CorsConfig that lists https://app.example.com in AccessControlAllowOrigins and GET and HEAD in AccessControlAllowMethods, then attach it to the cache behavior that serves the fonts. CloudFront adds the CORS headers when it sends the response, so the Origin header does not need to be in the cache key or forwarded to S3. All viewers share one cached copy of each font, and the hit ratio stays the same.
Exercise
You set X-Frame-Options to DENY with Override false, but a browser still shows SAMEORIGIN on one HTML file. What most likely happened, and how do you enforce DENY?
Show answer
The object was uploaded to S3 with its own X-Frame-Options metadata of SAMEORIGIN. With Override false, CloudFront keeps the origin's value when one exists. Set Override to true in the policy so CloudFront replaces the origin value. No invalidation is needed, because the header is applied at response time.