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).

![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

## 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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

note: I rewrote the README based on s3-sqs-cdk, with more detailed steps👍

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(
self,
"My-Website-Bucket",
removal_policy=RemovalPolicy.DESTROY,
auto_delete_objects=True,
encryption=s3.BucketEncryption.KMS,
encryption=s3.BucketEncryption.S3_MANAGED,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

note: To keep the pattern cost-effective and easy to try out, I changed the bucket encryption from KMS to S3 managed encryption.

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),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

note: Migrated from OAI to OAC here, since S3Origin with OriginAccessIdentity is now deprecated.

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,
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=["/*"]
)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

note: Since I added index.html, this deploys it to the S3 bucket.


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()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

note: The original setup seemed to expect users to move the provided file into their own CDK project to run it, but this differs from the other patterns and I don't think it works as a standalone pattern. I improved the CDK implementation so that it can be deployed on its own😀

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