When working with S3 buckets in a Node.js environment using the AWS Cloud Development Kit (CDK), developers need to be aware of certain gotchas to ensure the correct configuration and secure access to their buckets. Here, we explore a common issue related to granting public access and discuss a workaround to overcome it

Granting Public Access in Node.js CDK:
While creating an S3 bucket in Node.js CDK, developers often leverage the CDK construct called ‘Bucket’ to simplify the process. By default, the CDK provides an option to grant public read access to the bucket. In previous versions of the AWS policy, the following code snippet was sufficient to enable public access:

const s3Bucket = new s3api.Bucket(this, 'databucket123', {
  bucketName: 'someuniquebucketname',
  publicReadAccess: true
});

However, with the recent changes in the AWS security policy, as announced in April 2023, the above code will no longer work as expected. These changes are aimed at enhancing the security of S3 buckets and reducing the risk of unintended public access.

Solution:
To adapt to the new security policy, developers need to modify the code by implementing a workaround. The following code snippet demonstrates the updated approach:

const s3Bucket = new s3api.Bucket(this, 'databucket123', {
  bucketName: 'someuniquebucketname',
  blockPublicAccess: s3api.BlockPublicAccess.BLOCK_ACLS,
  accessControl: s3api.BucketAccessControl.BUCKET_OWNER_FULL_CONTROL
});

In this updated version, we explicitly set the blockPublicAccess property to s3api.BlockPublicAccess.BLOCK_ACLS to prevent public access through Access Control Lists (ACLs).
Additionally, we set the accessControl property to s3api.BucketAccessControl.BUCKET_OWNER_FULL_CONTROL to ensure that only the bucket owner has full control over the bucket.

Granting Public Access:
After implementing the workaround, if there is a specific requirement to grant public access to the bucket, we can use the grantPublicAccess() method as shown below:

s3Bucket.grantPublicAccess();

By invoking this method, we explicitly grant public access to the bucket while maintaining the desired security restrictions.