Light, fluffy, and always free - The AWS Local Emulator alternative
fix(s3): report the owner and ACL grantees as a canonical user id (#6549)
Matheus Oliveira56196fec1c58
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3Test.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3Test.javaindex 32ed165a4a..a4c441ac44 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3Test.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3Test.java@@ -5,6 +5,7 @@ import software.amazon.awssdk.core.ResponseBytes;import software.amazon.awssdk.core.ResponseInputStream;import software.amazon.awssdk.core.sync.RequestBody;import software.amazon.awssdk.services.s3.S3Client;+import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest;import software.amazon.awssdk.services.s3.model.BucketLocationConstraint;import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload;@@ -21,10 +22,14 @@ import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;import software.amazon.awssdk.services.s3.model.DeleteObjectTaggingRequest;import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest;import software.amazon.awssdk.services.s3.model.DeleteObjectsResponse;+import software.amazon.awssdk.services.s3.model.GetBucketAclRequest;+import software.amazon.awssdk.services.s3.model.GetBucketAclResponse;import software.amazon.awssdk.services.s3.model.GetBucketLocationRequest;import software.amazon.awssdk.services.s3.model.GetBucketLocationResponse;import software.amazon.awssdk.services.s3.model.GetBucketTaggingRequest;import software.amazon.awssdk.services.s3.model.GetBucketTaggingResponse;+import software.amazon.awssdk.services.s3.model.GetObjectAclRequest;+import software.amazon.awssdk.services.s3.model.GetObjectAclResponse;import software.amazon.awssdk.services.s3.model.GetObjectRequest;import software.amazon.awssdk.services.s3.model.GetObjectResponse;import software.amazon.awssdk.services.s3.model.GetObjectTaggingRequest;@@ -36,14 +41,18 @@ import software.amazon.awssdk.services.s3.model.HeadObjectResponse;import software.amazon.awssdk.services.s3.model.ListBucketsResponse;import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;+import software.amazon.awssdk.services.s3.model.ListPartsRequest;+import software.amazon.awssdk.services.s3.model.ListPartsResponse;import software.amazon.awssdk.services.s3.model.NoSuchBucketException;import software.amazon.awssdk.services.s3.model.ObjectIdentifier;+import software.amazon.awssdk.services.s3.model.Permission;import software.amazon.awssdk.services.s3.model.PutBucketTaggingRequest;import software.amazon.awssdk.services.s3.model.PutObjectRequest;import software.amazon.awssdk.services.s3.model.PutObjectResponse;import software.amazon.awssdk.services.s3.model.PutObjectTaggingRequest;import software.amazon.awssdk.services.s3.model.S3Exception;import software.amazon.awssdk.services.s3.model.Tagging;+import software.amazon.awssdk.services.s3.model.Type;import software.amazon.awssdk.services.s3.model.UploadPartRequest;import java.io.ByteArrayOutputStream;@@ -612,6 +621,56 @@ class S3Test {}}+ @Test+ @Order(35)+ void ownerAndGranteesAreTheAccountsCanonicalUserId() {+ // S3 identifies the owner of buckets and objects, and CanonicalUser ACL grantees, by the+ // account's 64-hex canonical user ID, the same value in ListBuckets, both ACLs and the+ // multipart listing. The value itself is opaque on AWS, so the SDK test pins the form+ // and the cross-response identity, not a specific derivation.+ String bucket = TestFixtures.uniqueName("canonical-owner-bucket");+ String key = "owned.txt";+ String multipartKey = "owned.bin";+ s3.createBucket(CreateBucketRequest.builder().bucket(bucket).build());+ try {+ String ownerId = s3.listBuckets().owner().id();+ assertThat(ownerId).matches("[0-9a-f]{64}");++ GetBucketAclResponse bucketAcl = s3.getBucketAcl(+ GetBucketAclRequest.builder().bucket(bucket).build());+ assertThat(bucketAcl.owner().id()).isEqualTo(ownerId);+ assertThat(bucketAcl.grants()).singleElement().satisfies(grant -> {+ assertThat(grant.grantee().id()).isEqualTo(ownerId);+ assertThat(grant.grantee().type()).isEqualTo(Type.CANONICAL_USER);+ assertThat(grant.permission()).isEqualTo(Permission.FULL_CONTROL);+ });++ s3.putObject(PutObjectRequest.builder().bucket(bucket).key(key).build(),+ RequestBody.fromString(CONTENT));+ GetObjectAclResponse objectAcl = s3.getObjectAcl(+ GetObjectAclRequest.builder().bucket(bucket).key(key).build());+ assertThat(objectAcl.owner().id()).isEqualTo(ownerId);+ assertThat(objectAcl.grants()).singleElement().satisfies(grant -> {+ assertThat(grant.grantee().id()).isEqualTo(ownerId);+ assertThat(grant.grantee().type()).isEqualTo(Type.CANONICAL_USER);+ assertThat(grant.permission()).isEqualTo(Permission.FULL_CONTROL);+ });++ String uploadId = s3.createMultipartUpload(CreateMultipartUploadRequest.builder()+ .bucket(bucket).key(multipartKey).build()).uploadId();+ s3.uploadPart(UploadPartRequest.builder().bucket(bucket).key(multipartKey)+ .uploadId(uploadId).partNumber(1).build(), RequestBody.fromString("part"));+ ListPartsResponse parts = s3.listParts(ListPartsRequest.builder()+ .bucket(bucket).key(multipartKey).uploadId(uploadId).build());+ assertThat(parts.initiator().id()).isEqualTo(ownerId);+ assertThat(parts.owner().id()).isEqualTo(ownerId);+ s3.abortMultipartUpload(AbortMultipartUploadRequest.builder()+ .bucket(bucket).key(multipartKey).uploadId(uploadId).build());+ } finally {+ deleteObjectAndBucketQuietly(bucket, key);+ }+ }+private void assertInlineTaggingHeaderRejected(String rawTaggingHeader, int expectedStatus, String expectedErrorCode) {String bucket = TestFixtures.uniqueName("inline-tag-reject");String key = "rejected.txt";@@ -630,12 +689,20 @@ class S3Test {assertThat(s3e.awsErrorDetails().errorCode()).isEqualTo(expectedErrorCode);});} finally {- try {- s3.deleteObject(DeleteObjectRequest.builder().bucket(bucket).key(key).build());- } catch (Exception ignored) {}- try {- s3.deleteBucket(DeleteBucketRequest.builder().bucket(bucket).build());- } catch (Exception ignored) {}+ deleteObjectAndBucketQuietly(bucket, key);+ }+ }++ private void deleteObjectAndBucketQuietly(String bucket, String key) {+ try {+ s3.deleteObject(DeleteObjectRequest.builder().bucket(bucket).key(key).build());+ } catch (Exception ignored) {+ // cleanup only: an already-deleted object must not mask the assertion+ }+ try {+ s3.deleteBucket(DeleteBucketRequest.builder().bucket(bucket).build());+ } catch (Exception ignored) {+ // cleanup only: an already-emptied bucket must not mask the assertion}}}diff --git a/docs/services/iam.md b/docs/services/iam.mdindex 53cac931e0..9ff9e60cc0 100644--- a/docs/services/iam.md+++ b/docs/services/iam.md@@ -1836,7 +1836,7 @@ AWS checks as `dynamodb:GetItem`, is checked item by item, as described underWhen `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` is active, Floci also queries registered `ResourcePolicyProvider` SPI implementations (such as S3 bucket policies) during request authorization:-- Resource policy statements are matched against the caller (`Principal` and `NotPrincipal` clauses), each principal type naming only its own kind of caller, as on AWS: `"*"` matches anyone; `{"AWS": "*"}` matches IAM identities and AWS services; any other `AWS` entry (a user, role, account id or account root) matches IAM identities only, and a role session matches a `Principal` naming its role through the role's own ARN, path included; `{"Service": "<name>"}` matches that service exactly. `{"CanonicalUser": "<id>"}`, which S3 bucket policies accept, names an account by its S3 canonical user ID and matches that account's IAM identities, as an account principal does; Floci's canonical ID for an account is the account id, as its S3 ACLs report it. `{"Service": "*"}`, which AWS does not accept, matches nothing, and `Federated` entries never match an IAM caller.+- Resource policy statements are matched against the caller (`Principal` and `NotPrincipal` clauses), each principal type naming only its own kind of caller, as on AWS: `"*"` matches anyone; `{"AWS": "*"}` matches IAM identities and AWS services; any other `AWS` entry (a user, role, account id or account root) matches IAM identities only, and a role session matches a `Principal` naming its role through the role's own ARN, path included; `{"Service": "<name>"}` matches that service exactly. `{"CanonicalUser": "<id>"}`, which S3 bucket policies accept, names an account by its S3 canonical user ID and matches that account's IAM identities, as an account principal does; Floci derives that ID from the account ID as its SHA-256 hex digest, the 64-hex value its S3 ACLs report, and still accepts the account ID itself for policies written before it derived one. `{"Service": "*"}`, which AWS does not accept, matches nothing, and `Federated` entries never match an IAM caller.- An explicit **Deny** in a resource policy overrides any allows.- A Deny statement's `NotPrincipal` spares an IAM caller only when it names the caller's account as well as the caller itself, the user, role or role session (the account alone for the account root), and never spares a caller that has a permissions boundary attached, as the IAM User Guide's "AWS JSON policy elements: NotPrincipal" describes: without the account, AWS "might deny access to the entire account", and with a boundary it "will always deny". An Allow with `NotPrincipal`, which Access Analyzer warns can grant to anonymous callers, grants everyone it does not name.- In cross-account scenarios or resource-controlled access, an explicit **Allow** in a resource policy grants access to the principal.diff --git a/docs/services/s3.md b/docs/services/s3.mdindex 8653c72ce2..50049bd7be 100644--- a/docs/services/s3.md+++ b/docs/services/s3.md@@ -422,7 +422,7 @@ Bucket policy statements can specify principals using `Principal` or `NotPrincip- **IAM User:** `{"AWS": "arn:aws:iam::<account>:user/<name>"}`.- **IAM Role:** `{"AWS": "arn:aws:iam::<account>:role/<path><name>"}`. A session of the role matches it through the role's own ARN, path included.- **AWS Account:** `{"AWS": "<12-digit-account-id>"}` or `{"AWS": "arn:aws:iam::<account>:root"}` matches any principal belonging to the specified account.-- **Canonical user:** `{"CanonicalUser": "<canonical-id>"}` names an account by its S3 canonical user ID and matches any principal belonging to that account, as an account principal does. Floci's canonical ID for an account is its account id, the owner ID `GetBucketAcl` and `GetObjectAcl` report.+- **Canonical user:** `{"CanonicalUser": "<canonical-id>"}` names an account by its S3 canonical user ID and matches any principal belonging to that account, as an account principal does. Floci derives the canonical ID deterministically from the account ID as its SHA-256 hex digest, a 64-character lowercase hex string, and reports it wherever S3 identifies an owner: the `Owner` of `ListBuckets`, `ListParts` and both ACLs, the `Initiator` of `ListParts`, and every `CanonicalUser` grantee of an ACL Floci generates. The account ID itself still matches, for policies written when Floci reported the account as the canonical ID.- **Service Principal:** `{"Service": "<service>.amazonaws.com"}`.- **NotPrincipal:** Inverts matching so the statement applies to any principal not matching the specified patterns. On a `Deny`, an IAM caller is spared only when the list names its account as well as the caller, and never when it has a permissions boundary attached; see [Resource-based policies](iam.md#resource-based-policies).diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsCanonicalUserId.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsCanonicalUserId.javanew file mode 100644index 0000000000..ba11e25746--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsCanonicalUserId.java@@ -0,0 +1,18 @@+package io.github.hectorvent.floci.core.common;++/**+ * The S3 canonical user ID an account is identified by in bucket and object ownership, ACL+ * grantees and bucket-policy principals: a 64-character lowercase hex string. AWS derives it+ * from the account and never publishes how, so Floci derives its own value as the SHA-256 hex+ * digest of the account ID: the same account answers the same ID across calls, restarts and+ * storage modes, and two accounts never share one.+ */+public final class AwsCanonicalUserId {++ private AwsCanonicalUserId() {+ }++ public static String forAccount(String accountId) {+ return Digests.sha256Hex(accountId);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.javaindex bd80877bd0..2137730f54 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.iam;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.core.common.AwsArnUtils;+import io.github.hectorvent.floci.core.common.AwsCanonicalUserId;import io.github.hectorvent.floci.core.common.AwsServiceNamespaces;import io.github.hectorvent.floci.core.common.CidrCanonicalizer;import io.github.hectorvent.floci.core.common.ServicePrincipals;@@ -1005,9 +1006,10 @@ public class IamPolicyEvaluator {* role session matches the role it assumed through that role's own ARN, path included.* {@code Service} names one service exactly; {@code {"Service": "*"}} is not a form AWS accepts* and matches nothing. {@code CanonicalUser}, which S3 bucket policies accept, names an account- * by its S3 canonical user ID, and matches the IAM identities of that account as an account- * principal does; Floci's canonical ID for an account is the account id, as its S3 ACLs report- * it. {@code Federated} and any other type name callers this evaluator never sees, and so match+ * by its S3 canonical user ID, the 64-hex value S3 reports as owner and ACL grantee, and matches+ * the IAM identities of that account as an account principal does. The account ID itself still+ * matches, for policies written when Floci reported the account as the canonical ID.+ * {@code Federated} and any other type name callers this evaluator never sees, and so match* nothing, rather than being compared with an IAM ARN. An entry naming the caller itself wins* over one naming only its account.*/@@ -1054,7 +1056,8 @@ public class IamPolicyEvaluator {} else if ("CanonicalUser".equalsIgnoreCase(type)) {if (principal.type() == RequestPrincipal.Type.IAM && principal.arn() != null) {String accountId = extractAccountId(principal.arn());- if (accountId != null && patterns.contains(accountId)) {+ if (accountId != null && (patterns.contains(AwsCanonicalUserId.forAccount(accountId))+ || patterns.contains(accountId))) {strongest = PrincipalMatch.ACCOUNT;}}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 0eb988e083..b815a50291 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@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.s3;+import io.github.hectorvent.floci.core.common.AwsCanonicalUserId;import org.jboss.logging.Logger;final class S3AclPublicAccessEvaluator {@@ -55,14 +56,25 @@ final class S3AclPublicAccessEvaluator {}}- static boolean aclGrantsNonOwner(String acl, String ownerId) {+ /**+ * Whether an ACL grants anyone other than the owner account: every grant must name the+ * owner, whose canonical user ID is what generated ACLs carry and whose account ID is+ * accepted for ACLs written before Floci derived one. An ACL with no grants names nobody,+ * so ownership enforcement rejects it too.+ */+ static boolean aclGrantsNonOwner(String acl, String ownerAccount) {if (acl == null || acl.isBlank()) {return false;}try {S3AclPolicy policy = S3AclPolicy.parse(acl);- return policy.grants().isEmpty() || policy.grants().stream()- .anyMatch(grant -> !grant.grantee().isCanonicalUser(ownerId));+ if (policy.grants().isEmpty()) {+ return true;+ }+ String canonicalId = AwsCanonicalUserId.forAccount(ownerAccount);+ return policy.grants().stream()+ .anyMatch(grant -> !grant.grantee().isCanonicalUser(canonicalId)+ && !grant.grantee().isCanonicalUser(ownerAccount));} catch (S3AclPolicy.AclParseException e) {LOG.debugv(e, "Failed to parse S3 ACL for ownership enforcement");return true;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 13c47a4cde..5745a74dc7 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@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.AccountResolver;import io.github.hectorvent.floci.core.common.AwsArnUtils;+import io.github.hectorvent.floci.core.common.AwsCanonicalUserId;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.AwsNamespaces;import io.github.hectorvent.floci.core.common.AwsRegions;@@ -252,7 +253,7 @@ public class S3Controller {.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>").start("ListAllMyBucketsResult", AwsNamespaces.S3).start("Owner")- .elem("ID", regionResolver.getAccountId())+ .elem("ID", AwsCanonicalUserId.forAccount(regionResolver.getAccountId())).elem("DisplayName", S3Service.DEFAULT_OWNER_DISPLAY_NAME).end("Owner").start("Buckets");@@ -1987,11 +1988,11 @@ public class S3Controller {String initiatorAccountId = upload.getInitiatorAccountId() != null? upload.getInitiatorAccountId() : ownerAccountId;xml.start("Initiator")- .elem("ID", initiatorAccountId)+ .elem("ID", AwsCanonicalUserId.forAccount(initiatorAccountId)).elem("DisplayName", S3Service.DEFAULT_OWNER_DISPLAY_NAME).end("Initiator").start("Owner")- .elem("ID", ownerAccountId)+ .elem("ID", AwsCanonicalUserId.forAccount(ownerAccountId)).elem("DisplayName", S3Service.DEFAULT_OWNER_DISPLAY_NAME).end("Owner").elem("StorageClass", upload.getStorageClass());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 caf6f41e38..9e0f718ef9 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@@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.AwsArnShapes;import io.github.hectorvent.floci.core.common.AwsArnUtils;+import io.github.hectorvent.floci.core.common.AwsCanonicalUserId;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.AwsNamespaces;import io.github.hectorvent.floci.core.common.AwsRegions;@@ -6042,12 +6043,21 @@ public class S3Service implements Resettable, ResourceProvider {throw new AwsException("AccessControlListNotSupported", "The bucket does not allow ACLs", 400);}+ /**+ * Whether an {@code x-amz-grant-full-control} header grants the owner alone, which ownership+ * enforcement tolerates. The owner is named by its canonical user ID, the form S3 reports+ * and clients echo back; the account ID form is still accepted for grants written when+ * Floci reported the account itself.+ */private static boolean isOnlyOwnerFullControlGrant(String ownerAccount, String header) {if (isBlank(header)) {return false;}+ String canonicalId = AwsCanonicalUserId.forAccount(ownerAccount);for (String grantee : header.split(",", -1)) {- if (!("id=\"" + ownerAccount + "\"").equals(grantee.trim())) {+ String token = grantee.trim();+ if (!("id=\"" + canonicalId + "\"").equals(token)+ && !("id=\"" + ownerAccount + "\"").equals(token)) {return false;}}@@ -6448,17 +6458,18 @@ public class S3Service implements Resettable, ResourceProvider {LOG.infov("Restored object: {0}/{1} (stub)", bucketName, key);}- private static String defaultAclXml(String id, String displayName) {+ private static String defaultAclXml(String ownerAccount, String displayName) {+ String canonicalId = AwsCanonicalUserId.forAccount(ownerAccount);return new XmlBuilder().start("AccessControlPolicy").start("Owner")- .elem("ID", id)+ .elem("ID", canonicalId).elem("DisplayName", displayName).end("Owner").start("AccessControlList").start("Grant").raw("<Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"CanonicalUser\">")- .elem("ID", id)+ .elem("ID", canonicalId).elem("DisplayName", displayName).raw("</Grantee>").elem("Permission", "FULL_CONTROL")@@ -6688,7 +6699,8 @@ public class S3Service implements Resettable, ResourceProvider {}private static String ownerFullControlGrant(String ownerAccount) {- return canonicalUserGrant(ownerAccount, DEFAULT_OWNER_DISPLAY_NAME, "FULL_CONTROL");+ return canonicalUserGrant(AwsCanonicalUserId.forAccount(ownerAccount),+ DEFAULT_OWNER_DISPLAY_NAME, "FULL_CONTROL");}private static String canonicalUserGrant(String id, String displayName, String permission) {@@ -6718,7 +6730,7 @@ public class S3Service implements Resettable, ResourceProvider {XmlBuilder xml = new XmlBuilder().start("AccessControlPolicy").start("Owner")- .elem("ID", ownerAccount)+ .elem("ID", AwsCanonicalUserId.forAccount(ownerAccount)).elem("DisplayName", DEFAULT_OWNER_DISPLAY_NAME).end("Owner").start("AccessControlList");diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AwsCanonicalUserIdTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AwsCanonicalUserIdTest.javanew file mode 100644index 0000000000..8b53ccb39a--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/core/common/AwsCanonicalUserIdTest.java@@ -0,0 +1,32 @@+package io.github.hectorvent.floci.core.common;++import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * The canonical user ID is the S3 wire identity of an account: 64 lowercase hex characters,+ * stable for the same account and distinct per account, whatever the partition or storage mode.+ */+class AwsCanonicalUserIdTest {++ @Test+ void isSixtyFourLowercaseHexCharacters() {+ assertTrue(AwsCanonicalUserId.forAccount("000000000000").matches("[0-9a-f]{64}"));+ assertTrue(AwsCanonicalUserId.forAccount("123456789012").matches("[0-9a-f]{64}"));+ }++ @Test+ void isStableForTheSameAccount() {+ assertEquals(AwsCanonicalUserId.forAccount("000000000000"),+ AwsCanonicalUserId.forAccount("000000000000"));+ }++ @Test+ void differsPerAccount() {+ assertNotEquals(AwsCanonicalUserId.forAccount("000000000000"),+ AwsCanonicalUserId.forAccount("000000000001"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.javaindex 9ffb173227..a406d7cd16 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.iam;import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.AwsCanonicalUserId;import io.github.hectorvent.floci.core.common.AwsServiceNamespaces;import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccountRelationship;@@ -898,8 +899,11 @@ class IamPolicyEvaluatorTest {@Testvoid aCanonicalUserNamesTheIamIdentitiesOfItsAccount() {// S3 bucket policies can name an account by its canonical user ID (IAM User Guide, "AWS- // account principals"); Floci's canonical ID for an account is the account id.- String canonical = resourcePolicy("Allow", "\"Principal\":{\"CanonicalUser\":\"123456789012\"}");+ // account principals"): the 64-hex value S3 reports as owner, which Floci derives from+ // the account. The account ID itself still matches, for policies written when Floci+ // reported the account as the canonical ID.+ String canonical = resourcePolicy("Allow", "\"Principal\":{\"CanonicalUser\":\""+ + AwsCanonicalUserId.forAccount("123456789012") + "\"}");assertEquals(ResourcePolicyDecision.ALLOW_ACCOUNT,resourceDecision(canonical, RequestPrincipal.iam("arn:aws:iam::123456789012:user/alice")));assertEquals(ResourcePolicyDecision.ALLOW_ACCOUNT, resourceDecision(canonical, RequestPrincipal.roleSession(@@ -911,6 +915,13 @@ class IamPolicyEvaluatorTest {assertEquals(ResourcePolicyDecision.NEUTRAL, resourceDecision(canonical, RequestPrincipal.anonymous()));}+ @Test+ void anAccountWrittenAsTheCanonicalIdStillMatches() {+ String legacy = resourcePolicy("Allow", "\"Principal\":{\"CanonicalUser\":\"123456789012\"}");+ assertEquals(ResourcePolicyDecision.ALLOW_ACCOUNT,+ resourceDecision(legacy, RequestPrincipal.iam("arn:aws:iam::123456789012:user/alice")));+ }+@Testvoid onlyAGrantNamingTheUserExactlyIsDirect() {// A grant names a user directly by its exact ARN, or by "*" with aws:PrincipalArn pinned todiff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluatorTest.javaindex af0f15d8f0..da8707abef 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluatorTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluatorTest.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.s3;+import io.github.hectorvent.floci.core.common.AwsCanonicalUserId;import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.assertFalse;@@ -114,6 +115,39 @@ class S3AclPublicAccessEvaluatorTest {"http://acs.amazonaws.com/groups/s3/LogDelivery", "WRITE"))));}+ @Test+ void ownerCanonicalUserGrantIsNotANonOwnerGrant() {+ String ownerAccount = "000000000000";+ String canonicalId = AwsCanonicalUserId.forAccount(ownerAccount);++ assertFalse(S3AclPublicAccessEvaluator.aclGrantsNonOwner(acl(+ canonicalUserGrant(canonicalId, "FULL_CONTROL")), ownerAccount));+ }++ @Test+ void ownerAccountGrantStillMatchesForAclsWrittenBeforeCanonicalIds() {+ String ownerAccount = "000000000000";++ assertFalse(S3AclPublicAccessEvaluator.aclGrantsNonOwner(acl(+ canonicalUserGrant(ownerAccount, "FULL_CONTROL")), ownerAccount));+ }++ @Test+ void anotherCanonicalUserGrantIsANonOwnerGrant() {+ String ownerAccount = "000000000000";++ assertTrue(S3AclPublicAccessEvaluator.aclGrantsNonOwner(acl(+ canonicalUserGrant(AwsCanonicalUserId.forAccount("111111111111"), "READ")),+ ownerAccount));+ }++ @Test+ void grantlessAclGrantsNonOwner() {+ assertTrue(S3AclPublicAccessEvaluator.aclGrantsNonOwner(+ "<AccessControlPolicy><AccessControlList/></AccessControlPolicy>",+ "000000000000"));+ }+@Testvoid canonicalUserOnlyAclIsNotPublic() {String acl = """@@ -160,4 +194,15 @@ class S3AclPublicAccessEvaluatorTest {</Grant>""".formatted(groupUri, permission);}++ private static String canonicalUserGrant(String id, String permission) {+ return """+ <Grant>+ <Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser">+ <ID>%s</ID>+ </Grantee>+ <Permission>%s</Permission>+ </Grant>+ """.formatted(id, permission);+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3BucketPolicyEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3BucketPolicyEnforcementIntegrationTest.javaindex d2efaf11a7..1fe148565e 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3BucketPolicyEnforcementIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3BucketPolicyEnforcementIntegrationTest.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.s3;+import io.github.hectorvent.floci.core.common.AwsCanonicalUserId;import io.github.hectorvent.floci.testing.EnforcementFixtures;import io.github.hectorvent.floci.testing.PartitionCleanup;import io.github.hectorvent.floci.testing.S3IamEnforcementProfile;@@ -357,8 +358,10 @@ class S3BucketPolicyEnforcementIntegrationTest {@Testvoid aBucketPolicyNamingAnAccountByItsCanonicalIdGrantsThatAccount() {- // A bucket policy can name an account by its S3 canonical user ID (IAM User Guide, "AWS account- // principals"), and Floci's canonical ID for an account is its account id.+ // A bucket policy can name an account by its S3 canonical user ID (IAM User Guide, "AWS+ // account principals"): the 64-hex value S3 reports as owner, which Floci derives from+ // the account. The account ID itself still matches, for policies written when Floci+ // reported the account as the canonical ID.String suffix = UUID.randomUUID().toString().substring(0, 8);String source = "bp-canonical-" + suffix;S3RequestSigner owner = sourceBucketInAccountA(source);@@ -371,6 +374,14 @@ class S3BucketPolicyEnforcementIntegrationTest {allowGetObject(owner, source, "{\"CanonicalUser\":\"" + ACCOUNT_B + "\"}");assertReadAndCopy(reader, source, destination, 200);++ allowGetObject(owner, source,+ "{\"CanonicalUser\":\"" + AwsCanonicalUserId.forAccount(ACCOUNT_B) + "\"}");+ assertReadAndCopy(reader, source, destination, 200);++ allowGetObject(owner, source,+ "{\"CanonicalUser\":\"" + AwsCanonicalUserId.forAccount(ACCOUNT_A) + "\"}");+ assertReadAndCopy(reader, source, destination, 403);}/** Creates a bucket in account A holding {@code o.txt}, and returns its owner, an account-A administrator. */diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3GlobalBucketNamespaceTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3GlobalBucketNamespaceTest.javaindex 568414c451..227771f1e5 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3GlobalBucketNamespaceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3GlobalBucketNamespaceTest.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.s3;+import io.github.hectorvent.floci.core.common.AwsCanonicalUserId;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RequestContext;import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;@@ -351,15 +352,15 @@ class S3GlobalBucketNamespaceTest {String defaultAcl = globalNs.getObjectAcl("shared-metadata-bucket", "object.txt", versionId);- assertTrue(defaultAcl.contains(ACCOUNT_A));- assertFalse(defaultAcl.contains(ACCOUNT_B));+ assertTrue(defaultAcl.contains(AwsCanonicalUserId.forAccount(ACCOUNT_A)));+ assertFalse(defaultAcl.contains(AwsCanonicalUserId.forAccount(ACCOUNT_B)));globalNs.putObjectAcl("shared-metadata-bucket", "object.txt", versionId,"", "public-read", null, null, null, null, null);String storedAcl = globalNs.getObjectAcl("shared-metadata-bucket", "object.txt", versionId);- assertTrue(storedAcl.contains(ACCOUNT_A));- assertFalse(storedAcl.contains(ACCOUNT_B));+ assertTrue(storedAcl.contains(AwsCanonicalUserId.forAccount(ACCOUNT_A)));+ assertFalse(storedAcl.contains(AwsCanonicalUserId.forAccount(ACCOUNT_B)));globalNs.deleteObjectTagging("shared-metadata-bucket", "object.txt");assertTrue(globalNs.getObjectTagging("shared-metadata-bucket", "object.txt").isEmpty());diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3OwnerIdentityIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3OwnerIdentityIntegrationTest.javaindex 8033811879..e57f1decb3 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3OwnerIdentityIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3OwnerIdentityIntegrationTest.java@@ -1,10 +1,12 @@package io.github.hectorvent.floci.services.s3;+import io.github.hectorvent.floci.core.common.AwsCanonicalUserId;import io.quarkus.test.junit.QuarkusTest;import org.junit.jupiter.api.Test;import static io.restassured.RestAssured.given;import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.matchesPattern;import static org.hamcrest.Matchers.not;@QuarkusTest@@ -14,32 +16,93 @@ class S3OwnerIdentityIntegrationTest {private static final String ACCOUNT_TWO = "000000000012";@Test- void listBucketsOwnerMatchesTheCallerAccountAndBucketAcl() {+ void listBucketsOwnerIsTheCallersCanonicalUserId() {String bucket = "owner-identity-list-bucket";createBucket(ACCOUNT_ONE, bucket);+ String canonicalOne = canonical(ACCOUNT_ONE);given().header("Authorization", authorization(ACCOUNT_ONE)).when().get("/").then().statusCode(200)- .body(containsString("<Owner><ID>" + ACCOUNT_ONE + "</ID><DisplayName>floci</DisplayName></Owner>"))+ .body(containsString("<Owner><ID>" + canonicalOne+ + "</ID><DisplayName>floci</DisplayName></Owner>"))+ .body(matchesPattern(".*<Owner><ID>[0-9a-f]{64}</ID>.*")).body(containsString("<Name>" + bucket + "</Name>"));+ given().header("Authorization", authorization(ACCOUNT_TWO))+ .when().get("/")+ .then().statusCode(200)+ .body(containsString("<Owner><ID>" + canonical(ACCOUNT_TWO)+ + "</ID><DisplayName>floci</DisplayName></Owner>"))+ .body(not(containsString("<Owner><ID>" + canonicalOne + "</ID>")))+ .body(not(containsString("<Name>" + bucket + "</Name>")));+ }++ @Test+ void defaultBucketAclNamesTheOwnerByCanonicalUserId() {+ String bucket = "owner-identity-bucket-acl";+ createBucket(ACCOUNT_ONE, bucket);+ String canonicalOne = canonical(ACCOUNT_ONE);+given().header("Authorization", authorization(ACCOUNT_ONE)).when().get("/" + bucket + "?acl").then().statusCode(200)- .body(containsString("<Owner><ID>" + ACCOUNT_ONE + "</ID><DisplayName>floci</DisplayName></Owner>"));+ .body(containsString("<Owner><ID>" + canonicalOne+ + "</ID><DisplayName>floci</DisplayName></Owner>"))+ .body(containsString("xsi:type=\"CanonicalUser\"><ID>" + canonicalOne + "</ID>"))+ .body(not(containsString("<ID>" + ACCOUNT_ONE + "</ID>")));+ }++ @Test+ void defaultObjectAclNamesTheOwnerByCanonicalUserId() {+ String bucket = "owner-identity-object-acl";+ createBucket(ACCOUNT_ONE, bucket);++ given().header("Authorization", authorization(ACCOUNT_ONE))+ .when().put("/" + bucket + "/key.txt")+ .then().statusCode(200);++ String canonicalOne = canonical(ACCOUNT_ONE);+ given().header("Authorization", authorization(ACCOUNT_ONE))+ .when().get("/" + bucket + "/key.txt?acl")+ .then().statusCode(200)+ .body(containsString("<Owner><ID>" + canonicalOne+ + "</ID><DisplayName>floci</DisplayName></Owner>"))+ .body(containsString("xsi:type=\"CanonicalUser\"><ID>" + canonicalOne + "</ID>"))+ .body(not(containsString("<ID>" + ACCOUNT_ONE + "</ID>")));+ }++ @Test+ void cannedObjectAclKeepsOnlyTheOwnerGrantCanonical() {+ String bucket = "owner-identity-canned-acl";+ createBucket(ACCOUNT_TWO, bucket);given().header("Authorization", authorization(ACCOUNT_TWO))- .when().get("/")+ .body("<OwnershipControls><Rule><ObjectOwnership>ObjectWriter</ObjectOwnership></Rule></OwnershipControls>")+ .when().put("/" + bucket + "?ownershipControls")+ .then().statusCode(200);++ given().header("Authorization", authorization(ACCOUNT_TWO))+ .header("x-amz-acl", "public-read")+ .when().put("/" + bucket + "/public.txt")+ .then().statusCode(200);++ String canonicalTwo = canonical(ACCOUNT_TWO);+ given().header("Authorization", authorization(ACCOUNT_TWO))+ .when().get("/" + bucket + "/public.txt?acl").then().statusCode(200)- .body(containsString("<Owner><ID>" + ACCOUNT_TWO + "</ID><DisplayName>floci</DisplayName></Owner>"))- .body(not(containsString("<Name>" + bucket + "</Name>")));+ .body(containsString("<Owner><ID>" + canonicalTwo+ + "</ID><DisplayName>floci</DisplayName></Owner>"))+ .body(containsString("xsi:type=\"CanonicalUser\"><ID>" + canonicalTwo + "</ID>"))+ .body(containsString("<URI>http://acs.amazonaws.com/groups/global/AllUsers</URI>"))+ .body(not(containsString("<ID>" + ACCOUNT_TWO + "</ID>")));}@Test- void listPartsOwnerAndInitiatorUseTheUploadAccount() {+ void listPartsOwnerAndInitiatorUseTheUploadAccountsCanonicalUserId() {String bucket = "owner-identity-parts-bucket";createBucket(ACCOUNT_TWO, bucket);+ String canonicalTwo = canonical(ACCOUNT_TWO);String uploadId = given().header("Authorization", authorization(ACCOUNT_TWO)).when().post("/" + bucket + "/part.bin?uploads")@@ -49,10 +112,11 @@ class S3OwnerIdentityIntegrationTest {given().header("Authorization", authorization(ACCOUNT_TWO)).when().get("/" + bucket + "/part.bin?uploadId=" + uploadId).then().statusCode(200)- .body(containsString("<Initiator><ID>" + ACCOUNT_TWO+ .body(containsString("<Initiator><ID>" + canonicalTwo+ "</ID><DisplayName>floci</DisplayName></Initiator>"))- .body(containsString("<Owner><ID>" + ACCOUNT_TWO- + "</ID><DisplayName>floci</DisplayName></Owner>"));+ .body(containsString("<Owner><ID>" + canonicalTwo+ + "</ID><DisplayName>floci</DisplayName></Owner>"))+ .body(not(containsString("<ID>" + ACCOUNT_TWO + "</ID>")));}@Test@@ -94,10 +158,14 @@ class S3OwnerIdentityIntegrationTest {given().header("Authorization", authorization(ACCOUNT_TWO)).when().get("/" + bucket + "/part.bin?uploadId=" + secondUploadId).then().statusCode(200)- .body(containsString("<Owner><ID>" + ACCOUNT_TWO+ .body(containsString("<Owner><ID>" + canonical(ACCOUNT_TWO)+ "</ID><DisplayName>floci</DisplayName></Owner>"));}+ private static String canonical(String account) {+ return AwsCanonicalUserId.forAccount(account);+ }+private static void createBucket(String account, String bucket) {given().header("Authorization", authorization(account)).when().put("/" + bucket)diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3OwnershipControlsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3OwnershipControlsIntegrationTest.javaindex 1bd53b98eb..4cc2f93fb1 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3OwnershipControlsIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3OwnershipControlsIntegrationTest.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.s3;+import io.github.hectorvent.floci.core.common.AwsCanonicalUserId;import io.quarkus.test.junit.QuarkusTest;import jakarta.inject.Inject;import org.junit.jupiter.api.MethodOrderer;@@ -175,6 +176,10 @@ class S3OwnershipControlsIntegrationTest {given().header("x-amz-grant-full-control", "id=\"000000000000\"").when().post("/" + bucket + "/accepted?uploads").then().statusCode(200).body(containsString("<UploadId>"));+ given().header("x-amz-grant-full-control",+ "id=\"" + AwsCanonicalUserId.forAccount("000000000000") + "\"")+ .when().post("/" + bucket + "/accepted-canonical?uploads")+ .then().statusCode(200).body(containsString("<UploadId>"));}@Test