Adding IAM policy to S3 using CDK giving errors

Viewed 1187

I am trying to create a S3 bucket using CDK. Bucket has created fine. However, when I trying to add the following IAM policy, I am getting create failed - API: s3:PutBucketPolicy Access Denied

TestBucket.addToResourcePolicy(new iam.PolicyStatement({
      actions: [ 's3:*'],
      effect: iam.Effect.DENY,
      principals: [ new iam.AnyPrincipal],
      resources:  [TestBucket.bucketArn+'/*'],
      conditions: {
        "Bool": {
          "aws:SecureTransport": "false"
        }
      },

The user I am running this code as has admin privs. What could be the issue ?

1 Answers

Sample CDK code to create an S3 Bucket and set resource policy to allow only HTTPS.

import * as cdk from "@aws-cdk/core";
import * as s3 from "@aws-cdk/aws-s3";
import * as iam from "@aws-cdk/aws-iam";

export class TestS3Stack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);
    this.simpleS3();
  }

  simpleS3() {
    const myBucket = new s3.Bucket(this, "my-bucket", {
      bucketName: "my-test-bucket-balu",
      blockPublicAccess: {
        blockPublicAcls: true,
        blockPublicPolicy: true,
        ignorePublicAcls: true,
        restrictPublicBuckets: true,
      },
    });
    myBucket.addToResourcePolicy(
      new iam.PolicyStatement({
        actions: ["s3:*"],
        effect: iam.Effect.DENY,
        principals: [new iam.AnyPrincipal()],
        resources: [myBucket.bucketArn, myBucket.bucketArn + "/*"],
        conditions: {
          Bool: {
            "aws:SecureTransport": "false",
          },
        },
      })
    );
  }
}

Unless there is a service control policy blocking admin user to PutBucketPolicy, we shouldn't get the error when creating a bucket policy which simply blocks http requests.

We can check if there are permission issues, by trying put bucket policy from cli

aws s3api put-bucket-policy --bucket my-test-bucket --policy '{"Version": "2012-10-17","Statement": [{"Effect": "Deny","Principal": "","Action": "s3:","Resource": "arn:aws:s3:::my-test-bucket/*","Condition": {"Bool": {"aws:SecureTransport": "false"}}}]}'

Related