Staging a Content-Security-Policy on CloudFront: a rollout workflow

A stage-by-stage workflow for turning on a Content-Security-Policy on CloudFront: observe with Report-Only, enforce for a slice of traffic on a staging distribution, then promote with a rollback path. Commands follow the AWS CLI reference; the workflow itself has not been run on AWS.

CloudFront's managed SecurityHeadersPolicy sets Referrer-Policy, Strict-Transport-Security, X-Content-Type-Options, X-Frame-Options and X-XSS-Protection. It has no Content-Security-Policy (CSP) and no Permissions-Policy. A CSP cannot be copied from a template: the right one depends on what your pages load, and a wrong one blocks your own scripts. So the header that limits injected scripts is the one many sites leave out.
This article describes a way to turn a CSP on in stages: observe with Report-Only, enforce for a slice of traffic on a CloudFront staging distribution, then promote. The commands follow the AWS CLI reference, and their argument shapes and JSON were checked offline against the AWS CLI's own parameter validation, with no request sent to AWS. The workflow itself has not been run on AWS, and nothing here guarantees your site will not break. What it does is make a mistake visible, and recoverable, before it reaches everyone.

Step 0: take an inventory first

Leaving the CSP field out of a response headers policy does not remove a CSP that something else sends. Before changing anything, find out what already sets security headers:
  • Run  curl -sI https://dXXXX.cloudfront.net/  and look for  content-security-policy  and  content-security-policy-report-only  in the response.
  • List every cache behavior (the default one and each entry under  CacheBehaviors ) with its current  ResponseHeadersPolicyId , and write the IDs down. A behavior may have no ResponseHeadersPolicyId at all; record that as "none", because restoring it means removing the field, not setting an empty or different ID. The first command below prints them, and the second saves the whole original configuration as your exact rollback reference.
  • Check whether the origin, a CloudFront Function or a Lambda@Edge function attached to a behavior adds headers.
