Sub topic 5
Keeping the bucket private with Origin Access Control
This chapter assumes you can read an S3 bucket policy, know that CloudFront serves content from a distribution, and can run AWS CLI commands. It covers how Origin Access Control (OAC) lets CloudFront read a private bucket, how to set it up, and the errors you are most likely to hit. The bucket policy that completes the setup is covered in the next chapter, so it appears here only in outline.
Why the bucket should stay private
If an S3 bucket is public, anyone can fetch objects from https://bucket.s3.amazonaws.com/key and skip CloudFront. That bypass has three costs:
- Your cache rules, response headers, and signed URL checks do not apply to those requests.
- You pay S3 request and data transfer prices instead of CloudFront prices.
- Any object you upload by mistake becomes world-readable.
The fix is to leave S3 Block Public Access enabled and give CloudFront its own identity to read the bucket. OAC is the mechanism for that.
What OAC is
Origin Access Control is a CloudFront resource that you attach to an S3 origin in a distribution. When CloudFront fetches an object from that origin, it signs the request with AWS Signature Version 4 (SigV4). S3 sees an authenticated request from the CloudFront service principal, cloudfront.amazonaws.com. The bucket policy then decides whether that request is allowed.
OAC replaces Origin Access Identity (OAI), the older mechanism. OAI used a special CloudFront user and a legacy signing method. For new work, use OAC. It supports:
- All S3 Regions, including opt-in Regions.
- Server-side encryption with AWS KMS (SSE-KMS).
- Dynamic requests such as
PUTandDELETEthrough CloudFront. - Short-lived credentials with IAM-style policy conditions.
You can migrate an existing distribution from OAI to OAC. Add the OAC permission to the bucket policy first, then switch the origin, then remove the OAI statement.
The request flow
The diagram shows what happens on a cache miss. On a cache hit, CloudFront answers from the edge location and never contacts S3.
Creating an OAC
An OAC has four settings:
| Setting | Typical value | Meaning |
|---|---|---|
| `Name` | `site-oac` | A label for the OAC. It must be unique in your account. |
| `OriginAccessControlOriginType` | `s3` | The kind of origin this OAC signs for. |
| `SigningProtocol` | `sigv4` | The only supported protocol. |
| `SigningBehavior` | `always` | Whether CloudFront signs origin requests. |
The three signing behaviors differ in how they treat an Authorization header sent by the viewer:
alwayssigns every origin request and replaces anyAuthorizationheader from the viewer. Use this for S3 origins.no-overridesigns only when the viewer did not send anAuthorizationheader. Use it only when you deliberately let clients bring their own credentials.neverturns signing off. A bucket that needs signed requests will return 403.
Create one from the CLI:
aws cloudfront create-origin-access-control \
--origin-access-control-config \
"Name=site-oac,Description=OAC for the site bucket,SigningProtocol=sigv4,SigningBehavior=always,OriginAccessControlOriginType=s3"The response contains an Id. You pass that ID to the distribution's origin.
Attaching the OAC to an origin
In CloudFormation, define the OAC and reference it from the origin. This is the same excerpt used throughout the tutorial. It assumes a bucket resource named SiteBucket is defined elsewhere in the template.
Resources:
SiteOac:
Type: AWS::CloudFront::OriginAccessControl
Properties:
OriginAccessControlConfig:
Name: site-oac
OriginAccessControlOriginType: s3
SigningBehavior: always
SigningProtocol: sigv4
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
CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6Three details matter here:
DomainNameuses the bucket's regional domain name, such asamzn-s3-demo-bucket.s3.us-east-1.amazonaws.com. That is the S3 REST endpoint. OAC only works with this endpoint.OriginAccessIdentity: ''stays empty. CloudFormation requires theS3OriginConfigblock for S3 origins. An empty identity tells CloudFront you are not using OAI, soOriginAccessControlIdtakes effect.CachePolicyIdis the managed CachingOptimized policy. Cache policies are covered in a later chapter.
Why the website endpoint does not work
An S3 static website endpoint (bucket.s3-website-us-east-1.amazonaws.com) is a separate HTTP-only service. It does not accept SigV4-signed requests, so OAC cannot authenticate to it. CloudFront treats a website endpoint as a custom origin. To use one, the bucket must be public or protected by a custom header or referer check, which defeats the goal of a private bucket.
Using the REST endpoint costs you some website features:
- S3 will not rewrite
/docs/to/docs/index.htmlfor you. CloudFront's default root object covers only the root path. - S3 will not apply website redirect rules.
- Error pages come from CloudFront custom error responses, not from the bucket's website configuration.
The chapter on default root objects and custom error pages shows how to cover these gaps. If you need subdirectory index files, a CloudFront Function that rewrites URIs is the usual answer.
Granting access in the bucket policy
Creating an OAC does not give CloudFront any permission. The bucket policy must allow the service principal, and it must be limited to your distribution with an AWS:SourceArn condition. The next chapter walks through this policy line by line. The shape is:
{
"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"
}
}
}
]
}The SourceArn condition is what prevents the confused deputy problem. Without it, a distribution in any other AWS account could point at your bucket and CloudFront would sign the requests. The condition ties the grant to one distribution in your account.
SSE-KMS buckets
If objects are encrypted with a customer managed KMS key, the bucket policy alone is not enough. CloudFront must also be allowed to use the key. Add a statement like this to the KMS key policy:
{
"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/EDFDVBD6EXAMPLE"
}
}
}Objects encrypted with the default SSE-S3 keys, or with the AWS managed aws/s3 key, need no extra step for SSE-S3. The AWS managed aws/s3 key cannot be used with OAC because you cannot edit its key policy.
Verifying the setup
Test both paths. The direct S3 URL should fail and the CloudFront URL should succeed:
curl -I https://amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com/index.html
curl -I https://d111111abcdef8.cloudfront.net/index.htmlThe first request should return 403 Forbidden. The second should return 200 OK, with an X-Cache header that reads Miss from cloudfront on the first request and Hit from cloudfront on a repeat.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| 403 on every object through CloudFront | The bucket policy is missing, or its `SourceArn` names a different distribution | Check the distribution ID and account ID in the policy |
| 403 on every object, and the origin domain ends in `s3-website` | The origin is a website endpoint | Switch to the bucket's regional REST domain name |
| 403 for files that do not exist, where you expected 404 | The policy grants `s3:GetObject` but not `s3:ListBucket`, so S3 hides whether a key exists | Add `s3:ListBucket` on the bucket ARN if you want real 404s, or map 403 to your error page |
| 403 only for some objects in a KMS bucket | The key policy does not trust CloudFront | Add the KMS statement shown above |
| 403 after you edited the policy, and the distribution status is `In Progress` | The distribution change has not finished deploying | Wait for the status to reach `Deployed` |
| `PUT` through CloudFront fails | The policy lacks `s3:PutObject`, or the cache behavior does not allow the method | Add the action and allow `PUT` in the behavior's allowed methods |
Granting s3:ListBucket makes missing keys return 404. That tells anyone who can reach the distribution whether a key exists, so decide whether you want that.
Exercise
A distribution uses an OAC with signing behavior always. Requests through CloudFront return 403. The origin domain name is amzn-s3-demo-bucket.s3-website-us-east-1.amazonaws.com, and the bucket policy correctly names the distribution ARN. What is wrong, and what do you change?
Show answer
The origin points to the S3 website endpoint, which cannot accept SigV4-signed requests, so OAC cannot authenticate to it. Change the origin's domain name to the bucket's regional REST endpoint, amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com, keep the OAC attached, and wait for the distribution to redeploy. If you relied on website features such as index documents in subdirectories, replace them with a default root object, custom error responses, or a CloudFront Function.
Exercise
Why must the bucket policy include the AWS:SourceArn condition when the principal is cloudfront.amazonaws.com?
Show answer
The principal cloudfront.amazonaws.com represents the CloudFront service for every AWS account. Without the condition, a distribution in any account could use CloudFront to read your bucket. The AWS:SourceArn condition limits the grant to the one distribution you name.