Sub topic 6
Writing the bucket policy that trusts your distribution
This chapter covers the bucket policy that lets one CloudFront distribution read from a private S3 bucket. It assumes you know S3 buckets, objects, and keys, can read IAM JSON policies, and have run AWS CLI commands. It also assumes you have created an Origin Access Control (OAC) and attached it to a distribution, as covered in the previous chapter.
Why the policy is needed
An OAC makes CloudFront sign each request it sends to S3 with Signature Version 4 (SigV4). The signature proves who is asking. It does not grant permission. S3 still evaluates the bucket policy, and with Block Public Access on, no policy statement means no read access.
So the bucket needs one statement that says: the CloudFront service may call s3:GetObject, but only on behalf of this specific distribution.
The policy, line by line
Here is the policy for a bucket named amzn-s3-demo-bucket and a distribution in account 111122223333.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowCloudFrontServicePrincipalReadOnly",
"Effect": "Allow",
"Principal": {
"Service": "cloudfront.amazonaws.com"
},
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*",
"Condition": {
"StringEquals": {
"AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/EDFDVBD6EXAMPLE"
}
}
}
]
}Each element does a specific job:
- Version:
2012-10-17is the current policy language version. Keep it. Older versions lack features such as policy variables. - Sid: a label for humans. It must be unique within the policy.
- Effect:
Allowgrants access. Everything not allowed stays denied by default. - Principal:
cloudfront.amazonaws.comis a service principal. OAC uses this, so the policy names the service, not an identity that CloudFront owns in your account. - Action:
s3:GetObjectallows reading objects only. It does not allow listing, writing, or deleting. - Resource: the
/*suffix matters.GetObjectapplies to objects, so the ARN must name objects. The bucket ARN without/*would match nothing for this action. - Condition:
AWS:SourceArnpins the permission to one distribution.
Why the condition is not optional
The principal cloudfront.amazonaws.com is shared by every CloudFront distribution in every AWS account. Without the condition, anyone could create their own distribution, point its origin at your bucket, and read your objects. This is a confused deputy problem: a trusted service is tricked into acting for the wrong party.
AWS:SourceArn closes the gap, because CloudFront sets it to the ARN of the distribution that made the request. Only that distribution matches.
Two details about the ARN:
- CloudFront is a global service, so the ARN has no Region. The segment between
cloudfront:and the account ID is empty, which is why you seecloudfront::111122223333. - The ARN contains the distribution ID, not its domain name. Copy the ID from the console or from
aws cloudfront list-distributions.
Applying the policy
Save the JSON as policy.json, replace the bucket name, account ID, and distribution ID, then apply it:
aws s3api put-bucket-policy --bucket amzn-s3-demo-bucket --policy file://policy.jsonCheck what S3 stored:
aws s3api get-bucket-policy --bucket amzn-s3-demo-bucket --query Policy --output textput-bucket-policy replaces the entire policy. If the bucket already has statements, such as a deny rule for non-TLS traffic, fetch the existing policy first and merge your statement into it. Otherwise the existing rules are lost.
Doing it in CloudFormation
The policy can be created from the same template as the distribution. Because the distribution ID is only known after creation, build the ARN with !Sub and the distribution's Ref.
SiteBucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref SiteBucket
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: AllowCloudFrontServicePrincipalReadOnly
Effect: Allow
Principal:
Service: cloudfront.amazonaws.com
Action: s3:GetObject
Resource: !Sub "${SiteBucket.Arn}/*"
Condition:
StringEquals:
AWS:SourceArn: !Sub "arn:aws:cloudfront::${AWS::AccountId}:distribution/${SiteDistribution}"This references the distribution from the bucket policy, and the distribution references the bucket's domain name. That is not a cycle, because the distribution depends on the bucket and the policy depends on both.
What the policy does not cover
The statement grants read access only to objects that exist. Two cases surprise people.
Missing objects return 403, not 404
S3 reports a missing key as 404 only if the caller has s3:ListBucket on the bucket. With only GetObject, S3 returns 403 for a key that does not exist. Viewers will see 403 for typos and deleted files.
You have two options. You can handle it in CloudFront with a custom error response that maps 403 to your error page, which the root object and errors chapter covers. Or you can add a second statement that grants s3:ListBucket on the bucket ARN, with the same AWS:SourceArn condition, so S3 returns real 404s. The second choice lets the distribution list your keys if someone can send it a list request, so use it only if you need accurate status codes.
Objects encrypted with a KMS key
If the bucket uses SSE-S3 (the default), no extra permission is needed. If objects use SSE-KMS with a customer managed key, the key policy must also allow the CloudFront service principal to use kms:Decrypt and kms:GenerateDataKey, again conditioned on the distribution ARN. A bucket policy alone gives AccessDenied on these objects.
Objects owned by another account
A bucket policy applies to objects the bucket owner owns. If another account uploaded objects without giving up ownership, the policy may not apply to them. Set Object Ownership to "Bucket owner enforced" so ACLs are disabled and every object belongs to the bucket owner.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| 403 Access Denied for every file | Wrong distribution ID in `AWS:SourceArn`, or no policy applied | Compare the ARN with `aws cloudfront list-distributions` output |
| 403 only for some files | Objects use SSE-KMS or belong to another account | Update the key policy, or enforce bucket owner ownership |
| 403 for missing files, expected 404 | No `s3:ListBucket` permission | Add a custom error response or the list statement |
| Policy rejected: "Invalid principal" | Principal written as `"AWS": "cloudfront.amazonaws.com"` | Use `"Service": "cloudfront.amazonaws.com"` |
| Policy rejected by Block Public Access | Principal is `"*"` without a strong condition | Use the service principal with `AWS:SourceArn` |
| Works through S3 URL, fails through CloudFront | Distribution still uses the website endpoint or has no OAC attached | Use the REST endpoint and attach the OAC |
| Access worked before, fails after recreating the distribution | A new distribution has a new ID | Update the policy with the new ID |
The last row is common with infrastructure-as-code. Deleting and recreating a distribution changes its ID, so the policy must follow it. The CloudFormation example above handles this automatically.
Older setups: Origin Access Identity
Distributions created before OAC used an Origin Access Identity (OAI). Its policy looks different: the principal is arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E2EXAMPLE. If you migrate an OAI distribution to OAC, you can keep both principals in the policy during the switch, then remove the OAI statement after you confirm requests succeed. OAC is the current recommendation because it supports SSE-KMS, all Regions, and short-lived SigV4 credentials.
Testing the setup
Test both paths. The CloudFront path should succeed and the direct S3 path should fail.
curl -I https://d111111abcdef8.cloudfront.net/index.html
curl -I https://amzn-s3-demo-bucket.s3.amazonaws.com/index.htmlThe first request should return 200. The second should return 403. If the second returns 200, the bucket is still publicly readable, so check Block Public Access and object ACLs.
If the first request fails, run these checks in order:
- Confirm the distribution's origin domain is the bucket's regional REST domain, such as
amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com. - Confirm the OAC is attached to that origin in the distribution configuration.
- Confirm the account ID and distribution ID in
AWS:SourceArn. - Confirm the object key exists, since a missing key also returns 403.
Summary of the design
The trust chain has three links. The OAC makes CloudFront sign requests. The bucket policy allows the CloudFront service principal to read objects. The AWS:SourceArn condition limits that permission to your distribution. Remove any link and requests fail, which is the intended behavior.
Exercise
A teammate removes the Condition block from the bucket policy because "the principal is already CloudFront, so it is safe." What can now happen, and what single change restores the protection?
Show answer
Any CloudFront distribution in any AWS account can now use your bucket as an origin and read its objects, because cloudfront.amazonaws.com is shared by all distributions (a confused deputy problem). Restore the condition "StringEquals": {"AWS:SourceArn": "arn:aws:cloudfront::<account-id>:distribution/<distribution-id>"} so only your distribution matches.
Exercise
After you apply the correct policy, requests for existing files return 200, but requests for /missing.html return 403 instead of 404. Why, and name two ways to deal with it.
Show answer
The policy grants only s3:GetObject. Without s3:ListBucket, S3 hides whether a key exists and returns 403 for missing keys. Either add a CloudFront custom error response that maps 403 to your error page, or add an s3:ListBucket statement on the bucket ARN (without /*) with the same AWS:SourceArn condition.