How to grant s3 access to cloudfront using the CDK?

0

I'm confused within the CDK how I can set up CloudFront only permissions on an S3 bucket. I crated the bucket, with publicReadAccess: false then am trying to grant cloudformation permissions like this:

import * as s3 from "aws-cdk-lib/aws-s3";
import * as cf from "aws-cdk-lib/aws-cloudfront";
import * as iam from "aws-cdk-lib/aws-iam";

export function grantCloudFrontAccessToBucket(stack: cdk.Stack, cfInstance: cf.CloudFrontWebDistribution, bucket: s3.Bucket) {
    const bucketObjects = `${bucket.bucketArn}:*`;
    const cfArn =`arn:aws:cloudfront::${stack.account}:distribution/${cfInstance.distributionId}`;

    const policy = new iam.PolicyStatement({
            actions: ["s3:GetObject"],
            resources: [bucketObjects],
            principals: [
                new iam.ServicePrincipal('cloudfront.amazonaws.com')
            ],
            conditions: [
                {
                    "StringEquals": {
                        "AWS:SourceArn": cfArn
                    }
                }
            ]
        });

    bucket.addToResourcePolicy(policy);
}

It complains that it is an invalid condition type, but I think StringEquals should be okay? The only other thing I can think of is I built the ARNs wrong?

Update: I found This Article that explains how to do what I was trying to do using OIN. But, the console help seems to suggest OAC is better. Can you use OAC in a similar way from the CDK?

profile picture
wz2b
asked a year ago3828 views
2 Answers
0
Accepted Answer

I'm closing this for now. I settled on just using the old way first until the CDK catches up.

const oin = new OriginAccessIdentity(stack, 'washnet-cf-origin-access-identity');
sourceBucket.grantRead(oin);

then in the cloudfront config:

s3OriginSource: {
    s3BucketSource: source,
    originAccessIdentity: oin
},

Good enough for now.

profile picture
wz2b
answered a year ago
0

The policy statement syntax is wrong: conditions is not a list. Annoyingly IDEs do not catch this error. Try:

conditions: { StringEquals: { "AWS:SourceArn": `arn:aws:cloudfront::${this.account}:distribution/${distribution.distributionId}` } }
MarkusR
answered 4 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions