Restrict access to an S3 VPC endpoint

Restrict access to an S3 VPC endpoint

A gateway VPC endpoint lets instances in a VPC reach S3 without going through the Internet Gateway. Combined with the aws:sourceVpce condition key in a bucket policy, you can make sure objects are only accessible from your VPC.

Create the gateway endpoint

  1. Open the VPC console → Endpoints → Create endpoint.
  2. Enter the name S3-Endpoint and keep AWS services selected.

Endpoint name

  1. In Services, filter on s3 and select com.amazonaws..s3 with type Gateway.

S3 gateway service

  1. In VPC, select SID-vpc. For now, do not select any route table – you will add it later to see the difference. Keep Full access for the endpoint policy and choose Create endpoint.

No route table selected

  1. Copy the VPC endpoint ID (vpce-...).

Endpoint created

Add the bucket policy

  1. In the S3 console, open the bucket → Permissions → Bucket policy → Edit, paste the policy below (replace the bucket name and the endpoint ID) and choose Save changes.
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "DenyOutsideVpce",
            "Action": "s3:*",
            "Effect": "Deny",
            "Principal": "*",
            "Resource": "arn:aws:s3:::<your-bucket-name>/*",
            "Condition": {
                "StringNotEquals": {
                    "aws:sourceVpce": "<your-vpc-endpoint-id>"
                }
            }
        }
    ]
}

Deny outside the VPC endpoint

  1. In the terminal, read the object metadata:
aws s3api head-object --key app1/file1 --bucket $bucket

The request fails with 403 Forbidden: the subnet route table has no route to the endpoint, so the traffic still leaves through the Internet Gateway and does not carry the endpoint ID.

Request outside the endpoint denied

Associate the route table

  1. Back in Endpoints, select S3-Endpoint → Actions → Manage route tables.

Manage route tables

  1. Select SID-routes and choose Modify route tables.

Select SID-routes

  1. Run the same command again. This time it succeeds, because S3 traffic from the subnet now goes through the gateway endpoint.

Request through the endpoint allowed

This policy also denies object access from the S3 console and from anywhere outside the VPC – including you. Delete it (or the whole stack) when you are done with the lab.