aws-cdk icon indicating copy to clipboard operation
aws-cdk copied to clipboard

aws-cloudfront-origins/s3: allow passing in custom resources

Open SamVerschueren opened this issue 3 years ago • 0 comments

Describe the feature

Currently, when creating an S3 origin (for let's say CloudFront), it will always allow the origin access identity S3:GetObject permission on the entire bucket.

I think it would make sense to allow users to pass in custom resources.

Use Case

I'm setting up a CloudFront distribution with a default behaviour being a Lambda function, and an additional behaviour on path /-/* for S3. So all requests coming in starting with /- should go to S3.

However, I want to restrict the origin to read objects from other directories. Currently it has access to /* of the S3 bucket, while I want to restrict it to /-/*.

Proposed Solution

My idea would be to add an additional resources property to the S3OriginProps interface.

export interface S3OriginProps extends cloudfront.OriginProps {
  /**
   * An optional Origin Access Identity of the origin identity cloudfront will use when calling your s3 bucket.
   *
   * @default - An Origin Access Identity will be created.
   */
  readonly originAccessIdentity?: cloudfront.IOriginAccessIdentity;

  /**
   * An optional list of resources that should be added to the bucket policy.
   *
   * @default ['*']
   */
  readonly resources?: string[];
}

And in the S3BucketOrigin class at the bottom, replace the addToResourcePolicy call with

this.bucket.addToResourcePolicy(
  new iam.PolicyStatement({
    resources: this.resources || [this.bucket.arnForObjects('*')],
    actions: ['s3:GetObject'],
    principals: [this.originAccessIdentity.grantPrincipal],
  })
);

This allows me to pass in resources myself by doing

new S3Origin(myBucket, {
  originAccessIdentity: originAccess,
  resources: [myBucket.arnForObjects('-/*')],
});

Other Information

At first I manually did a bucket.grantRead(oid, '-/*). But then I ended up with 2 policy statements.

Acknowledgements

  • [X] I may be able to implement this feature request
  • [ ] This feature might incur a breaking change

CDK version used

2.32.0

Environment details (OS name and version, etc.)

macOS Montery

SamVerschueren avatar Jul 27 '22 11:07 SamVerschueren