Home > Software design >  How to set public permissions for files but not directories/folders in AWS S3
How to set public permissions for files but not directories/folders in AWS S3

Time:10-23

I have a bucket and I want its content to be public but not the folders, essentially allow access to any image or document in any folder or subfolder but deny access if I try to access the folder.

I currently use this Bucket Policy which gets the work pretty close:

{
    "Id": "Policy1666356335738",
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AccessContent",
            "Action": ["s3:GetObject"],
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::bucket-name/*",
            "Principal": "*"
        }
    ]
}

With this policy:

  1. I can access the content
  2. I get a 403 if I try to access a folder without trailing slash
  3. I get a 200 and the browser downloads an empty file named download if I try to access a folder using a trailing slash

How can I modify and configure my bucket so that also in the third case (using trailing slash) I get a 403 ?

CodePudding user response:

Folders do not actually exist in Amazon S3.

If you upload a file to a location (eg invoices/january.txt), then the invoices folder will magically 'appear'. However, it doesn't actually exist. If the object was then deleted, the invoices folder will 'disappear' because it never actually existed.

If you click the Create folder button in the Amazon S3 management console, then it creates a zero-length object with the name of the folder. This causes the folder to 'appear' even if there are no objects in that path (because the zero-length object is 'in' the path). This is probably what is happening with your Case #3.

You can resolve it by deleting the zero-length object with the name of the folder (which includes the trailing slash). This will not delete any objects inside the folder (because folders do not actually exist).

  • Related