aws cloudfront get-distribution-config --id PRIMARY | jq -r '.DistributionConfig
| [.DefaultCacheBehavior.ResponseHeadersPolicyId]
+ [(.CacheBehaviors.Items // [])[].ResponseHeadersPolicyId] | @tsv'

aws cloudfront get-distribution-config --id PRIMARY > original-primary.json
If a CSP already comes from somewhere else, you are changing a policy that exists, not adding one. Sort that out first. The gate below can detect a surprise after the change, but it should not be the first time you hear about it.

One rule keeps staging safe: one policy resource per stage

A staging distribution starts as a copy of the primary, so both point at the same response headers policy ID. AWS lists the response headers policy among the resources you can update while staging is active, and UpdateResponseHeadersPolicy replaces the entire policy. Editing the policy the primary uses is therefore an edit to production, whatever distribution you were looking at.
So never edit a policy that production uses. Create a new policy for each stage and change which ID a cache behavior points at. The old policy stays untouched, and rollback means restoring each behavior to what it had in Step 0, which may be an ID or no policy at all.

How to change a distribution without clobbering it

 update-distribution  replaces the whole configuration; values you leave out are not merged from the existing one. So always start from a fresh copy, edit only what you mean to, and keep everything else. The example below changes only the default cache behavior and leaves every other behavior as it is. That is the safer starting point. If you want the same policy on every behavior, use the variant filter shown after the example instead, and know that it overwrites each behavior's existing policy, including ones that had none.
aws cloudfront get-distribution-config --id DIST > dc.json
ETAG=$(jq -r .ETag dc.json)
jq --arg id POLICY_ID '.DistributionConfig
| .DefaultCacheBehavior.ResponseHeadersPolicyId = $id' dc.json > config.json
aws cloudfront update-distribution --id DIST --if-match "$ETAG" \
--distribution-config file://config.json
aws cloudfront wait distribution-deployed --id DIST
The ETag identifies the version you fetched, and the CLI reference says to copy it from that response for  --if-match . Fetch the config again right before each edit and use that fresh ETag, so you never overwrite a change you have not seen. Variant that sets the policy on every behavior: replace the  jq  filter with  .DistributionConfig | .DefaultCacheBehavior.ResponseHeadersPolicyId = $id | if .CacheBehaviors.Quantity > 0 then .CacheBehaviors.Items |= map(.ResponseHeadersPolicyId = $id) else . end . To target one extra path pattern, change only that item. Wait for the deployed state before you test or move on:  wait  polls every 60 seconds and gives up after 35 failed checks.
Create each policy with the command below and note the returned  Id . Start each policy from the kit's  policies/security-headers-full.json , with a new  Name .
aws cloudfront create-response-headers-policy \
--response-headers-policy-config file://policy.json

Stage 1: observe with Report-Only

CloudFront's dedicated CSP field always sends the enforcing header. So the stage 1 policy deletes  SecurityHeadersConfig.ContentSecurityPolicy  from the kit file, and its  CustomHeadersConfig  becomes:
"CustomHeadersConfig": {
"Quantity": 3,
"Items": [
{"Header": "Permissions-Policy",
"Value": "camera=(), microphone=(), geolocation=()",
"Override": true},
{"Header": "Reporting-Endpoints",
"Value": "csp-endpoint=\"https://csp.example.com/reports\"",
"Override": true},
{"Header": "Content-Security-Policy-Report-Only",
"Value": "default-src 'self'; report-to csp-endpoint; report-uri https://csp.example.com/reports",
"Override": true}
]
}
Point the primary at this policy with the procedure above. The collector URL is a placeholder: you must run an endpoint that accepts reports, over HTTPS (MDN says non-secure endpoints in  Reporting-Endpoints  are ignored). The kit does not provide one.
MDN says a Report-Only policy needs  report-to , or the older  report-uri , to send reports at all.  report-to  is the current directive, but MDN notes it does not yet have full cross-browser support and recommends declaring both until it does, which is what the example does. Coverage still depends on your visitors' browsers, so a quiet collector is not proof that nothing would break.
Both custom headers are untested on CloudFront. The AWS pages I read list no restriction on adding them, but only  create-response-headers-policy  can tell you if the service accepts them. If it rejects either, this stage cannot be done this way.
Run the gate below, then loosen the policy for each legitimate source the reports show. Make every change a new policy and point the behavior at it.

Stage 2: enforce for a slice, on a staging distribution

  1. Create the staging distribution. The output holds the staging  Distribution.Id  and  Distribution.DomainName .
aws cloudfront copy-distribution --primary-distribution-id PRIMARY --staging \
--if-match PRIMARY_ETAG --caller-reference NAME
  1. Create a policy for enforcement: the kit file with a new  Name , the CSP field set to the same value you tested in Report-Only ( default-src 'self'; report-to csp-endpoint; report-uri https://csp.example.com/reports , adjusted by what the reports showed), and a  CustomHeadersConfig  that keeps  Permissions-Policy  and  Reporting-Endpoints  (Quantity 2). Keeping the reporting config in the enforcing policy is what lets you see blocked loads from the slice. The dedicated CSP field is limited to 1,783 characters.
  1. Create the continuous deployment policy. For header routing,  cdp.json  is:
{"StagingDistributionDnsNames": {"Quantity": 1, "Items": ["STAGING_DOMAIN"]},
"Enabled": true,
"TrafficConfig": {"Type": "SingleHeader",
"SingleHeaderConfig": {"Header": "aws-cf-cd-csp", "Value": "staging"}}}
aws cloudfront create-continuous-deployment-policy \
--continuous-deployment-policy-config file://cdp.json
For weight routing use  "Type": "SingleWeight"  with  "SingleWeightConfig": {"Weight": 0.05} , at most 0.15. The header name must start with  aws-cf-cd- .
  1. Attach it to the primary with the update procedure above, setting  .DistributionConfig.ContinuousDeploymentPolicyId  to the policy's  Id . Wait for the primary to deploy.
  1. Update the staging distribution the same way, fetching its own config and ETag, setting the same behavior or behaviors you changed in Stage 1 to the enforcing policy ID. Wait for it to deploy.
  1. If the primary uses origin access control for an S3 bucket, add the staging distribution to the bucket policy. The kit's  deploy.py  scopes the bucket policy to one distribution ARN, so this step is needed. Continuous deployment also cannot be used with a distribution that supports HTTP/3, so check  HttpVersion  in the config.
Check routing with the exact header name and value you put in the policy:
curl -sI -H 'aws-cf-cd-csp: staging' https://PRIMARY_DOMAIN/
That response should show  content-security-policy , and the same request without  -H  should not. Use your own name and value if you changed them.
The primary and staging distributions do not have a shared cache. CloudFront may send all traffic to the primary during peak periods, so a quiet slice is not proof by itself. Treat the stage as ready only when both hold: reports from the slice stay quiet over a real traffic period, and you have used the staged site in a browser, with the routing header added by an extension, through its main pages, forms, embeds, fonts and analytics, with developer tools open for blocked resources. With weight routing you cannot choose who is in the slice, so do the browser pass at a low weight and read the reports.

Stage 3: promote, then verify, with a way back

Fetch both ETags immediately before promoting ( get-distribution-config  on each), then:
aws cloudfront update-distribution-with-staging-config --id PRIMARY \
--staging-distribution-id STAGING --if-match 'PRIMARY_ETAG,STAGING_ETAG'
CloudFront copies the staging configuration, including its policy ID, to the primary and disables the continuous deployment policy. That is the step that enforces the CSP for everyone; staging edits do not change the primary's own configuration until then. Wait for the primary to deploy and run the gate.
Headers do not need a cache invalidation: CloudFront applies a response headers policy to responses served from cache as well as from the origin. To roll back, restore each behavior to what  original-primary.json  recorded: its old ID, or no  ResponseHeadersPolicyId  field if it had none. Fetch a fresh config into  fresh.json  with  get-distribution-config  and note its ETag, then rebuild the config with this filter, which restores by path pattern and removes the field where the original had none, and pass the result to  update-distribution  as above. The old policy resources are unchanged.
jq --slurpfile o original-primary.json '$o[0].DistributionConfig as $orig
| .DistributionConfig
| .DefaultCacheBehavior |= (if $orig.DefaultCacheBehavior.ResponseHeadersPolicyId
then .ResponseHeadersPolicyId = $orig.DefaultCacheBehavior.ResponseHeadersPolicyId
else del(.ResponseHeadersPolicyId) end)
| if .CacheBehaviors.Quantity > 0
then .CacheBehaviors.Items |= map(. as $b
| ([$orig.CacheBehaviors.Items[]? | select(.PathPattern == $b.PathPattern)] | first) as $ob
| if $ob.ResponseHeadersPolicyId
then .ResponseHeadersPolicyId = $ob.ResponseHeadersPolicyId
else del(.ResponseHeadersPolicyId) end)
else . end' fresh.json > config.json
Run this on a sample first: on a sample config with one behavior that had a policy and one that had none, it reproduced the original configuration exactly. It matches behaviors by  PathPattern , so it assumes you did not add or rename path patterns in between.

The gate

The kit's  verify.py  audits the live response and prints JSON. It always exits 0, including on a low score or an unreachable site, so alone it cannot stop a pipeline. Save this as  gate.py  in the kit's root directory, the one containing  scripts/ ; it finds  scripts/verify.py  relative to its own location, so you can run it from any directory:
python3 gate.py https://dXXXX.cloudfront.net report-only
python3 gate.py https://dXXXX.cloudfront.net enforced
It matches the check names  verify.py  reports ( CSP  is the one it relies on) and fails on a crash, bad output, an unreachable site, unexpected failing checks, or the wrong CSP header for the stage:
#!/usr/bin/env python3
import json, os, subprocess, sys, urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
url, stage = sys.argv[1], sys.argv[2] # stage: report-only | enforced
if stage not in ("report-only", "enforced"):
sys.exit("stage must be report-only or enforced")
p = subprocess.run([sys.executable, os.path.join(HERE, "scripts", "verify.py"), url],
capture_output=True, text=True, timeout=120)
if p.returncode != 0:
sys.exit("verify.py crashed: " + p.stderr[-300:])
try:
r = json.loads(p.stdout)
except ValueError:
sys.exit("verify.py output is not JSON")
if "error" in r or not r.get("checks"):
sys.exit("audit did not run: " + str(r.get("error", "no checks")))
failing = sorted(c["check"] for c in r["checks"]
if c["pass"] is False and not c.get("info"))
expected = ["CSP"] if stage == "report-only" else []
if failing != expected:
sys.exit("stage %s: expected failing %s, got %s" % (stage, expected, failing))
h = {k.lower(): v for k, v in urllib.request.urlopen(url, timeout=20).headers.items()}
if stage == "report-only" and ("content-security-policy" in h
or "content-security-policy-report-only" not in h):
sys.exit("report-only: Report-Only header missing or enforcing CSP present")
print("gate passed for stage", stage, "- score", r["score"])
This is a presence check: it confirms the headers are there and that the CSP is in the right mode. It does not test that your pages work under the policy, and it cannot test the staging slice, because  verify.py  sends no custom request headers. The report-only stage expects exactly one failing check, CSP, because  verify.py  does not count a Report-Only header as CSP. The browser pass in Stage 2 is the functional test.

What is tested and what is not

  • Tested locally: the kit's offline tests, and  gate.py  against local fixtures: Report-Only only (passes  report-only , fails  enforced ), an enforcing CSP (the reverse), no CSP, and an unreachable URL (fails closed).
  • The  jq  filters, including the rollback, were run on sample configurations, one of them with a behavior that had no policy. Checked offline against the AWS CLI's parameter validation, with the endpoint pointed at an unused local port so nothing reached AWS: both policy JSON files, both continuous deployment policy files, and the  copy-distribution ,  update-distribution  and  update-distribution-with-staging-config  argument shapes. This shows the shapes are valid, not that CloudFront accepts them or that the workflow works.
  • Observed earlier on one demo distribution that has since been torn down: the stock S3 + CloudFront setup sent none of the six audited security headers, and the kit's full policy took the audit from 5/11 to 11/11. That is a single distribution, not a statistic.
  • Not tested: every step against AWS. The kit's  deploy.py  and  teardown.py  also have no end-to-end run of their own.

Cleanup

Delete what you created for the trial once you finish, and check the AWS console to confirm. I did not check current prices; look at the AWS pricing pages for what applies to you.
  • Things that can cost money while they exist or are used: traffic through CloudFront, objects and requests in S3, a log bucket if you enabled logging, and whatever hosts your report collector.
  • Configuration resources that are left behind: the staging distribution, the continuous deployment policy, and the extra response headers policies. These are not traffic, but they stay in your account until deleted. I did not verify AWS's delete procedure for staging distributions or continuous deployment policies, so check the documentation before removing them.
 teardown.py  removes only what  deploy.py  recorded in  .kit-state.json : its bucket, origin access control, distribution and one headers policy, each after re-checking a tag or name prefix. It knows nothing about the staging resources, the extra policies or the collector. The scripts have not had an end-to-end run, so confirm the result instead of assuming it worked.

Where this stops

A passing audit is a floor. It does not replace fixing the injection bugs a CSP is meant to contain, and it says nothing about IAM, bucket permissions or dependencies. The kit is at  cloudfront-security-headers-kit : the policy templates,  deploy.py ,  verify.py ,  teardown.py  and tests.

References

Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article