fix(s3): check bucket policies for the actions IAM checks (#5913)

S3's own access check under floci.services.s3.enforce-auth, which
evaluates bucket policies and ACLs, lagged behind IAM enforcement. It
checked a version's tagging, ACL and annotation requests as the base
actions, an object created with tags, an ACL or Object Lock settings as
s3:PutObject alone, GetObjectAttributes without the read, and a write
carrying If-Match without the read IAM checks for it. It offered a
bucket policy none of the request's condition keys, and asked for
s3:BypassGovernanceRetention on an annotation delete, which the user
guide says the permission "does not apply to".

The bucket-policy check now checks the actions IAM does: the version
counterpart when a request names a versionId, the tagging, ACL,
retention and legal-hold actions an object creation's settings need, a
copy of a tagged source included, s3:GetObject beside
s3:GetObjectAttributes and beside an If-Match write, and no bypass
permission on an annotation delete. A signed request's bucket policy is
offered the tag and Object Lock keys the request sets: an object
creation's headers and the tagging, retention and legal-hold bodies,
read by the same S3ObjectActions helpers IAM's condition resolver now
uses.

s3:BypassGovernanceRetention is asked for only by a request that
overrides a governance lock, by IAM and by the bucket policy. The user
guide's permissions table requires it "if you want to delete an object
that's protected by governance mode" and to "bypass the governance mode
of an Object Lock retention configuration", and DeleteObjects already
asked for it only then. DeleteObject and PutObjectRetention asked for
it whenever the header was sent; they now ask only for a delete that
removes a version under a governance lock, not one that only adds a
delete marker, and for a retention change that shortens or removes one.

The IAM condition resolver now reads the object key from the path as
it arrived, as S3Controller does, through the new S3ObjectKeys: the
normalized path drops a key's leading slash, so the lock and the
s3:ExistingObjectTag tags of "/doc" were looked up on "doc". A CopyObject
replacing its source's tags reads x-amz-tagging from the query as well,
as PutObject does, so it applies the tags both checks saw. An anonymous
creation that a public bucket ACL's WRITE grant admits may still apply
its ACL, tags and Object Lock settings, unless a public bucket policy
decides their actions, since an ACL grant names no actions.

The creation checks are told whether a request is a CopyObject rather
than guessing it from x-amz-copy-source, which a CreateMultipartUpload
ignores while it applies its own tags, so those tags are always
checked, by IAM and by the bucket policy. With an access check on, a
DeleteObject, a DeleteObjects entry and a PutObjectRetention hand
S3Service the bypass only when they override a lock whose bypass
permission the checks approved, IAM's decision travelling in
RequestContext, so a lock set after the checks is refused rather than
bypassed unchecked.

Refs #5716
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-18 09:28:33 -05:00
1 parent d6ffe3037e
commit c17bd49096
16 files changed
+1063 -179

No files matched your search

@@ -90,7 +90,8 @@ class IamConditionContextResolverTest {
config = mock(EmulatorConfig.class);
when(config.defaultRegion()).thenReturn("us-east-1");
resolver = new IamConditionContextResolver(
dynamoDbFacadeInstance, ec2ServiceInstance, s3ServiceInstance, logsServiceInstance, requestContext, config);
dynamoDbFacadeInstance, ec2ServiceInstance, s3ServiceInstance, logsServiceInstance, requestContext, config,
null);
}
@Test
@@ -359,7 +360,7 @@ class IamConditionContextResolverTest {
@SuppressWarnings("unchecked")
private IamConditionContextResolver resolverAt(Instant now) {
return new IamConditionContextResolver(mock(Instance.class), mock(Instance.class), mock(Instance.class),
mock(Instance.class), requestContext, config, Clock.fixed(now, ZoneOffset.UTC));
mock(Instance.class), requestContext, config, null, Clock.fixed(now, ZoneOffset.UTC));
}
@Test
@@ -2031,6 +2031,46 @@ class IamEnforcementFilterTest {
"x-amz-object-attributes", "ETag", "s3:GetObject", "s3:GetObjectAttributes"));
}
@Test
void theGovernanceBypassDecisionIsRecordedForS3ToHonour() {
// S3Controller lets a delete bypass a lock only as far as this check approved it, so a lock set
// after the check is refused rather than bypassed without the permission.
assertEquals(Boolean.FALSE, governanceBypassDecision(false));
assertEquals(Boolean.TRUE, governanceBypassDecision(true));
}
/** Runs an allowed versioned delete sending the bypass header and returns the decision recorded. */
private Boolean governanceBypassDecision(boolean overrides) {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
UriInfo uriInfo = mock(UriInfo.class);
MultivaluedHashMap<String, String> query = new MultivaluedHashMap<>();
query.putSingle("versionId", "v1");
when(uriInfo.getPath()).thenReturn("/bucket/object");
when(uriInfo.getQueryParameters()).thenReturn(query);
when(containerRequest.getUriInfo()).thenReturn(uriInfo);
when(containerRequest.getMethod()).thenReturn("DELETE");
String auth = "AWS4-HMAC-SHA256 Credential=AKIABYPASS/20260706/us-east-1/s3/aws4_request, "
+ "SignedHeaders=host, Signature=abc";
requestContext.setAccountId("222233334444");
requestContext.setRegion("us-east-1");
requestContext.setIamGovernanceBypass(null);
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIABYPASS");
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
when(containerRequest.getHeaderString("x-amz-bypass-governance-retention")).thenReturn("true");
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:DeleteObjectVersion");
when(iamService.resolveCallerContext(eq("AKIABYPASS"), any())).thenReturn(CallerContext.of(List.of()));
when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
.thenReturn(List.of("arn:aws:s3:::bucket/object"));
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), any(), any(), any()))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
when(conditionContextResolver.s3OverridesGovernanceRetention(any(), any())).thenReturn(overrides);
newFilter(mock(CurrentVertxRequest.class), mock(CloudTrailService.class)).filter(containerRequest);
verify(containerRequest, never()).abortWith(any());
return requestContext.getIamGovernanceBypass();
}
/**
* Runs an S3 request whose own action is allowed and whose extra action is denied, asserts the
* denial names the extra action, and returns the event name CloudTrail recorded for it.
@@ -2058,6 +2098,8 @@ class IamEnforcementFilterTest {
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), eq(deniedAction), any(), any()))
.thenReturn(IamPolicyEvaluator.Decision.DENY);
// A bypass header counts only on a request that overrides a governance lock.
when(conditionContextResolver.s3OverridesGovernanceRetention(any(), any())).thenReturn(true);
CloudTrailService cloudTrail = mock(CloudTrailService.class);
newFilter(mock(CurrentVertxRequest.class), cloudTrail).filter(containerRequest);
@@ -152,7 +152,8 @@ class DynamoDbFacadeTest {
RequestContext requestContext = new RequestContext();
requestContext.setRegion(OTHER_REGION);
IamConditionContextResolver resolver = new IamConditionContextResolver(dynamoDb,
mock(Instance.class), mock(Instance.class), mock(Instance.class), requestContext, mock(EmulatorConfig.class));
mock(Instance.class), mock(Instance.class), mock(Instance.class), requestContext, mock(EmulatorConfig.class),
null);
ContainerRequestContext request = mock(ContainerRequestContext.class);
JsonNode body = mapper.readTree("""
{"TableName": "recorded-table", "Key": {"id": {"S": "USER_alice"}}}
@@ -12,13 +12,21 @@ import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Each S3 operation is checked as the action AWS documents for it: the multipart upload operations
@@ -188,7 +196,9 @@ class S3ObjectOperationsIamEnforcementIntegrationTest {
.body(retention("2031-01-01T00:00:00Z"))
.when().put(f.path("a/governed")).then().statusCode(200);
// Extending the lock overrides nothing, so the header asks for nothing more; shortening it does.
f.policy(f.allow("s3:PutObjectRetention"));
f.putRetention("a/governed", "2032-01-01T00:00:00Z", true).statusCode(200);
denied(f.putRetention("a/governed", "2030-01-01T00:00:00Z", true), "s3:BypassGovernanceRetention");
f.policy(f.allow("s3:PutObjectRetention", "s3:BypassGovernanceRetention"));
@@ -196,18 +206,23 @@ class S3ObjectOperationsIamEnforcementIntegrationTest {
}
@Test
void deletingWithTheBypassNeedsBypassGovernanceRetention() {
// The DeleteObject API reference: "To use this header, you must have the
// s3:BypassGovernanceRetention permission", whether or not the request names a version.
void deletingWithTheBypassNeedsBypassGovernanceRetentionOnlyToRemoveALockedVersion() {
// The permissions table: s3:BypassGovernanceRetention is "Required if you want to delete an
// object that's protected by governance mode", so the header on a delete that removes no
// locked version asks for nothing more.
Fixture f = new Fixture("delete-bypass", true);
String versionId = f.seedVersion("a/governed");
String free = f.seedVersion("a/free");
f.admin().queryParam("retention", "").queryParam("versionId", versionId)
.body(retention("2031-01-01T00:00:00Z"))
.when().put(f.path("a/governed")).then().statusCode(200);
f.policy(f.allow("s3:DeleteObject", "s3:DeleteObjectVersion"));
denied(f.user().header("x-amz-bypass-governance-retention", "true")
.when().delete(f.path("a/governed")).then(), "s3:BypassGovernanceRetention");
// An unlocked version, and a delete that only adds a delete marker over the locked one.
f.user().header("x-amz-bypass-governance-retention", "true").queryParam("versionId", free)
.when().delete(f.path("a/free")).then().statusCode(204);
f.user().header("x-amz-bypass-governance-retention", "true")
.when().delete(f.path("a/governed")).then().statusCode(204);
denied(f.user().header("x-amz-bypass-governance-retention", "true").queryParam("versionId", versionId)
.when().delete(f.path("a/governed")).then(), "s3:BypassGovernanceRetention");
@@ -216,6 +231,44 @@ class S3ObjectOperationsIamEnforcementIntegrationTest {
.when().delete(f.path("a/governed")).then().statusCode(204);
}
@Test
void theBypassIsDecidedOnTheKeyARequestNamesEvenWithALeadingSlash() {
// A key that starts with "/" travels as "//" after the bucket, which JAX-RS collapses to the
// key without it. The lock is looked up on the key the request names, so a governance lock on
// "/governed" still needs s3:BypassGovernanceRetention to shorten or delete.
Fixture f = new Fixture("slash-bypass", true);
HttpResponse<String> put = f.raw("PUT", "/governed", null, ADMIN, Map.of(), "version");
assertEquals(200, put.statusCode(), put.body());
String versionId = put.headers().firstValue("x-amz-version-id").orElseThrow();
String version = "versionId=" + versionId;
assertEquals(200, f.raw("PUT", "/governed", "retention&" + version, ADMIN, Map.of(),
retention("2031-01-01T00:00:00Z")).statusCode());
Map<String, String> bypass = Map.of("x-amz-bypass-governance-retention", "true");
f.policy(f.allow("s3:PutObjectRetention", "s3:DeleteObjectVersion"));
rawDenied(f.raw("PUT", "/governed", "retention&" + version, f.accessKeyId, bypass,
retention("2030-01-01T00:00:00Z")), "s3:BypassGovernanceRetention");
rawDenied(f.raw("DELETE", "/governed", version, f.accessKeyId, bypass, null),
"s3:BypassGovernanceRetention");
f.policy(f.allow("s3:DeleteObjectVersion", "s3:BypassGovernanceRetention"));
assertEquals(204, f.raw("DELETE", "/governed", version, f.accessKeyId, bypass, null).statusCode());
}
@Test
void anExistingObjectTagConditionReadsTheTagsOfTheKeyARequestNames() {
// "/doc" and "doc" are two objects; a read of "/doc" is authorized against its own tags.
Fixture f = new Fixture("slash-tags", true);
assertEquals(200, f.raw("PUT", "/doc", null, ADMIN, Map.of("x-amz-tagging", "env=a"), "slash").statusCode());
f.admin().header("x-amz-tagging", "env=b").body("plain").when().put(f.path("doc")).then().statusCode(200);
f.policy(f.allowWhen("{\"StringEquals\":{\"s3:ExistingObjectTag/env\":\"a\"}}", "s3:GetObject"));
HttpResponse<String> slash = f.raw("GET", "/doc", null, f.accessKeyId, Map.of(), null);
assertEquals(200, slash.statusCode(), slash.body());
assertEquals("slash", slash.body());
denied(f.user().when().get(f.path("doc")).then(), "s3:GetObject");
}
@Test
void deletingAnAnnotationWithTheBypassHeaderNeedsNoBypassPermission() {
// The user guide: "The BypassGovernanceRetention permission does not apply to annotation
@@ -268,6 +321,10 @@ class S3ObjectOperationsIamEnforcementIntegrationTest {
.when().put(f.path("a/grant")).then(), "s3:PutObjectAcl");
denied(f.user().header("x-amz-tagging", "env=a").queryParam("uploads", "")
.when().post(f.path("a/upload")).then(), "s3:PutObjectTagging");
// A multipart upload ignores x-amz-copy-source and applies its own tags, so the header does not
// make it a copy whose tags come from a source.
denied(f.user().header("x-amz-tagging", "env=a").header("x-amz-copy-source", f.bucket + "/a/source")
.queryParam("uploads", "").when().post(f.path("a/upload")).then(), "s3:PutObjectTagging");
denied(f.user().header("x-amz-acl", "private").queryParam("uploads", "")
.when().post(f.path("a/upload")).then(), "s3:PutObjectAcl");
denied(f.copy().header("x-amz-tagging-directive", "REPLACE").header("x-amz-tagging", "env=a")
@@ -575,6 +632,11 @@ class S3ObjectOperationsIamEnforcementIntegrationTest {
.body(containsString(action));
}
private static void rawDenied(HttpResponse<String> response, String action) {
assertEquals(403, response.statusCode(), response.body());
assertTrue(response.body().contains("AccessDenied") && response.body().contains(action), response.body());
}
private static String retention(String until) {
return """
<Retention xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
@@ -618,6 +680,28 @@ class S3ObjectOperationsIamEnforcementIntegrationTest {
return "/" + bucket + "/" + key;
}
/**
* Sends a request on {@code key} with the path as written, signed as {@code accessKeyId}:
* RestAssured, like JAX-RS, collapses the double slash a key starting with "/" travels as.
*/
HttpResponse<String> raw(String method, String key, String query, String accessKeyId,
Map<String, String> headers, String body) {
URI uri = URI.create("http://localhost:" + baseUri.getPort() + path(key) + (query == null ? "" : "?" + query));
HttpRequest.Builder request = HttpRequest.newBuilder(uri)
.header("Authorization", auth(accessKeyId, "s3"))
.method(method, body == null
? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(body));
headers.forEach(request::header);
try (HttpClient client = HttpClient.newHttpClient()) {
return client.send(request.build(), HttpResponse.BodyHandlers.ofString());
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
}
String allowOnBucket(String... actions) {
return "{\"Effect\":\"Allow\",\"Action\":[\"" + String.join("\",\"", actions)
+ "\"],\"Resource\":\"arn:aws:s3:::" + bucket + "\"}";
@@ -782,6 +866,11 @@ class S3ObjectOperationsIamEnforcementIntegrationTest {
List<String> keys = versions.getList("ListVersionsResult." + entry + ".Key", String.class);
List<String> ids = versions.getList("ListVersionsResult." + entry + ".VersionId", String.class);
for (int i = 0; i < keys.size(); i++) {
if (keys.get(i).startsWith("/")) {
assertEquals(204, raw("DELETE", keys.get(i), "versionId=" + ids.get(i), ADMIN,
Map.of("x-amz-bypass-governance-retention", "true"), null).statusCode());
continue;
}
admin().header("x-amz-bypass-governance-retention", "true")
.queryParam("versionId", ids.get(i))
.when().delete(path(keys.get(i))).then().statusCode(204);
@@ -1311,21 +1311,25 @@ class S3AuthEnforcementIntegrationTest {
@Test
@Order(42)
void deleteObjectDoesNotBypassGovernanceRetentionWithoutDistinctPermission() {
given().filter(LOCAL_SIGNER).when().put("/" + BYPASS_BUCKET).then().statusCode(200);
given()
.filter(LOCAL_SIGNER)
void deleteObjectNeedsTheBypassPermissionOnlyToRemoveAGovernanceLockedVersion() {
// The permissions table requires s3:BypassGovernanceRetention "if you want to delete an object
// that's protected by governance mode", so the header alone asks for nothing more.
given().filter(LOCAL_SIGNER).header("x-amz-bucket-object-lock-enabled", "true")
.when().put("/" + BYPASS_BUCKET).then().statusCode(200);
String free = given().filter(LOCAL_SIGNER).body("unlocked")
.when().put("/" + BYPASS_BUCKET + "/free.txt")
.then().statusCode(200).extract().header("x-amz-version-id");
String locked = given().filter(LOCAL_SIGNER)
.header("x-amz-object-lock-mode", "GOVERNANCE")
.header("x-amz-object-lock-retain-until-date", "2031-01-01T00:00:00Z")
.body("locked candidate")
.when()
.put("/" + BYPASS_BUCKET + "/" + BYPASS_KEY)
.then()
.statusCode(200);
.when().put("/" + BYPASS_BUCKET + "/" + BYPASS_KEY)
.then().statusCode(200).extract().header("x-amz-version-id");
given()
.filter(LOCAL_SIGNER)
.contentType("application/json")
.body(publicObjectActionPolicy(BYPASS_BUCKET, "s3:DeleteObject"))
.body(publicObjectActionPolicy(BYPASS_BUCKET, "s3:DeleteObjectVersion"))
.when()
.put("/" + BYPASS_BUCKET + "?policy")
.then()
@@ -1333,6 +1337,14 @@ class S3AuthEnforcementIntegrationTest {
given()
.header("x-amz-bypass-governance-retention", "true")
.queryParam("versionId", free)
.when()
.delete("/" + BYPASS_BUCKET + "/free.txt")
.then()
.statusCode(204);
given()
.header("x-amz-bypass-governance-retention", "true")
.queryParam("versionId", locked)
.when()
.delete("/" + BYPASS_BUCKET + "/" + BYPASS_KEY)
.then()
@@ -1350,6 +1362,7 @@ class S3AuthEnforcementIntegrationTest {
given()
.header("x-amz-bypass-governance-retention", "true")
.queryParam("versionId", locked)
.when()
.delete("/" + BYPASS_BUCKET + "/" + BYPASS_KEY)
.then()
@@ -1363,7 +1376,7 @@ class S3AuthEnforcementIntegrationTest {
"Statement": {
"Effect": "Allow",
"Principal": "*",
"Action": ["s3:DeleteObject", "s3:BypassGovernanceRetention"],
"Action": ["s3:DeleteObjectVersion", "s3:BypassGovernanceRetention"],
"Resource": "arn:aws:s3:::%s/*"
}
}
@@ -0,0 +1,37 @@
package io.github.hectorvent.floci.services.s3;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The bypass a delete or retention change hands S3Service. With an access check on, it is the
* header only for a request that overrides a governance lock and whose bypass permission the checks
* approved, so a lock set after the checks is refused rather than bypassed without the permission.
*/
class S3ControllerGovernanceBypassTest {
@Test
void withNoCheckOnTheHeaderIsHandedOnAsSent() {
assertTrue(S3Controller.effectiveBypass(true, false, false, null));
assertFalse(S3Controller.effectiveBypass(false, false, false, null));
}
@Test
void s3sOwnCheckHandsItOnOnlyForARequestThatOverridesALock() {
assertTrue(S3Controller.effectiveBypass(true, true, true, null));
assertFalse(S3Controller.effectiveBypass(true, false, true, null));
assertFalse(S3Controller.effectiveBypass(false, true, true, null));
}
@Test
void anIamCheckThatFoundNoLockToOverrideHandsItOnForNone() {
// IAM saw no lock, so it checked no bypass permission: a lock S3Controller sees afterwards was
// set after IAM's check, and the operation must refuse it.
assertFalse(S3Controller.effectiveBypass(true, true, false, false));
assertFalse(S3Controller.effectiveBypass(true, true, true, false));
assertTrue(S3Controller.effectiveBypass(true, true, false, true));
assertFalse(S3Controller.effectiveBypass(true, false, false, true));
}
}
@@ -0,0 +1,356 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.testing.S3EnforceAuthProfile;
import io.github.hectorvent.floci.testutil.S3RequestSigner;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
/**
* S3's own bucket-policy check, with IAM enforcement off, checks an object request as the actions
* the enforcement filter does: the version action a versionId selects, s3:GetObject beside
* s3:GetObjectAttributes and beside a write carrying If-Match, and the actions an object created
* with tags, an ACL or Object Lock settings, or copied from a tagged object, needs besides
* s3:PutObject. The policy is offered the tag and Object Lock keys the request sets, and
* s3:BypassGovernanceRetention is asked for only by a request that overrides a governance lock.
* Each case is an explicit Deny in the bucket policy refusing the bucket owner.
*/
@QuarkusTest
@TestProfile(S3EnforceAuthProfile.class)
class S3ObjectOperationsBucketPolicyIntegrationTest {
private static final S3RequestSigner OWNER = S3RequestSigner.signedAs("test", "test");
@Test
void aRequestNamingAVersionIsCheckedAsTheVersionAction() {
String bucket = bucket(true);
String versionId = owner().header("x-amz-tagging", "env=a").body("v1").when().put(bucket + "/doc")
.then().statusCode(200).extract().header("x-amz-version-id");
owner().queryParam("annotation", "").queryParam("annotationName", "labels").body("x")
.when().put(bucket + "/doc").then().statusCode(200);
policy(bucket, deny("s3:GetObjectVersionTagging", "s3:PutObjectVersionTagging",
"s3:DeleteObjectVersionTagging", "s3:GetObjectVersionAcl", "s3:GetObjectVersionAnnotation",
"s3:PutObjectVersionAnnotation", "s3:DeleteObjectVersionAnnotation"));
owner().queryParam("tagging", "").queryParam("versionId", versionId).when().get(bucket + "/doc")
.then().statusCode(403);
owner().queryParam("tagging", "").queryParam("versionId", versionId)
.body("<Tagging><TagSet/></Tagging>").when().put(bucket + "/doc").then().statusCode(403);
owner().queryParam("tagging", "").queryParam("versionId", versionId).when().delete(bucket + "/doc")
.then().statusCode(403);
owner().queryParam("acl", "").queryParam("versionId", versionId).when().get(bucket + "/doc")
.then().statusCode(403);
owner().queryParam("annotation", "").queryParam("annotationName", "labels")
.queryParam("versionId", versionId).when().get(bucket + "/doc").then().statusCode(403);
owner().queryParam("annotation", "").queryParam("annotationName", "labels")
.queryParam("versionId", versionId).body("y").when().put(bucket + "/doc").then().statusCode(403);
owner().queryParam("annotation", "").queryParam("annotationName", "labels")
.queryParam("versionId", versionId).when().delete(bucket + "/doc").then().statusCode(403);
// Without a versionId the base actions are checked, which the policy leaves alone.
owner().queryParam("tagging", "").when().get(bucket + "/doc").then().statusCode(200);
owner().queryParam("acl", "").when().get(bucket + "/doc").then().statusCode(200);
owner().queryParam("annotation", "").queryParam("annotationName", "labels")
.when().get(bucket + "/doc").then().statusCode(200);
}
@Test
void getObjectAttributesNeedsTheReadAsWell() {
String bucket = bucket(false);
owner().body("data").when().put(bucket + "/doc").then().statusCode(200);
policy(bucket, deny("s3:GetObject"));
attributes(bucket + "/doc").then().statusCode(403);
policy(bucket, deny("s3:GetObjectAttributes"));
attributes(bucket + "/doc").then().statusCode(403);
owner().when().get(bucket + "/doc").then().statusCode(200);
}
@Test
void aWriteCarryingIfMatchNeedsTheReadAsWell() {
String bucket = bucket(false);
String source = bucket(false);
String eTag = owner().body("v1").when().put(bucket + "/doc").then().statusCode(200).extract().header("ETag");
owner().body("copied").when().put(source + "/doc").then().statusCode(200);
policy(bucket, deny("s3:GetObject"));
owner().header("If-Match", eTag).body("v2").when().put(bucket + "/doc").then().statusCode(403);
owner().header("If-Match", eTag).header("x-amz-copy-source", source + "/doc")
.when().put(bucket + "/doc").then().statusCode(403);
String uploadId = owner().queryParam("uploads", "").when().post(bucket + "/doc")
.then().statusCode(200).extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId");
String partETag = owner().queryParam("uploadId", uploadId).queryParam("partNumber", 1).body("v3")
.when().put(bucket + "/doc").then().statusCode(200).extract().header("ETag");
String parts = "<CompleteMultipartUpload><Part><PartNumber>1</PartNumber><ETag>" + partETag
+ "</ETag></Part></CompleteMultipartUpload>";
owner().header("If-Match", eTag).queryParam("uploadId", uploadId).body(parts)
.when().post(bucket + "/doc").then().statusCode(403);
// The same writes without the condition need only the write.
owner().queryParam("uploadId", uploadId).body(parts).when().post(bucket + "/doc").then().statusCode(200);
owner().body("v4").when().put(bucket + "/doc").then().statusCode(200);
}
@Test
void anObjectCreatedWithTagsOrAnAclNeedsThoseActions() {
String bucket = bucket(false);
policy(bucket, deny("s3:PutObjectTagging", "s3:PutObjectAcl"));
owner().header("x-amz-tagging", "env=a").body("tagged").when().put(bucket + "/tagged")
.then().statusCode(403);
owner().header("x-amz-acl", "bucket-owner-full-control").body("acl").when().put(bucket + "/acl")
.then().statusCode(403);
owner().header("x-amz-tagging", "env=a").queryParam("uploads", "").when().post(bucket + "/upload")
.then().statusCode(403);
owner().body("plain").when().put(bucket + "/plain").then().statusCode(200);
// A multipart upload ignores x-amz-copy-source and applies its own tags, so the header does not
// make it a copy whose tags come from a source.
owner().header("x-amz-tagging", "env=a").header("x-amz-copy-source", bucket + "/plain")
.queryParam("uploads", "").when().post(bucket + "/upload").then().statusCode(403);
}
@Test
void aCopyOfATaggedObjectNeedsPutObjectTagging() {
String bucket = bucket(false);
owner().header("x-amz-tagging", "env=a").body("tagged").when().put(bucket + "/tagged")
.then().statusCode(200);
owner().body("plain").when().put(bucket + "/plain").then().statusCode(200);
policy(bucket, deny("s3:PutObjectTagging"));
owner().header("x-amz-copy-source", bucket + "/tagged").when().put(bucket + "/copy")
.then().statusCode(403);
owner().header("x-amz-copy-source", bucket + "/plain").header("x-amz-tagging-directive", "REPLACE")
.header("x-amz-tagging", "env=b").when().put(bucket + "/copy").then().statusCode(403);
owner().header("x-amz-copy-source", bucket + "/plain").when().put(bucket + "/copy")
.then().statusCode(200);
}
@Test
void aReplacingCopyAppliesTheTagsItIsCheckedForFromAPresignedQuery() throws Exception {
// A presigner may move x-amz-tagging into the query, where PutObject already reads it; a copy
// replacing its source's tags reads it there too, so the object gets the tags the policy saw.
String bucket = bucket(false);
owner().body("plain").when().put(bucket + "/plain").then().statusCode(200);
policy(bucket, denyWhen("{\"StringEquals\":{\"s3:RequestObjectTag/env\":\"secret\"}}", "s3:PutObject"));
presignedCopy(bucket + "/plain", bucket + "/secret?x-amz-tagging=env%3Dsecret").then().statusCode(403);
presignedCopy(bucket + "/plain", bucket + "/copy?x-amz-tagging=env%3Db").then().statusCode(200);
owner().queryParam("tagging", "").when().get(bucket + "/copy").then().statusCode(200)
.body(containsString("<Value>b</Value>"));
}
@Test
void anAnonymousCreationAPublicBucketAclAdmitsMayApplyItsSettings() {
// The bucket ACL's WRITE grant admits the creation with its ACL and tags, as before they were
// checked; a public bucket policy that names a setting's action still decides it.
String bucket = bucket(false);
owner().body("<OwnershipControls><Rule><ObjectOwnership>ObjectWriter</ObjectOwnership></Rule></OwnershipControls>")
.when().put(bucket + "?ownershipControls").then().statusCode(200);
owner().header("x-amz-acl", "public-read-write").when().put(bucket + "?acl").then().statusCode(200);
given().header("x-amz-acl", "bucket-owner-full-control").body("acl").when().put(bucket + "/acl")
.then().statusCode(200);
given().header("x-amz-tagging", "env=a").body("tagged").when().put(bucket + "/tagged")
.then().statusCode(200);
policy(bucket, deny("s3:PutObjectTagging"));
given().header("x-amz-tagging", "env=a").body("tagged").when().put(bucket + "/denied")
.then().statusCode(403);
given().body("plain").when().put(bucket + "/plain").then().statusCode(200);
}
@Test
void anObjectCreationOffersItsTagAndObjectLockKeys() {
String bucket = lockedBucket();
policy(bucket, denyWhen("{\"StringEquals\":{\"s3:RequestObjectTag/env\":\"secret\"}}",
"s3:PutObjectTagging")
+ "," + denyWhen("{\"StringEquals\":{\"s3:object-lock-mode\":\"COMPLIANCE\"}}",
"s3:PutObjectRetention")
+ "," + denyWhen("{\"StringEquals\":{\"s3:object-lock-legal-hold\":\"ON\"}}",
"s3:PutObjectLegalHold")
+ "," + denyWhen("{\"ForAnyValue:StringEquals\":{\"s3:RequestObjectTagKeys\":\"blocked\"}}",
"s3:PutObject"));
owner().header("x-amz-tagging", "env=secret").body("x").when().put(bucket + "/secret")
.then().statusCode(403);
owner().header("x-amz-tagging", "env=secret").queryParam("uploads", "").when().post(bucket + "/upload")
.then().statusCode(403);
owner().header("x-amz-tagging", "env=open").body("x").when().put(bucket + "/open")
.then().statusCode(200);
owner().header("x-amz-tagging", "blocked=yes").body("x").when().put(bucket + "/blocked")
.then().statusCode(403);
owner().header("x-amz-object-lock-mode", "COMPLIANCE")
.header("x-amz-object-lock-retain-until-date", "2031-01-01T00:00:00Z")
.body("x").when().put(bucket + "/compliance").then().statusCode(403);
owner().header("x-amz-object-lock-mode", "GOVERNANCE")
.header("x-amz-object-lock-retain-until-date", "2031-01-01T00:00:00Z")
.body("x").when().put(bucket + "/governance").then().statusCode(200);
owner().header("x-amz-object-lock-legal-hold", "ON").body("x").when().put(bucket + "/held")
.then().statusCode(403);
owner().header("x-amz-object-lock-legal-hold", "OFF").body("x").when().put(bucket + "/released")
.then().statusCode(200);
}
@Test
void theTaggingRetentionAndLegalHoldBodiesOfferTheirKeys() {
String bucket = lockedBucket();
owner().body("x").when().put(bucket + "/doc").then().statusCode(200);
policy(bucket, denyWhen("{\"StringEquals\":{\"s3:RequestObjectTag/env\":\"secret\"}}",
"s3:PutObjectTagging")
+ "," + denyWhen("{\"StringEquals\":{\"s3:object-lock-mode\":\"COMPLIANCE\"}}",
"s3:PutObjectRetention")
+ "," + denyWhen("{\"NumericGreaterThan\":{\"s3:object-lock-remaining-retention-days\":\"3650\"}}",
"s3:PutObjectRetention")
+ "," + denyWhen("{\"StringEquals\":{\"s3:object-lock-legal-hold\":\"ON\"}}",
"s3:PutObjectLegalHold"));
owner().queryParam("tagging", "").body(tagging("secret")).when().put(bucket + "/doc").then().statusCode(403);
owner().queryParam("tagging", "").body(tagging("open")).when().put(bucket + "/doc").then().statusCode(200);
owner().queryParam("retention", "").body(retention("COMPLIANCE", "2031-01-01T00:00:00Z"))
.when().put(bucket + "/doc").then().statusCode(403);
owner().queryParam("retention", "").body(retention("GOVERNANCE", "2045-01-01T00:00:00Z"))
.when().put(bucket + "/doc").then().statusCode(403);
owner().queryParam("retention", "").body(retention("GOVERNANCE", "2031-01-01T00:00:00Z"))
.when().put(bucket + "/doc").then().statusCode(200);
owner().queryParam("legal-hold", "").body(legalHold("ON")).when().put(bucket + "/doc").then().statusCode(403);
owner().queryParam("legal-hold", "").body(legalHold("OFF")).when().put(bucket + "/doc").then().statusCode(200);
}
@Test
void onlyARequestOverridingAGovernanceLockNeedsTheBypassPermission() {
// The permissions table requires s3:BypassGovernanceRetention "if you want to delete an object
// that's protected by governance mode" and to "bypass the governance mode of an Object Lock
// retention configuration".
String bucket = lockedBucket();
String locked = owner().header("x-amz-object-lock-mode", "GOVERNANCE")
.header("x-amz-object-lock-retain-until-date", "2031-01-01T00:00:00Z")
.body("locked").when().put(bucket + "/locked").then().statusCode(200)
.extract().header("x-amz-version-id");
String free = owner().body("free").when().put(bucket + "/free").then().statusCode(200)
.extract().header("x-amz-version-id");
owner().header("x-amz-object-lock-mode", "GOVERNANCE")
.header("x-amz-object-lock-retain-until-date", "2031-01-01T00:00:00Z")
.body("batch").when().put(bucket + "/batch").then().statusCode(200);
policy(bucket, deny("s3:BypassGovernanceRetention"));
// Extending the lock, deleting an unlocked version, and adding a delete marker override nothing.
bypass().queryParam("retention", "").queryParam("versionId", locked)
.body(retention("GOVERNANCE", "2032-01-01T00:00:00Z"))
.when().put(bucket + "/locked").then().statusCode(200);
bypass().queryParam("versionId", free).when().delete(bucket + "/free").then().statusCode(204);
bypass().when().delete(bucket + "/locked").then().statusCode(204);
bypass().contentType("application/xml").body("<Delete><Object><Key>batch</Key></Object></Delete>")
.when().post(bucket + "?delete").then().statusCode(200)
.body(containsString("<Deleted><Key>batch</Key>"));
// Shortening the lock and deleting the locked version override it.
bypass().queryParam("retention", "").queryParam("versionId", locked)
.body(retention("GOVERNANCE", "2030-01-01T00:00:00Z"))
.when().put(bucket + "/locked").then().statusCode(403);
bypass().queryParam("versionId", locked).when().delete(bucket + "/locked").then().statusCode(403);
}
@Test
void aRetentionChangeOnAMissingObjectOrBucketIsReportedMissing() {
String bucket = lockedBucket();
bypass().queryParam("retention", "").body(retention("GOVERNANCE", "2031-01-01T00:00:00Z"))
.when().put(bucket + "/missing").then().statusCode(404).body(containsString("NoSuchKey"));
bypass().queryParam("retention", "").body(retention("GOVERNANCE", "2031-01-01T00:00:00Z"))
.when().put("/s3ops-policy-missing-" + UUID.randomUUID() + "/doc").then().statusCode(404)
.body(containsString("NoSuchBucket"));
}
@Test
void deletingAnAnnotationWithTheBypassHeaderNeedsNoBypassPermission() {
// The user guide: "The BypassGovernanceRetention permission does not apply to annotation
// operations."
String bucket = lockedBucket();
owner().body("x").when().put(bucket + "/doc").then().statusCode(200);
owner().queryParam("annotation", "").queryParam("annotationName", "labels").body("x")
.when().put(bucket + "/doc").then().statusCode(200);
owner().queryParam("retention", "").body(retention("GOVERNANCE", "2031-01-01T00:00:00Z"))
.when().put(bucket + "/doc").then().statusCode(200);
policy(bucket, deny("s3:BypassGovernanceRetention"));
bypass().queryParam("annotation", "").queryParam("annotationName", "labels")
.when().delete(bucket + "/doc").then().statusCode(204);
}
private static RequestSpecification owner() {
return given().filter(OWNER);
}
private static RequestSpecification bypass() {
return owner().header("x-amz-bypass-governance-retention", "true");
}
/** A CopyObject replacing the source's tags, presigned by the owner over the destination's own query. */
private static Response presignedCopy(String source, String destinationAndQuery) throws Exception {
String query = OWNER.presignedQuery("PUT",
URI.create("http://localhost:" + RestAssured.port + destinationAndQuery), 300);
String destination = destinationAndQuery.substring(0, destinationAndQuery.indexOf('?'));
return given().urlEncodingEnabled(false).header("x-amz-copy-source", source)
.header("x-amz-tagging-directive", "REPLACE").when().put(destination + "?" + query);
}
private static Response attributes(String path) {
return owner().queryParam("attributes", "").header("x-amz-object-attributes", "ETag").when().get(path);
}
/** A new bucket, with versioning on when asked, as its path. */
private static String bucket(boolean versioned) {
String bucket = "/s3ops-policy-" + UUID.randomUUID();
owner().when().put(bucket).then().statusCode(200);
if (versioned) {
owner().body("<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>")
.when().put(bucket + "?versioning").then().statusCode(200);
}
return bucket;
}
/** A new bucket with Object Lock enabled, as its path. */
private static String lockedBucket() {
String bucket = "/s3ops-policy-" + UUID.randomUUID();
owner().header("x-amz-bucket-object-lock-enabled", "true").when().put(bucket).then().statusCode(200);
return bucket;
}
private static String tagging(String env) {
return "<Tagging><TagSet><Tag><Key>env</Key><Value>" + env + "</Value></Tag></TagSet></Tagging>";
}
private static String retention(String mode, String until) {
return "<Retention><Mode>" + mode + "</Mode><RetainUntilDate>" + until + "</RetainUntilDate></Retention>";
}
private static String legalHold(String status) {
return "<LegalHold><Status>" + status + "</Status></LegalHold>";
}
private static String denyWhen(String condition, String... actions) {
String deny = deny(actions);
return deny.substring(0, deny.length() - 1) + ",\"Condition\":" + condition + "}";
}
private static String deny(String... actions) {
return "{\"Effect\":\"Deny\",\"Principal\":\"*\",\"Action\":[\"" + String.join("\",\"", actions)
+ "\"],\"Resource\":\"arn:aws:s3:::%s/*\"}";
}
private static void policy(String bucket, String statement) {
owner().contentType("application/json")
.body("{\"Version\":\"2012-10-17\",\"Statement\":[" + statement.replace("%s", bucket.substring(1))
+ "]}")
.when().put(bucket + "?policy").then().statusCode(200);
}
}