bucket policy vs iam policy which one takes the precedence

I have a task to create an S3 bucket named "xyz" and give Read-Write access to particular users. I have created the bucket and wrote an IAM policy like the following and attached it to specific users.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:GetObjectVersion",
                "s3:GetBucket"
            ],
            "Resource": [
                "arn:aws:s3:::xyz",
                "arn:aws:s3:::xyz/*"
            ]
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": "s3:ListAllMyBuckets",
            "Resource": "*"
        }
    ]
}

Now I have to apply another condition, that is restricting access to this bucket to a particular VPC. For that I have to write a bucket policy.

While trying to generate the bucket policy using policy generator it's again asking for actions on the S3 bucket.

If I select all the actions i.e, s3:* will it be giving all the access to the users?

I want to know which policy takes the precedence.


Solution 1:

None of them takes precedence. This is the way permissions work in AWS:

  1. Does any of the applicable policies explicitly allow access?

    ⇨ If not access is denied by default.

    ⇨ If yes go to the next step.

  2. Does any of the applicable policies explicitly deny access?

    ⇨ If yes access is denied (even if another policy allows access).

    ⇨ If there is no deny access is now granted.

That means that if there is no applicable policy then access is by default denied and if any policy denies access then access is denied too.

Only if one or more policies explicitly allow access and none denies access only then access is granted.

In your case the bucket policy should deny access to everyone not in your VPC (using policy conditions). The IAM Policy will then grant access to your users while the bucket policy will deny access from outside of your VPC.

Also note that individual objects in S3 can have their own permissions too.

Best to refer to Overview of Managing S3 Access for all the details.

Hope that helps :)