AWS CDK v2:使用 OAC 限制 Cloudfront 分发对 S3 中特定文件夹的访问

问题描述 投票:0回答:1

现在 AWS CDK 具有 L2 构造 OAC 支持,我尝试在我的项目中使用它,但是,由于它现在自动为我创建相关的 S3 存储桶策略规则,我正在努力修改它以限制访问仅某些目录。

使用以下代码:

const bucket = new Bucket(this, 'MyBucket', {
  bucketName: 'my-bucket',
  blockPublicAccess: BlockPublicAccess.BLOCK_ALL,
  removalPolicy: RemovalPolicy.DESTROY,
  autoDeleteObjects: true
});

const dist = new Distribution(this, 'Distribution', {
  defaultBehavior: {
    // Using new S3BucketOrigin construct with OAC functionality built in
    origin: S3BucketOrigin.withOriginAccessControl(bucket),
    viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS
  },
  domainNames: [domainName],
  certificate,
});

在存储桶上自动创建以下策略:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Deny",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::my-bucket",
                "arn:aws:s3:::my-bucket/*"
            ],
            "Condition": {
                "Bool": {
                    "aws:SecureTransport": "false"
                }
            }
        },
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::123456789012:role/the-autodelete-role"
            },
            "Action": [
                "s3:DeleteObject*",
                "s3:GetBucket*",
                "s3:List*",
                "s3:PutBucketPolicy"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket",
                "arn:aws:s3:::my-bucket/*"
            ]
        },
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "cloudfront.amazonaws.com"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::my-bucket/*",
            "Condition": {
                "StringEquals": {
                    "AWS:SourceArn": "arn:aws:cloudfront::123456789012:distribution/ABCDEFGHIJKLMN"
                }
            }
        }
    ]
}

我现在如何通过 CDK 修改此策略以仅允许访问某些目录?

谢谢你

typescript amazon-web-services amazon-s3 amazon-cloudfront aws-cdk
1个回答
0
投票

感谢 @luk2302 指导我找到源代码,以确认 S3BucketOrigin.withOriginAccessControl 不可能。

然后我意识到 S3 存储桶策略中的 Deny 语句始终会覆盖 Allow 语句,因此在我的例子中,当我需要限制对某些“目录”的访问时,我设法在之后向存储桶策略中添加了 Deny 语句:

bucket.addToResourcePolicy(new iam.PolicyStatement({
  effect: iam.Effect.DENY,
  principals: [new iam.ServicePrincipal('cloudfront.amazonaws.com')],
  actions: ['s3:GetObject'],
  notResources: [
    `${bucket.bucketArn}/assets/*`,
    `${bucket.bucketArn}/tmp/*`
  ],
  conditions: {
    StringEquals: {
      'AWS:SourceArn': `arn:aws:cloudfront::${this.account}:distribution/${dist.distributionId}`
    }
  }
}));

我希望这对某人有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.