Skip to content

How to change the publicReadAccess property of an S3 bucket accessed via cfnBucket?

1

I am trying to set up an S3 bucket to host my static website. Using the amplify gen2 framework, I have created a bucket using the defineStorage class:

import { defineStorage } from "@aws-amplify/backend";

export const webHostingBucket = defineStorage({
  name: "hostingBucket",
});

The L1 construct of this bucket is then accessed in a custom class to override some properties:

import { NestedStack, NestedStackProps, RemovalPolicy } from "aws-cdk-lib";
import { Backend } from "../backend";

export class WebHosting extends NestedStack {
  constructor(backend: Backend, id: string, props?: NestedStackProps) {
    super(backend.stack, id, props);
    const { cfnResources } = backend.webHostingBucket.resources;
    cfnResources.cfnBucket.websiteConfiguration = {
      indexDocument: "index.html",
    };
    cfnResources.cfnBucket.publicAccessBlockConfiguration = {
      blockPublicAcls: false,
      blockPublicPolicy: false,
      ignorePublicAcls: false,
      restrictPublicBuckets: false,
    };
    cfnResources.cfnBucket.applyRemovalPolicy(RemovalPolicy.DESTROY);
  }
}

From a resource I have read online, it says that I would have to set publicReadAccess to true, but I am struggling to find this property. Also, I tried to configure the access control by updating the defineStorage definition to :

export const webHostingBucket = defineStorage({
  name: "hostingBucket",
  // access: (allow) => ({
  //   "*": [allow.guest],
  // }),
});

but Storage access paths must end with /*, not start with *'

Should I just create an S3 bucket manually or is there a way to access the publicReadAccess property for this amplofy managed resource?

asked a year ago289 views

2 Answers
1
Accepted Answer

Hello! This is an excellent question that gets to the heart of working with Amplify Gen 2's abstractions while needing lower-level CDK control. You're on the right track, but there are a few key concepts and a missing piece to make this work.

The core issue is that making an S3 bucket publicly readable for website hosting requires two separate configurations:

Bucket Policy: Grants public s3:GetObject permissions. This is what the publicReadAccess property would configure behind the scenes.

Block Public Access Settings: By default, all S3 buckets have these security blocks enabled. You must explicitly disable them to allow the public bucket policy to take effect.

You've successfully disabled the Block Public Access settings by overriding publicAccessBlockConfiguration. However, you are missing the Bucket Policy that actually grants public read access.

The error from the defineStorage access modifier (storage access paths must end with /*) is a red herring here. That system is designed for structuring fine-grained data access (e.g., for Auth users), not for configuring a bucket to be a public web host. The Solution: Add a Bucket Policy You need to add a Bucket Policy to the cfnBucket L1 construct. Here is your updated WebHosting class with the crucial addition:

import { NestedStack, NestedStackProps, RemovalPolicy } from "aws-cdk-lib"; import { Backend } from "../backend"; import { Effect, PolicyStatement, AnyPrincipal } from "aws-cdk-lib/aws-iam";

export class WebHosting extends NestedStack { constructor(backend: Backend, id: string, props?: NestedStackProps) { super(backend.stack, id, props);

const { cfnResources } = backend.webHostingBucket.resources;

// 1. Configure the bucket as a website
cfnResources.cfnBucket.websiteConfiguration = {
  indexDocument: "index.html",
  errorDocument: "error.html" // Highly recommended to add this too
};

// 2. Disable the Block Public Access settings
cfnResources.cfnBucket.publicAccessBlockConfiguration = {
  blockPublicAcls: false,
  blockPublicPolicy: false,
  ignorePublicAcls: false,
  restrictPublicBuckets: false,
};

// 3. [THE MISSING PIECE] Add a Bucket Policy to allow public read access
cfnResources.cfnBucket.addPropertyOverride('BucketPolicy', {
  PolicyDocument: {
    Statement: [
      {
        Effect: 'Allow',
        Principal: '*', // This makes it public
        Action: 's3:GetObject',
        Resource: `${cfnResources.cfnBucket.attrArn}/*` // Note the '/*' to allow reading objects
      }
    ]
  }
});

// 4. Set removal policy
cfnResources.cfnBucket.applyRemovalPolicy(RemovalPolicy.DESTROY);

Final Recommendation: Stick with your current approach since you've already built most of it. Adding the bucket policy as shown above should resolve the issue and make your website publicly accessible.

I hope this clears things up! Good luck with your project.

answered a year ago

EXPERT

reviewed a year ago

  • Thank you :)

0

To make your S3 bucket publicly accessible for hosting a static website, you need to do two things: disable the Block Public Access settings (which you've already done) and add a bucket policy that grants public read access.

Your current code correctly disables the Block Public Access settings through the publicAccessBlockConfiguration property, but there isn't a direct publicReadAccess property on the CFN bucket. Instead, you need to add a bucket policy that grants the s3:GetObject permission to everyone.

You can add this bucket policy to your WebHosting class like this:

import { NestedStack, NestedStackProps, RemovalPolicy } from "aws-cdk-lib";
import { PolicyStatement, Effect, AnyPrincipal } from "aws-cdk-lib/aws-iam";
import { Backend } from "../backend";

export class WebHosting extends NestedStack {
constructor(backend: Backend, id: string, props?: NestedStackProps) {
super(backend.stack, id, props);
const { cfnResources } = backend.webHostingBucket.resources;

// Configure website hosting
cfnResources.cfnBucket.websiteConfiguration = {
indexDocument: "index.html",
};

// Disable Block Public Access settings
cfnResources.cfnBucket.publicAccessBlockConfiguration = {
blockPublicAcls: false,
blockPublicPolicy: false,
ignorePublicAcls: false,
restrictPublicBuckets: false,
};

// Add bucket policy for public read access
const bucketName = cfnResources.cfnBucket.ref;
cfnResources.cfnBucket.bucketPolicy = {
policyDocument: {
Version: "2012-10-17",
Statement: [
{
Sid: "PublicReadGetObject",
Effect: "Allow",
Principal: "*",
Action: "s3:GetObject",
Resource: `arn:aws:s3:::${bucketName}/*`
}
]
}
};

cfnResources.cfnBucket.applyRemovalPolicy(RemovalPolicy.DESTROY);
}
}

This approach adds a bucket policy that allows anyone to read objects from your bucket, which is necessary for hosting a public static website.

Regarding the Amplify access configuration, you're right that the syntax is different. For Amplify Gen2, if you want to grant public read access to all objects in your bucket, you would use a path pattern ending with "/*" like this:

export const webHostingBucket = defineStorage({
name: "hostingBucket",
access: (allow) => ({
"/*": [allow.guest],
}),
});

However, since you're already configuring the bucket directly with CDK constructs, the bucket policy approach above should work for your use case.
Sources
Setting permissions for website access - Amazon Simple Storage Service
Tutorial: Configuring a static website on Amazon S3 - Amazon Simple Storage Service
Configuring block public access settings for your S3 buckets - Amazon Simple Storage Service
Module 5. Test your setup

answered a year ago

EXPERT

reviewed a year 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.