Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions s3-cloudfront-oac-cdk-python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# S3 Hosted Website Served by a CloudFront Distribution restricted by CloudFront Origin Access Control (OAC)

This repo contains serverless patterns showing how to setup a S3 website hosting bucket that is served by a CloudFront distribution that also obfuscates the CloudFront Distribution domain via CloudFront Origin Access Control (OAC).
Comment on lines +1 to +3

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# S3 Hosted Website Served by a CloudFront Distribution restricted by CloudFront Origin Access Control (OAC)
This repo contains serverless patterns showing how to setup a S3 website hosting bucket that is served by a CloudFront distribution that also obfuscates the CloudFront Distribution domain via CloudFront Origin Access Control (OAC).
# Amazon S3 static website served by an Amazon CloudFront distribution restricted with Origin Access Control (OAC)
This repo contains a serverless pattern showing how to set up an Amazon S3 website hosting bucketthat is served by a CloudFront distribution that also obfuscates the CloudFront Distribution domain via CloudFront Origin Access Control (OAC).


![Demo Project Solution Architecture Diagram](diagram.PNG)

- Learn more about these patterns at https://serverlessland.com/patterns.
- To learn more about submitting a pattern, read the [publishing guidelines page](https://github.com/aws-samples/serverless-patterns/blob/main/PUBLISHING.md).

Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.

## Requirements

* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* [AWS Cloud Development Kit](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html) (AWS CDK) Installed and account bootstrapped

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* [AWS Cloud Development Kit](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html) (AWS CDK) Installed and account bootstrapped
* [Python 3](https://www.python.org/downloads/) (3.9 or later) installed
* [AWS Cloud Development Kit](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html) (AWS CDK) Installed and account bootstrapped


## Deployment Instructions

1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
```bash
git clone https://github.com/aws-samples/serverless-patterns
```
2. Change directory to the pattern directory:
```bash
cd s3-cloudfront-oac-cdk-python
```
3. Create a virtual environment for python:
```bash
python3 -m venv .venv
```
4. Activate the virtual environment:
```bash
source .venv/bin/activate
```
5. Install python modules:
```bash
python3 -m pip install -r requirements.txt
```
6. From the command line, use CDK to synthesize the CloudFormation template and check for errors:
```bash
cdk synth
```
7. From the command line, use CDK to deploy the stack:
```bash
cdk deploy
```

## How it works

This CDK app creates a private S3 bucket, uploads a sample `index.html` to it, and creates a CloudFront distribution in front of the bucket. CloudFront reads the bucket content through Origin Access Control (OAC), so the bucket stays private and is only accessible via CloudFront.

## Testing

1. Note the `DistributionId` and `DistributionDomainName` values from the outputs of the CDK deployment process.
2. Open `https://<DistributionDomainName>` in your browser. You should see the sample `index.html` page saying `Hello from S3 + CloudFront!`.
3. Confirm that the distribution accesses the S3 origin via Origin Access Control (OAC).
```bash
aws cloudfront get-distribution-config --id <DistributionId> --query 'DistributionConfig.Origins.Items[0].OriginAccessControlId'
```

## Cleanup

1. Delete the stack
```bash
cdk destroy
```
1. Confirm the stack has been deleted
```bash
aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'S3CloudFrontOACStack')].StackStatus"
```

----
Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0
Comment thread
marcojahn marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
import aws_cdk as cdk
from constructs import Construct
from aws_cdk import (
CfnOutput,
RemovalPolicy,
aws_s3 as s3,
aws_s3_deployment as s3deploy,
aws_cloudfront as cloudfront,
aws_cloudfront_origins as origins
)

class S3CloudFrontOAI(Construct):

def __init__(self, scope: Construct, id: str, **kwargs):
super().__init__(scope, id, **kwargs)
class S3CloudFrontOAC(Construct):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

website_bucket = s3.Bucket(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add

block_public_access=s3.BlockPublicAccess.BLOCK_ALL

The bucket does not explicitly set block_public_access. The pattern relies on CDK's secure default. While functionally correct, explicit configuration makes the private-bucket intent unambiguous for readers and guards against future changes.

self,
"My-Website-Bucket",
removal_policy=RemovalPolicy.DESTROY,
auto_delete_objects=True,
encryption=s3.BucketEncryption.KMS,
encryption=s3.BucketEncryption.S3_MANAGED,
Comment thread
marcojahn marked this conversation as resolved.
enforce_ssl=True,
versioned=True
)
Expand All @@ -29,25 +30,31 @@ def __init__(self, scope: Construct, id: str, **kwargs):
exposed_headers=["Access-Control-Allow-Origin"]
)

oai = cloudfront.OriginAccessIdentity(
self,
"My-OAI",
comment="My OAI for the S3 Website"
)

website_bucket.grant_read(oai)


cd = cloudfront.Distribution(self, "myCloudFrontDistribution",
distribution = cloudfront.Distribution(self, "myCloudFrontDistribution",
default_root_object='index.html',
default_behavior=cloudfront.BehaviorOptions(
origin=origins.S3Origin(website_bucket, origin_access_identity=oai),
origin_request_policy=cloudfront.OriginRequestPolicy.CORS_S3_ORIGIN,
origin=origins.S3BucketOrigin.with_origin_access_control(website_bucket),
Comment thread
marcojahn marked this conversation as resolved.
origin_request_policy=cloudfront.OriginRequestPolicy.CORS_S3_ORIGIN,
viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
response_headers_policy=cloudfront.ResponseHeadersPolicy.CORS_ALLOW_ALL_ORIGINS,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is only a static served site CORS should not be required at all, can you please check if this is enough:

# 1. REMOVED: website_bucket.add_cors_rule(...)
# S3 CORS rules are not required for a standard static site served only through CloudFront.

# 2. Updated CloudFront Distribution
distribution = cloudfront.Distribution(self, "myCloudFrontDistribution",
    default_root_object='index.html',
    default_behavior=cloudfront.BehaviorOptions(
        origin=origins.S3BucketOrigin.with_origin_access_control(website_bucket),
        viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
        cache_policy=cloudfront.CachePolicy.CACHING_OPTIMIZED,
        allowed_methods=cloudfront.AllowedMethods.ALLOW_ALL,
        
        # REMOVED: origin_request_policy=cloudfront.OriginRequestPolicy.CORS_S3_ORIGIN
        # REMOVED: response_headers_policy=cloudfront.ResponseHeadersPolicy.CORS_ALLOW_ALL_ORIGINS
        
        # OPTIONAL: It is highly recommended to add standard security headers here instead
        response_headers_policy=cloudfront.ResponseHeadersPolicy.SECURITY_HEADERS_DEFAULT
    )
)

cache_policy=cloudfront.CachePolicy.CACHING_OPTIMIZED,
allowed_methods=cloudfront.AllowedMethods.ALLOW_ALL
)
)
)


s3deploy.BucketDeployment(
self,
"DeployWebsite",
sources=[s3deploy.Source.asset("./website")],
destination_bucket=website_bucket,
distribution=distribution,
distribution_paths=["/*"]
)
Comment thread
marcojahn marked this conversation as resolved.

CfnOutput(self, "DistributionId", value=distribution.distribution_id)
CfnOutput(self, "DistributionDomainName", value=distribution.distribution_domain_name)

app = cdk.App()
stack = cdk.Stack(app, "S3CloudFrontOACStack")
S3CloudFrontOAC(stack, "s3-hosted-website")
app.synth()
Comment thread
marcojahn marked this conversation as resolved.
3 changes: 3 additions & 0 deletions s3-cloudfront-oac-cdk-python/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"app": "python3 app.py"
}
Binary file added s3-cloudfront-oac-cdk-python/diagram.PNG
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading