Light, fluffy, and always free - The AWS Local Emulator alternative
fix(s3): enforce auth on object write paths when enforce-auth is enabled (#2326)
Matheus Oliveira16a8f042e789
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPolicy.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPolicy.javaindex a134e15ed3..50509d630c 100644--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPolicy.java+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPolicy.java@@ -114,6 +114,10 @@ record S3AclPolicy(List<S3AclPolicy.Grant> grants) {return grantee.isAllUsersGroup() && permission.allowsRead();}+ boolean allowsPublicWrite() {+ return grantee.isAllUsersGroup() && permission.allowsWrite();+ }+boolean allowsCanonicalUserRead(String canonicalUserId) {return grantee.isCanonicalUser(canonicalUserId) && permission.allowsRead();}@@ -151,6 +155,10 @@ record S3AclPolicy(List<S3AclPolicy.Grant> grants) {boolean allowsRead() {return this == READ || this == FULL_CONTROL;}++ boolean allowsWrite() {+ return this == WRITE || this == FULL_CONTROL;+ }}private static final class SilentThrowingErrorHandler implements ErrorHandler {diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluator.javaindex cfa24c5844..7297eccacf 100644--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluator.java+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluator.java@@ -23,4 +23,17 @@ final class S3AclPublicAccessEvaluator {return false;}}++ static boolean aclAllowsPublicWrite(String acl) {+ if (acl == null || acl.isBlank()) {+ return false;+ }+ try {+ S3AclPolicy policy = S3AclPolicy.parse(acl);+ return policy.grants().stream().anyMatch(S3AclPolicy.Grant::allowsPublicWrite);+ } catch (S3AclPolicy.AclParseException e) {+ LOG.debugv(e, "Failed to parse S3 ACL for public write evaluation");+ return false;+ }+ }}diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.javaindex 92a24990ce..f534c9d3db 100644--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java@@ -617,19 +617,28 @@ public class S3Controller {byte[] body) {try {key = extractObjectKey(uriInfo, bucket);+ S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(+ s3Service.isAuthEnforced(), httpHeaders, uriInfo);if (hasQueryParam(uriInfo, "tagging")) {+ s3Service.authorizeObjectWrite(bucket, key, "s3:PutObjectTagging", authorization);return handlePutObjectTagging(bucket, key, body);}if (hasQueryParam(uriInfo, "retention")) {+ s3Service.authorizeObjectWrite(bucket, key, "s3:PutObjectRetention", authorization);+ if ("true".equalsIgnoreCase(httpHeaders.getHeaderString("x-amz-bypass-governance-retention"))) {+ s3Service.authorizeObjectWrite(bucket, key, "s3:BypassGovernanceRetention", authorization);+ }return handlePutObjectRetention(bucket, key,uriInfo.getQueryParameters().getFirst("versionId"), httpHeaders, body);}if (hasQueryParam(uriInfo, "legal-hold")) {+ s3Service.authorizeObjectWrite(bucket, key, "s3:PutObjectLegalHold", authorization);return handlePutObjectLegalHold(bucket, key,uriInfo.getQueryParameters().getFirst("versionId"), body);}if (hasQueryParam(uriInfo, "acl")) {+ s3Service.authorizeObjectWrite(bucket, key, "s3:PutObjectAcl", authorization);s3Service.putObjectAcl(bucket, key, uriInfo.getQueryParameters().getFirst("versionId"),new String(body, StandardCharsets.UTF_8),httpHeaders.getHeaderString("x-amz-acl"),@@ -642,6 +651,7 @@ public class S3Controller {}if (uploadId != null && partNumber != null) {+ s3Service.authorizeObjectWrite(bucket, key, "s3:PutObject", authorization);if (copySource != null && !copySource.isEmpty()) {return handleUploadPartCopy(copySource, bucket, key, uploadId, partNumber, httpHeaders);}@@ -659,6 +669,7 @@ public class S3Controller {}if (copySource != null && !copySource.isEmpty()) {+ s3Service.authorizeObjectWrite(bucket, key, "s3:PutObject", authorization);return handleCopyObject(copySource, bucket, key, contentType, httpHeaders);}@@ -680,6 +691,7 @@ public class S3Controller {String sseCustomerKey = httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-key");String sseCustomerKeyMd5 = httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-key-MD5");String cannedAcl = httpHeaders.getHeaderString("x-amz-acl");+ s3Service.authorizePutObject(bucket, key, authorization);S3Object obj = s3Service.putObject(bucket, key, data, contentType, extractUserMetadata(httpHeaders),new PutObjectOptions().withStorageClass(httpHeaders.getHeaderString("x-amz-storage-class"))@@ -1103,17 +1115,25 @@ public class S3Controller {@Context HttpHeaders httpHeaders) {try {key = extractObjectKey(uriInfo, bucket);+ S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(+ s3Service.isAuthEnforced(), httpHeaders, uriInfo);if (hasQueryParam(uriInfo, "tagging")) {+ s3Service.authorizeObjectWrite(bucket, key, "s3:DeleteObjectTagging", authorization);s3Service.deleteObjectTagging(bucket, key);return Response.noContent().build();}if (uploadId != null) {+ s3Service.authorizeObjectWrite(bucket, key, "s3:AbortMultipartUpload", authorization);s3Service.abortMultipartUpload(bucket, key, uploadId);return Response.noContent().build();}boolean bypass = "true".equalsIgnoreCase(httpHeaders.getHeaderString("x-amz-bypass-governance-retention"));+ s3Service.authorizeDeleteObject(bucket, key, versionId, authorization);+ if (bypass) {+ s3Service.authorizeObjectWrite(bucket, key, "s3:BypassGovernanceRetention", authorization);+ }S3Object result = s3Service.deleteObject(bucket, key, versionId, bypass);var resp = Response.noContent();if (result != null) {@@ -1137,11 +1157,12 @@ public class S3Controller {@Produces(MediaType.APPLICATION_XML)public Response handleBucketPost(@PathParam("bucket") String bucket,@HeaderParam("Content-Type") String contentType,+ @Context HttpHeaders httpHeaders,@Context UriInfo uriInfo,byte[] body) {try {if (hasQueryParam(uriInfo, "delete")) {- return handleDeleteObjects(bucket, body);+ return handleDeleteObjects(bucket, body, httpHeaders, uriInfo);}if (contentType != null && contentType.startsWith("multipart/form-data")) {return handlePresignedPost(bucket, contentType, body);@@ -1168,8 +1189,11 @@ public class S3Controller {byte[] body) {try {key = extractObjectKey(uriInfo, bucket);+ S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(+ s3Service.isAuthEnforced(), httpHeaders, uriInfo);if (hasQueryParam(uriInfo, "uploads")) {+ s3Service.authorizeObjectWrite(bucket, key, "s3:PutObject", authorization);MultipartUpload upload = s3Service.initiateMultipartUpload(bucket, key, contentType,extractUserMetadata(httpHeaders),httpHeaders.getHeaderString("x-amz-storage-class"),@@ -1195,13 +1219,12 @@ public class S3Controller {}if (hasQueryParam(uriInfo, "restore")) {+ s3Service.authorizeObjectWrite(bucket, key, "s3:RestoreObject", authorization);s3Service.restoreObject(bucket, key, versionId, new String(body, StandardCharsets.UTF_8));return Response.accepted().build();}if (hasQueryParam(uriInfo, "select")) {- S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(- s3Service.isAuthEnforced(), httpHeaders, uriInfo);s3Service.authorizeGetObject(bucket, key, versionId, authorization);S3Object obj = s3Service.getObject(bucket, key, versionId);byte[] result = s3SelectService.select(obj, new String(body, StandardCharsets.UTF_8));@@ -1211,6 +1234,7 @@ public class S3Controller {}if (uploadId != null) {+ s3Service.authorizeObjectWrite(bucket, key, "s3:PutObject", authorization);List<Integer> partNumbers = parseCompleteMultipartBody(new String(body));Response preconditionResponse = checkWritePreconditions(bucket, key, ifMatch, ifNoneMatch);if (preconditionResponse != null) {@@ -1250,7 +1274,7 @@ public class S3Controller {}}- private Response handleDeleteObjects(String bucket, byte[] body) {+ private Response handleDeleteObjects(String bucket, byte[] body, HttpHeaders httpHeaders, UriInfo uriInfo) {String xml = new String(body, StandardCharsets.UTF_8);List<String> keys = XmlParser.extractAll(xml, "Key");if (keys.isEmpty()) {@@ -1258,7 +1282,22 @@ public class S3Controller {"The XML you provided was not well-formed.", 400);}boolean quiet = XmlParser.containsValue(xml, "Quiet", "true");- S3Service.DeleteObjectsResult result = s3Service.deleteObjects(bucket, keys);++ S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(+ s3Service.isAuthEnforced(), httpHeaders, uriInfo);+ s3Service.authorizeSignedRequest(authorization);+ List<String> authorizedKeys = new ArrayList<>();+ List<S3Service.DeleteError> authorizationErrors = new ArrayList<>();+ for (String key : keys) {+ try {+ s3Service.authorizeObjectWrite(bucket, key, "s3:DeleteObject", authorization);+ authorizedKeys.add(key);+ } catch (AwsException e) {+ authorizationErrors.add(new S3Service.DeleteError(key, e.getErrorCode(), e.getMessage()));+ }+ }++ S3Service.DeleteObjectsResult result = s3Service.deleteObjects(bucket, authorizedKeys);XmlBuilder builder = new XmlBuilder().raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")@@ -1275,6 +1314,13 @@ public class S3Controller {builder.end("Deleted");}}+ for (S3Service.DeleteError e : authorizationErrors) {+ builder.start("Error")+ .elem("Key", e.key())+ .elem("Code", e.code())+ .elem("Message", e.message())+ .end("Error");+ }for (S3Service.DeleteError e : result.errors()) {builder.start("Error").elem("Key", e.key())diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.javaindex 992fc5d3b7..513473242e 100644--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java@@ -589,6 +589,72 @@ public class S3Service implements Resettable {authorizeS3Read(bucketName, key, versionId, action, objectArn, authorization);}+ void authorizePutObject(String bucketName, String key, RequestAuthorization authorization) {+ authorizeObjectWrite(bucketName, key, "s3:PutObject", authorization);+ }++ void authorizeDeleteObject(String bucketName, String key, String versionId, RequestAuthorization authorization) {+ String action = versionId != null ? "s3:DeleteObjectVersion" : "s3:DeleteObject";+ authorizeObjectWrite(bucketName, key, action, authorization);+ }++ void authorizeObjectWrite(String bucketName, String key, String action, RequestAuthorization authorization) {+ if (!enforceAuth) {+ return;+ }++ authorizeSignedRequest(authorization);+ RequestAuthorization requestAuthorization = authorization != null+ ? authorization+ : RequestAuthorization.unsigned();+ if (requestAuthorization.signed()) {+ return;+ }++ Bucket bucket = bucketStore.get(bucketName)+ .orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));++ String objectArn = S3PublicAccessEvaluator.objectArn(bucketName, key);+ S3PublicAccessEvaluator.PublicAccessDecision policyDecision =+ S3PublicAccessEvaluator.publicPolicyDecision(objectMapper, bucket.getPolicy(), action, objectArn);+ if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.DENY) {+ throw new AwsException("AccessDenied", "Access Denied", 403);+ }+ if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.ALLOW) {+ return;+ }+ if (isObjectCreationAction(action) && !readableObjectExists(bucketName, key)+ && publicBucketAclAllowsWrite(bucket)) {+ return;+ }++ throw new AwsException("AccessDenied", "Access Denied", 403);+ }++ /**+ * Checks only credential validity, not per-resource authorization. Batch callers use this to+ * fail the whole request on a bad access key, rather than the same InvalidAccessKeyId+ * surfacing as a per-resource error on every item.+ */+ void authorizeSignedRequest(RequestAuthorization authorization) {+ if (!enforceAuth) {+ return;+ }+ RequestAuthorization requestAuthorization = authorization != null+ ? authorization+ : RequestAuthorization.unsigned();+ if (requestAuthorization.signed() && !isKnownAccessKey(requestAuthorization.accessKeyId())) {+ throw new AwsException("InvalidAccessKeyId",+ "The AWS Access Key Id you provided does not exist in our records.", 403);+ }+ }++ private boolean publicBucketAclAllowsWrite(Bucket bucket) {+ return Optional.ofNullable(bucket.getAcl())+ .map(S3AclPublicAccessEvaluator::aclAllowsPublicWrite)+ .orElse(false);+ }+boolean isAuthEnforced() {return enforceAuth;}@@ -646,6 +712,16 @@ public class S3Service implements Resettable {return "s3:GetObject".equals(action) || "s3:GetObjectVersion".equals(action);}+ /**+ * A bucket ACL WRITE grant to a non-owner only authorizes creating a new object; per AWS's+ * ACL documentation it "denies non-owners the ability to overwrite or delete existing+ * objects." Floci has no per-object ownership model, so this is approximated as: only+ * PutObject on a key that doesn't exist yet counts as creation.+ */+ private static boolean isObjectCreationAction(String action) {+ return "s3:PutObject".equals(action);+ }+private static boolean isUnsignedRequest(RequestAuthorization authorization) {return authorization == null || !authorization.signed();}diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.javaindex 1461475e7c..f10308bc63 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java@@ -23,6 +23,7 @@ import javax.crypto.spec.SecretKeySpec;import static io.restassured.RestAssured.given;import static org.hamcrest.Matchers.containsString;import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.not;@QuarkusTest@TestProfile(S3AuthEnforcementIntegrationTest.S3AuthProfile.class)@@ -37,12 +38,22 @@ class S3AuthEnforcementIntegrationTest {private static final String DENY_BUCKET = "auth-deny-bucket";private static final String GET_ONLY_BUCKET = "auth-get-only-bucket";private static final String VERSION_BUCKET = "auth-version-bucket";+ private static final String WRITE_BUCKET = "auth-write-bucket";+ private static final String PUBLIC_WRITE_BUCKET = "auth-public-write-bucket";+ private static final String PUBLIC_WRITE_ACL_BUCKET = "auth-public-write-acl-bucket";+ private static final String DENY_WRITE_ACL_BUCKET = "auth-deny-write-acl-bucket";+ private static final String DELETE_VERSION_BUCKET = "auth-delete-version-bucket";+ private static final String BYPASS_BUCKET = "auth-bypass-governance-bucket";+ private static final String BYPASS_KEY = "bypass-target.txt";+ private static final String CONDITIONAL_DENY_ACL_BUCKET = "auth-conditional-deny-acl-bucket";private static final String PUBLIC_KEY = "public.txt";private static final String PRIVATE_KEY = "private.txt";private static final String ERROR_KEY = "error.html";private static final String ACL_KEY = "acl-list.txt";private static final String DENY_KEY = "deny.txt";private static final String VERSION_KEY = "versioned.txt";+ private static final String WRITE_KEY = "signed.txt";+ private static final String ANON_WRITE_KEY = "anon.txt";private static final String SIGNING_TIMESTAMP = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC).format(Instant.now());@@ -58,6 +69,7 @@ class S3AuthEnforcementIntegrationTest {given().when().put("/" + PRIVATE_BUCKET).then().statusCode(200);given()+ .header("Authorization", LOCAL_AUTH_HEADER).body("public body").when().put("/" + PUBLIC_BUCKET + "/" + PUBLIC_KEY)@@ -65,6 +77,7 @@ class S3AuthEnforcementIntegrationTest {.statusCode(200);given()+ .header("Authorization", LOCAL_AUTH_HEADER).body("private body").when().put("/" + PRIVATE_BUCKET + "/" + PRIVATE_KEY)@@ -229,6 +242,7 @@ class S3AuthEnforcementIntegrationTest {given().when().put("/" + WEBSITE_BUCKET).then().statusCode(200);given()+ .header("Authorization", LOCAL_AUTH_HEADER).contentType("text/html").body("<html>index</html>").when()@@ -275,6 +289,7 @@ class S3AuthEnforcementIntegrationTest {given().when().put("/" + WEBSITE_ERROR_BUCKET).then().statusCode(200);given()+ .header("Authorization", LOCAL_AUTH_HEADER).contentType("text/html").body("<html>private index</html>").when()@@ -283,6 +298,7 @@ class S3AuthEnforcementIntegrationTest {.statusCode(200);given()+ .header("Authorization", LOCAL_AUTH_HEADER).contentType("text/html").body("<html>denied</html>").when()@@ -323,6 +339,7 @@ class S3AuthEnforcementIntegrationTest {given().when().put("/" + BUCKET_ACL_BUCKET).then().statusCode(200);given()+ .header("Authorization", LOCAL_AUTH_HEADER).body("listed").when().put("/" + BUCKET_ACL_BUCKET + "/" + ACL_KEY)@@ -351,6 +368,7 @@ class S3AuthEnforcementIntegrationTest {given().when().put("/" + DENY_BUCKET).then().statusCode(200);given()+ .header("Authorization", LOCAL_AUTH_HEADER).header("x-amz-acl", "public-read").body("denied").when()@@ -499,6 +517,7 @@ class S3AuthEnforcementIntegrationTest {.statusCode(200);String versionId = given()+ .header("Authorization", LOCAL_AUTH_HEADER).body("versioned body").when().put("/" + VERSION_BUCKET + "/" + VERSION_KEY)@@ -652,6 +671,651 @@ class S3AuthEnforcementIntegrationTest {.body(containsString("AuthorizationQueryParametersError"));}+ @Test+ @Order(28)+ void unsignedRequestCannotPutObject() {+ given().when().put("/" + WRITE_BUCKET).then().statusCode(200);++ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .body("signed body")+ .when()+ .put("/" + WRITE_BUCKET + "/" + WRITE_KEY)+ .then()+ .statusCode(200);++ given()+ .body("injected-by-anonymous")+ .when()+ .put("/" + WRITE_BUCKET + "/" + ANON_WRITE_KEY)+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));++ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .when()+ .get("/" + WRITE_BUCKET + "/" + ANON_WRITE_KEY)+ .then()+ .statusCode(404);+ }++ @Test+ @Order(29)+ void unsignedRequestCannotDeleteObject() {+ given()+ .when()+ .delete("/" + WRITE_BUCKET + "/" + WRITE_KEY)+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));++ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .when()+ .get("/" + WRITE_BUCKET + "/" + WRITE_KEY)+ .then()+ .statusCode(200)+ .body(equalTo("signed body"));++ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .when()+ .delete("/" + WRITE_BUCKET + "/" + WRITE_KEY)+ .then()+ .statusCode(204);+ }++ @Test+ @Order(30)+ void signedRequestWithBadAccessKeyCannotWriteObject() {+ given()+ .header("Authorization", BAD_AUTH_HEADER)+ .body("bad key body")+ .when()+ .put("/" + WRITE_BUCKET + "/" + ANON_WRITE_KEY)+ .then()+ .statusCode(403)+ .body(containsString("InvalidAccessKeyId"));++ given()+ .header("Authorization", BAD_AUTH_HEADER)+ .when()+ .delete("/" + WRITE_BUCKET + "/" + ANON_WRITE_KEY)+ .then()+ .statusCode(403)+ .body(containsString("InvalidAccessKeyId"));+ }++ @Test+ @Order(31)+ void bucketPolicyCanExplicitlyAllowAnonymousWrite() {+ given().when().put("/" + PUBLIC_WRITE_BUCKET).then().statusCode(200);++ given()+ .contentType("application/json")+ .body(publicObjectActionPolicy(PUBLIC_WRITE_BUCKET, "s3:PutObject"))+ .when()+ .put("/" + PUBLIC_WRITE_BUCKET + "?policy")+ .then()+ .statusCode(200);++ given()+ .body("public write body")+ .when()+ .put("/" + PUBLIC_WRITE_BUCKET + "/" + ANON_WRITE_KEY)+ .then()+ .statusCode(200);++ given()+ .contentType("application/json")+ .body(publicObjectActionPolicy(PUBLIC_WRITE_BUCKET, "s3:DeleteObject"))+ .when()+ .put("/" + PUBLIC_WRITE_BUCKET + "?policy")+ .then()+ .statusCode(200);++ given()+ .when()+ .delete("/" + PUBLIC_WRITE_BUCKET + "/" + ANON_WRITE_KEY)+ .then()+ .statusCode(204);+ }++ @Test+ @Order(32)+ void unsignedRequestCannotWriteObjectSubresources() {+ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .body("subresource body")+ .when()+ .put("/" + WRITE_BUCKET + "/subresource.txt")+ .then()+ .statusCode(200);++ given()+ .contentType("application/xml")+ .body("<Tagging><TagSet><Tag><Key>a</Key><Value>b</Value></Tag></TagSet></Tagging>")+ .when()+ .put("/" + WRITE_BUCKET + "/subresource.txt?tagging")+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));++ given()+ .contentType("application/xml")+ .body("<Retention><Mode>GOVERNANCE</Mode><RetainUntilDate>2099-01-01T00:00:00Z</RetainUntilDate></Retention>")+ .when()+ .put("/" + WRITE_BUCKET + "/subresource.txt?retention")+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));++ given()+ .contentType("application/xml")+ .body("<LegalHold><Status>ON</Status></LegalHold>")+ .when()+ .put("/" + WRITE_BUCKET + "/subresource.txt?legal-hold")+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));++ given()+ .contentType("application/xml")+ .body(publicReadAcl())+ .when()+ .put("/" + WRITE_BUCKET + "/subresource.txt?acl")+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));++ given()+ .when()+ .delete("/" + WRITE_BUCKET + "/subresource.txt?tagging")+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));+ }++ @Test+ @Order(33)+ void unsignedRequestCannotWriteViaMultipartOrRestore() {+ given()+ .when()+ .post("/" + WRITE_BUCKET + "/multipart.txt?uploads")+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));++ String uploadId = given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .when()+ .post("/" + WRITE_BUCKET + "/multipart.txt?uploads")+ .then()+ .statusCode(200)+ .extract().body().xmlPath().getString("InitiateMultipartUploadResult.UploadId");++ given()+ .body("part data")+ .when()+ .put("/" + WRITE_BUCKET + "/multipart.txt?uploadId=" + uploadId + "&partNumber=1")+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));++ String eTag = given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .body("part data")+ .when()+ .put("/" + WRITE_BUCKET + "/multipart.txt?uploadId=" + uploadId + "&partNumber=1")+ .then()+ .statusCode(200)+ .extract().header("ETag");++ given()+ .contentType("application/xml")+ .body(completeMultipartBody(eTag))+ .when()+ .post("/" + WRITE_BUCKET + "/multipart.txt?uploadId=" + uploadId)+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));++ given()+ .when()+ .delete("/" + WRITE_BUCKET + "/multipart.txt?uploadId=" + uploadId)+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));++ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .contentType("application/xml")+ .body(completeMultipartBody(eTag))+ .when()+ .post("/" + WRITE_BUCKET + "/multipart.txt?uploadId=" + uploadId)+ .then()+ .statusCode(200);++ given()+ .contentType("application/xml")+ .body("<RestoreRequest><Days>1</Days></RestoreRequest>")+ .when()+ .post("/" + WRITE_BUCKET + "/multipart.txt?restore")+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));+ }++ @Test+ @Order(34)+ void unsignedRequestCannotCopyObject() {+ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .body("copy source body")+ .when()+ .put("/" + WRITE_BUCKET + "/copy-source.txt")+ .then()+ .statusCode(200);++ given()+ .header("x-amz-copy-source", "/" + WRITE_BUCKET + "/copy-source.txt")+ .when()+ .put("/" + WRITE_BUCKET + "/copy-dest.txt")+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));++ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .header("x-amz-copy-source", "/" + WRITE_BUCKET + "/copy-source.txt")+ .when()+ .put("/" + WRITE_BUCKET + "/copy-dest.txt")+ .then()+ .statusCode(200);+ }++ @Test+ @Order(35)+ void batchDeleteObjectsDeniesUnauthorizedKeysButAllowsAuthorized() {+ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .body("batch a")+ .when()+ .put("/" + WRITE_BUCKET + "/batch-a.txt")+ .then()+ .statusCode(200);++ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .body("batch b")+ .when()+ .put("/" + WRITE_BUCKET + "/batch-b.txt")+ .then()+ .statusCode(200);++ String deleteXml = """+ <Delete>+ <Object><Key>batch-a.txt</Key></Object>+ <Object><Key>batch-b.txt</Key></Object>+ </Delete>+ """;++ given()+ .contentType("application/xml")+ .body(deleteXml)+ .when()+ .post("/" + WRITE_BUCKET + "?delete")+ .then()+ .statusCode(200)+ .body(containsString("<Code>AccessDenied</Code>"))+ .body(containsString("<Key>batch-a.txt</Key>"))+ .body(containsString("<Key>batch-b.txt</Key>"))+ .body(not(containsString("<Deleted>")));++ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .when()+ .get("/" + WRITE_BUCKET + "/batch-a.txt")+ .then()+ .statusCode(200)+ .body(equalTo("batch a"));++ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .contentType("application/xml")+ .body(deleteXml)+ .when()+ .post("/" + WRITE_BUCKET + "?delete")+ .then()+ .statusCode(200)+ .body(containsString("<Deleted>"))+ .body(not(containsString("AccessDenied")));+ }++ @Test+ @Order(36)+ void batchDeleteObjectsWithUnknownAccessKeyFailsWholeRequest() {+ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .body("bad-key batch a")+ .when()+ .put("/" + WRITE_BUCKET + "/bad-key-batch-a.txt")+ .then()+ .statusCode(200);++ String deleteXml = """+ <Delete>+ <Object><Key>bad-key-batch-a.txt</Key></Object>+ </Delete>+ """;++ given()+ .header("Authorization", BAD_AUTH_HEADER)+ .contentType("application/xml")+ .body(deleteXml)+ .when()+ .post("/" + WRITE_BUCKET + "?delete")+ .then()+ .statusCode(403)+ .body("Error.Code", equalTo("InvalidAccessKeyId"));++ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .when()+ .get("/" + WRITE_BUCKET + "/bad-key-batch-a.txt")+ .then()+ .statusCode(200)+ .body(equalTo("bad-key batch a"));+ }++ @Test+ @Order(37)+ void bucketAclPublicReadWriteAllowsAnonymousCreateButNotOverwriteOrDelete() {+ // Per AWS's ACL docs, a bucket-ACL WRITE grant to a non-owner (like AllUsers) "denies+ // non-owners the ability to overwrite or delete existing objects" -- it only lets them+ // create new ones.+ given().when().put("/" + PUBLIC_WRITE_ACL_BUCKET).then().statusCode(200);++ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .header("x-amz-acl", "public-read-write")+ .when()+ .put("/" + PUBLIC_WRITE_ACL_BUCKET + "?acl")+ .then()+ .statusCode(200);++ given()+ .body("anonymous via public-read-write ACL")+ .when()+ .put("/" + PUBLIC_WRITE_ACL_BUCKET + "/" + ANON_WRITE_KEY)+ .then()+ .statusCode(200);++ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .when()+ .get("/" + PUBLIC_WRITE_ACL_BUCKET + "/" + ANON_WRITE_KEY)+ .then()+ .statusCode(200)+ .body(equalTo("anonymous via public-read-write ACL"));++ given()+ .body("overwrite attempt")+ .when()+ .put("/" + PUBLIC_WRITE_ACL_BUCKET + "/" + ANON_WRITE_KEY)+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));++ given()+ .when()+ .delete("/" + PUBLIC_WRITE_ACL_BUCKET + "/" + ANON_WRITE_KEY)+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));+ }++ @Test+ @Order(38)+ void explicitPolicyDenyOverridesPublicWriteAcl() {+ given().when().put("/" + DENY_WRITE_ACL_BUCKET).then().statusCode(200);++ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .header("x-amz-acl", "public-read-write")+ .when()+ .put("/" + DENY_WRITE_ACL_BUCKET + "?acl")+ .then()+ .statusCode(200);++ given()+ .contentType("application/json")+ .body(denyObjectActionPolicy(DENY_WRITE_ACL_BUCKET, "s3:PutObject"))+ .when()+ .put("/" + DENY_WRITE_ACL_BUCKET + "?policy")+ .then()+ .statusCode(200);++ given()+ .body("should stay denied despite public-read-write ACL")+ .when()+ .put("/" + DENY_WRITE_ACL_BUCKET + "/" + ANON_WRITE_KEY)+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));+ }++ private static String denyObjectActionPolicy(String bucket, String action) {+ return """+ {+ "Version": "2012-10-17",+ "Statement": {+ "Effect": "Deny",+ "Principal": "*",+ "Action": "%s",+ "Resource": "arn:aws:s3:::%s/*"+ }+ }+ """.formatted(action, bucket);+ }++ @Test+ @Order(39)+ void publicWriteAclDoesNotAuthorizeObjectSubresources() {+ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .body("subresource body")+ .when()+ .put("/" + PUBLIC_WRITE_ACL_BUCKET + "/acl-subresource.txt")+ .then()+ .statusCode(200);++ given()+ .contentType("application/xml")+ .body("<Tagging><TagSet><Tag><Key>a</Key><Value>b</Value></Tag></TagSet></Tagging>")+ .when()+ .put("/" + PUBLIC_WRITE_ACL_BUCKET + "/acl-subresource.txt?tagging")+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));++ given()+ .contentType("application/xml")+ .body(publicReadAcl())+ .when()+ .put("/" + PUBLIC_WRITE_ACL_BUCKET + "/acl-subresource.txt?acl")+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));+ }++ @Test+ @Order(40)+ void deleteObjectPolicyGrantDoesNotAuthorizeVersionedDelete() {+ given().when().put("/" + DELETE_VERSION_BUCKET).then().statusCode(200);++ given()+ .contentType("application/xml")+ .body("<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>")+ .when()+ .put("/" + DELETE_VERSION_BUCKET + "?versioning")+ .then()+ .statusCode(200);++ String versionId = given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .body("versioned delete target")+ .when()+ .put("/" + DELETE_VERSION_BUCKET + "/" + VERSION_KEY)+ .then()+ .statusCode(200)+ .extract().header("x-amz-version-id");++ given()+ .contentType("application/json")+ .body(publicObjectActionPolicy(DELETE_VERSION_BUCKET, "s3:DeleteObject"))+ .when()+ .put("/" + DELETE_VERSION_BUCKET + "?policy")+ .then()+ .statusCode(200);++ given()+ .when()+ .delete("/" + DELETE_VERSION_BUCKET + "/" + VERSION_KEY)+ .then()+ .statusCode(204);++ given()+ .when()+ .delete("/" + DELETE_VERSION_BUCKET + "/" + VERSION_KEY + "?versionId=" + versionId)+ .then()+ .statusCode(403)+ .body("Error.Code", equalTo("AccessDenied"));+ }++ @Test+ @Order(41)+ void deleteObjectDoesNotBypassGovernanceRetentionWithoutDistinctPermission() {+ given().when().put("/" + BYPASS_BUCKET).then().statusCode(200);++ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .body("locked candidate")+ .when()+ .put("/" + BYPASS_BUCKET + "/" + BYPASS_KEY)+ .then()+ .statusCode(200);++ given()+ .contentType("application/json")+ .body(publicObjectActionPolicy(BYPASS_BUCKET, "s3:DeleteObject"))+ .when()+ .put("/" + BYPASS_BUCKET + "?policy")+ .then()+ .statusCode(200);++ given()+ .header("x-amz-bypass-governance-retention", "true")+ .when()+ .delete("/" + BYPASS_BUCKET + "/" + BYPASS_KEY)+ .then()+ .statusCode(403)+ .body("Error.Code", equalTo("AccessDenied"));++ given()+ .contentType("application/json")+ .body(deleteAndBypassGovernancePolicy(BYPASS_BUCKET))+ .when()+ .put("/" + BYPASS_BUCKET + "?policy")+ .then()+ .statusCode(200);++ given()+ .header("x-amz-bypass-governance-retention", "true")+ .when()+ .delete("/" + BYPASS_BUCKET + "/" + BYPASS_KEY)+ .then()+ .statusCode(204);+ }++ private static String deleteAndBypassGovernancePolicy(String bucket) {+ return """+ {+ "Version": "2012-10-17",+ "Statement": {+ "Effect": "Allow",+ "Principal": "*",+ "Action": ["s3:DeleteObject", "s3:BypassGovernanceRetention"],+ "Resource": "arn:aws:s3:::%s/*"+ }+ }+ """.formatted(bucket);+ }++ @Test+ @Order(42)+ void conditionalPolicyDenyFailsClosedOverridingPublicWriteAcl() {+ // Floci has no request context to evaluate a Condition against, so a conditional Deny+ // is treated as applying (fail closed) -- consistent with S3PublicAccessEvaluatorTest's+ // conditionalDenyFailsClosedAndOverridesAllow, this must also override the ACL fallback.+ given().when().put("/" + CONDITIONAL_DENY_ACL_BUCKET).then().statusCode(200);++ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .header("x-amz-acl", "public-read-write")+ .when()+ .put("/" + CONDITIONAL_DENY_ACL_BUCKET + "?acl")+ .then()+ .statusCode(200);++ given()+ .contentType("application/json")+ .body(conditionalDenyObjectActionPolicy(CONDITIONAL_DENY_ACL_BUCKET, "s3:PutObject"))+ .when()+ .put("/" + CONDITIONAL_DENY_ACL_BUCKET + "?policy")+ .then()+ .statusCode(200);++ given()+ .body("should stay denied despite the public-read-write ACL")+ .when()+ .put("/" + CONDITIONAL_DENY_ACL_BUCKET + "/" + ANON_WRITE_KEY)+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));+ }++ private static String conditionalDenyObjectActionPolicy(String bucket, String action) {+ return """+ {+ "Version": "2012-10-17",+ "Statement": {+ "Effect": "Deny",+ "Principal": "*",+ "Action": "%s",+ "Resource": "arn:aws:s3:::%s/*",+ "Condition": {+ "StringEquals": {+ "aws:SourceIp": "203.0.113.0/24"+ }+ }+ }+ }+ """.formatted(action, bucket);+ }++ private static String completeMultipartBody(String eTag) {+ return """+ <CompleteMultipartUpload>+ <Part>+ <PartNumber>1</PartNumber>+ <ETag>%s</ETag>+ </Part>+ </CompleteMultipartUpload>+ """.formatted(eTag);+ }+private static String publicReadPolicy(String bucket) {return """{