Skip to content

Commit

Permalink
Merge pull request pulumi#1066 from lita/use-origin-access-identity
Browse files Browse the repository at this point in the history
Use Origin Access Identity and lock down S3 permissions on the AWS static website example
  • Loading branch information
jkodroff committed Jan 4, 2022
2 parents 6f56084 + babfc1f commit 464fd6e
Showing 1 changed file with 25 additions and 9 deletions.
34 changes: 25 additions & 9 deletions aws-ts-static-website/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ const config = {
const contentBucket = new aws.s3.Bucket("contentBucket",
{
bucket: config.targetDomain,
acl: "public-read",
// Configure S3 to serve bucket contents as a website. This way S3 will automatically convert
// requests for "foo/" to "foo/index.html".
website: {
Expand Down Expand Up @@ -154,6 +153,11 @@ if (config.certificateArn === undefined) {
certificateArn = certificateValidation.certificateArn;
}

// Generate Origin Access Identity to access the private s3 bucket.
const originAccessIdentity = new aws.cloudfront.OriginAccessIdentity("originAccessIdentity", {
comment: "this is needed to setup s3 polices and make s3 not public."
});

// if config.includeWWW include an alias for the www subdomain
const distributionAliases = config.includeWWW ? [config.targetDomain, `www.${config.targetDomain}`] : [config.targetDomain];

Expand All @@ -171,14 +175,9 @@ const distributionArgs: aws.cloudfront.DistributionArgs = {
{
originId: contentBucket.arn,
domainName: contentBucket.websiteEndpoint,
customOriginConfig: {
// Amazon S3 doesn't support HTTPS connections when using an S3 bucket configured as a website endpoint.
// https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesOriginProtocolPolicy
originProtocolPolicy: "http-only",
httpPort: 80,
httpsPort: 443,
originSslProtocols: ["TLSv1.2"],
},
s3OriginConfig: {
originAccessIdentity: originAccessIdentity.cloudfrontAccessIdentityPath
},
},
],

Expand Down Expand Up @@ -296,6 +295,23 @@ function createWWWAliasRecord(targetDomain: string, distribution: aws.cloudfront
);
}

const bucketPolicy = new aws.s3.BucketPolicy("bucketPolicy", {
bucket: siteBucket.id, // refer to the bucket created earlier
policy: pulumi.all([originAccessIdentity.iamArn, contentBucket.arn]).apply(([oaiArn, bucketArn]) =>JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Principal: {
AWS: oaiArn
}, // Only allow Cloudfront read access.
Action: ["s3:GetObject"],
Resource: [`${bucketArn}/*`], // Give Cloudfront access to the entire bucket.
},
],
}))
});

const aRecord = createAliasRecord(config.targetDomain, cdn);
if (config.includeWWW) {
const cnameRecord = createWWWAliasRecord(config.targetDomain, cdn);
Expand Down

0 comments on commit 464fd6e

Please sign in to comment.