Light, fluffy, and always free - The AWS Local Emulator alternative
fix(iam): scope managed policy attachment counts (#4213)
XuJianc15af65bf043
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.javaindex e63635ec73..0ec9c4552b 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java@@ -901,17 +901,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider {}public IamPolicy getPolicy(String policyArn) {- // AWS-managed policies (arn:aws:iam::aws:policy/...) are global — not owned by any- // account — so they are served from the catalog rather than the account-partitioned- // store, which would otherwise make them visible only to the default account.- if (policyArn != null && policyArn.startsWith(AwsManagedPolicies.ARN_PREFIX)) {- IamPolicy managed = awsManagedPolicies.get(policyArn);- if (managed != null) {- return managed;- }- throw new AwsException("NoSuchEntity", "Policy " + policyArn + " does not exist.", 404);+ IamPolicy policy = requirePolicy(policyArn);+ if (policyArn.startsWith(AwsManagedPolicies.ARN_PREFIX)) {+ return managedPolicySnapshot(policy, managedPolicyAttachmentCount(policyArn));}- return policies.get(policyArn)+ return policy;+ }++ private IamPolicy requirePolicy(String policyArn) {+ return resolvePolicy(policyArn).orElseThrow(() -> new AwsException("NoSuchEntity","Policy " + policyArn + " does not exist.", 404));}@@ -925,11 +923,75 @@ public class IamService implements SessionAccountLookup, ResourceProvider {*/private Optional<IamPolicy> resolvePolicy(String arn) {if (arn != null && arn.startsWith(AwsManagedPolicies.ARN_PREFIX)) {+ // Authorization and ListAttached* need policy documents or names, not attachment counts.return Optional.ofNullable(awsManagedPolicies.get(arn));}return policies.get(arn);}+ private int managedPolicyAttachmentCount(String policyArn) {+ return managedPolicyAttachmentCounts().getOrDefault(policyArn, 0);+ }++ private Map<String, Integer> managedPolicyAttachmentCounts() {+ Map<String, Integer> counts = new LinkedHashMap<>();+ users.scan(k -> true).forEach(user -> tallyManagedPolicyAttachments(user.getAttachedPolicyArns(), counts));+ groups.scan(k -> true).forEach(group -> tallyManagedPolicyAttachments(group.getAttachedPolicyArns(), counts));+ roles.scan(k -> true).forEach(role -> tallyManagedPolicyAttachments(role.getAttachedPolicyArns(), counts));+ return counts;+ }++ private void tallyManagedPolicyAttachments(List<String> policyArns, Map<String, Integer> counts) {+ for (String policyArn : policyArns) {+ if (policyArn.startsWith(AwsManagedPolicies.ARN_PREFIX)) {+ counts.merge(policyArn, 1, Integer::sum);+ }+ }+ }++ private IamPolicy managedPolicySnapshot(IamPolicy catalogPolicy, int attachmentCount) {+ IamPolicy snapshot = new IamPolicy();+ snapshot.setPolicyId(catalogPolicy.getPolicyId());+ snapshot.setPolicyName(catalogPolicy.getPolicyName());+ snapshot.setPath(catalogPolicy.getPath());+ snapshot.setArn(catalogPolicy.getArn());+ snapshot.setDescription(catalogPolicy.getDescription());+ snapshot.setDefaultVersionId(catalogPolicy.getDefaultVersionId());+ snapshot.setNextVersionNumber(catalogPolicy.getNextVersionNumber());+ snapshot.setCreateDate(catalogPolicy.getCreateDate());+ snapshot.setUpdateDate(catalogPolicy.getUpdateDate());+ snapshot.setTags(new LinkedHashMap<>(catalogPolicy.getTags()));+ Map<String, PolicyVersion> versions = new LinkedHashMap<>();+ synchronized (catalogPolicy.getVersions()) {+ for (Map.Entry<String, PolicyVersion> entry : catalogPolicy.getVersions().entrySet()) {+ PolicyVersion version = entry.getValue();+ versions.put(entry.getKey(), new PolicyVersion(version.getVersionId(), version.getDocument(),+ version.isDefaultVersion(), version.getCreateDate()));+ }+ }+ snapshot.setVersions(versions);+ snapshot.setAttachmentCount(attachmentCount);+ return snapshot;+ }++ private void incrementCustomerManagedPolicyAttachmentCount(IamPolicy policy) {+ if (policy.getArn().startsWith(AwsManagedPolicies.ARN_PREFIX)) {+ return;+ }+ policy.setAttachmentCount(policy.getAttachmentCount() + 1);+ policies.put(policy.getArn(), policy);+ }++ private void decrementCustomerManagedPolicyAttachmentCount(String policyArn) {+ if (policyArn.startsWith(AwsManagedPolicies.ARN_PREFIX)) {+ return;+ }+ policies.get(policyArn).ifPresent(policy -> {+ policy.setAttachmentCount(Math.max(0, policy.getAttachmentCount() - 1));+ policies.put(policyArn, policy);+ });+ }+private void rejectIfAwsManaged(String policyArn) {if (policyArn != null && policyArn.startsWith(AwsManagedPolicies.ARN_PREFIX)) {throw new AwsException("AccessDenied",@@ -957,7 +1019,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {* succeed. Attachments are tracked on the principals, so this scans them for the given ARN.*/public PolicyEntities listEntitiesForPolicy(String policyArn) {- getPolicy(policyArn); // AWS raises NoSuchEntity for an unknown policy ARN; fail fast likewise.+ requirePolicy(policyArn); // AWS raises NoSuchEntity for an unknown policy ARN; fail fast likewise.List<IamRole> attachedRoles = roles.scan(k -> true).stream().filter(r -> r.getAttachedPolicyArns().contains(policyArn)).toList();@@ -998,8 +1060,10 @@ public class IamService implements SessionAccountLookup, ResourceProvider {// AWS-managed policies are global (account-less arn:aws:iam::aws:policy/... ARN), so// every caller sees the full set regardless of the request account — mirroring the// getPolicy fix, and keeping the ListPolicies and GetPolicy read paths consistent.+ Map<String, Integer> attachmentCounts = managedPolicyAttachmentCounts();awsManagedPolicies.values().stream().filter(p -> p.getPath().startsWith(prefix))+ .map(p -> managedPolicySnapshot(p, attachmentCounts.getOrDefault(p.getArn(), 0))).forEach(result::add);}return result;@@ -1109,7 +1173,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {}public PolicyVersion getPolicyVersion(String policyArn, String versionId) {- IamPolicy policy = getPolicy(policyArn);+ IamPolicy policy = requirePolicy(policyArn);PolicyVersion version = policy.getVersions().get(versionId);if (version == null) {throw new AwsException("NoSuchEntity",@@ -1137,7 +1201,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {}public List<PolicyVersion> listPolicyVersions(String policyArn) {- Map<String, PolicyVersion> versions = getPolicy(policyArn).getVersions();+ Map<String, PolicyVersion> versions = requirePolicy(policyArn).getVersions();synchronized (versions) {return new ArrayList<>(versions.values());}@@ -1174,7 +1238,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {}public Map<String, String> listPolicyTags(String policyArn) {- return getPolicy(policyArn).getTags();+ return requirePolicy(policyArn).getTags();}// =========================================================================@@ -1183,12 +1247,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider {public void attachUserPolicy(String userName, String policyArn) {IamUser user = getUser(userName);- IamPolicy policy = getPolicy(policyArn);+ IamPolicy policy = requirePolicy(policyArn);if (!user.getAttachedPolicyArns().contains(policyArn)) {user.getAttachedPolicyArns().add(policyArn);users.put(userName, user);- policy.setAttachmentCount(policy.getAttachmentCount() + 1);- policies.put(policyArn, policy);+ incrementCustomerManagedPolicyAttachmentCount(policy);}}@@ -1199,10 +1262,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {"Policy " + policyArn + " is not attached to user " + userName + ".", 404);}users.put(userName, user);- policies.get(policyArn).ifPresent(p -> {- p.setAttachmentCount(Math.max(0, p.getAttachmentCount() - 1));- policies.put(policyArn, p);- });+ decrementCustomerManagedPolicyAttachmentCount(policyArn);}public List<IamPolicy> listAttachedUserPolicies(String userName, String pathPrefix) {@@ -1218,12 +1278,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider {public void attachGroupPolicy(String groupName, String policyArn) {IamGroup group = getGroup(groupName);- IamPolicy policy = getPolicy(policyArn);+ IamPolicy policy = requirePolicy(policyArn);if (!group.getAttachedPolicyArns().contains(policyArn)) {group.getAttachedPolicyArns().add(policyArn);groups.put(groupName, group);- policy.setAttachmentCount(policy.getAttachmentCount() + 1);- policies.put(policyArn, policy);+ incrementCustomerManagedPolicyAttachmentCount(policy);}}@@ -1234,10 +1293,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {"Policy " + policyArn + " is not attached to group " + groupName + ".", 404);}groups.put(groupName, group);- policies.get(policyArn).ifPresent(p -> {- p.setAttachmentCount(Math.max(0, p.getAttachmentCount() - 1));- policies.put(policyArn, p);- });+ decrementCustomerManagedPolicyAttachmentCount(policyArn);}public List<IamPolicy> listAttachedGroupPolicies(String groupName, String pathPrefix) {@@ -1254,12 +1310,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider {public void attachRolePolicy(String roleName, String policyArn) {IamRole role = getRole(roleName);requireNotServiceLinked(role, roleName);- IamPolicy policy = getPolicy(policyArn);+ IamPolicy policy = requirePolicy(policyArn);if (!role.getAttachedPolicyArns().contains(policyArn)) {role.getAttachedPolicyArns().add(policyArn);roles.put(roleName, role);- policy.setAttachmentCount(policy.getAttachmentCount() + 1);- policies.put(policyArn, policy);+ incrementCustomerManagedPolicyAttachmentCount(policy);}}@@ -1271,10 +1326,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {"Policy " + policyArn + " is not attached to role " + roleName + ".", 404);}roles.put(roleName, role);- policies.get(policyArn).ifPresent(p -> {- p.setAttachmentCount(Math.max(0, p.getAttachmentCount() - 1));- policies.put(policyArn, p);- });+ decrementCustomerManagedPolicyAttachmentCount(policyArn);}public List<IamPolicy> listAttachedRolePolicies(String roleName, String pathPrefix) {@@ -2508,7 +2560,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {// =========================================================================public void putUserPermissionsBoundary(String userName, String permissionsBoundaryArn) {- getPolicy(permissionsBoundaryArn); // validate policy exists+ requirePolicy(permissionsBoundaryArn); // validate policy existsIamUser user = getUser(userName);user.setPermissionsBoundaryArn(permissionsBoundaryArn);users.put(userName, user);@@ -2529,7 +2581,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {public void putRolePermissionsBoundary(String roleName, String permissionsBoundaryArn) {IamRole role = getRole(roleName);requireNotServiceLinked(role, roleName);- getPolicy(permissionsBoundaryArn); // validate policy exists+ requirePolicy(permissionsBoundaryArn); // validate policy existsrole.setPermissionsBoundaryArn(permissionsBoundaryArn);roles.put(roleName, role);LOG.infov("Set permissions boundary for role {0}: {1}", roleName, permissionsBoundaryArn);diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyAccountScopeTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyAccountScopeTest.javaindex f045ae0476..a30f07ebd8 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyAccountScopeTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyAccountScopeTest.java@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.RequestContext;import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.services.iam.model.AccessKey;import io.github.hectorvent.floci.services.iam.model.CallerContext;import io.github.hectorvent.floci.services.iam.model.IamGroup;import io.github.hectorvent.floci.services.iam.model.IamPolicy;@@ -16,13 +17,19 @@ import org.junit.jupiter.api.Test;import java.util.List;import java.util.Map;+import java.util.concurrent.atomic.AtomicReference;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotNull;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.clearInvocations;import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.spy;+import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;/**@@ -49,6 +56,15 @@ class IamManagedPolicyAccountScopeTest {return inst;}+ @SuppressWarnings("unchecked")+ private static Instance<RequestContext> requestContextFor(AtomicReference<String> accountId) {+ RequestContext rc = mock(RequestContext.class);+ when(rc.getAccountId()).thenAnswer(invocation -> accountId.get());+ Instance<RequestContext> inst = mock(Instance.class);+ when(inst.get()).thenReturn(rc);+ return inst;+ }+@Testvoid managedPolicyResolvesFromAnyAccountWhileCustomerPolicyStaysScoped() {// The policies store sees the current request as account 111..., default is 000...@@ -307,6 +323,105 @@ class IamManagedPolicyAccountScopeTest {assertEquals(IamPolicyEvaluator.Decision.DENY,evaluator.evaluate(caller, List.of(), "s3:GetObject", "arn:aws:s3:::private-bucket/key", Map.of()));}++ @Test+ void managedPolicyAuthorizationDoesNotScanPrincipalsForAttachmentCounts() {+ InMemoryStorage<String, IamUser> users = spy(new InMemoryStorage<>());+ InMemoryStorage<String, IamGroup> groups = spy(new InMemoryStorage<>());+ InMemoryStorage<String, IamRole> roles = spy(new InMemoryStorage<>());+ IamService service = new IamService(+ users, groups, roles, new InMemoryStorage<>(),+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ new RegionResolver("us-east-1", DEFAULT_ACCT));+ String managedArn = AwsManagedPolicies.ARN_PREFIX + "/service-role/AWSLambdaBasicExecutionRole";+ String boundaryArn = AwsManagedPolicies.ARN_PREFIX + "/PowerUserAccess";++ service.createUser("auth-user", "/");+ service.createGroup("auth-group", "/");+ IamRole role = service.createRole("auth-role", "/", "{}", null, 0, null);+ service.addUserToGroup("auth-group", "auth-user");+ service.attachUserPolicy("auth-user", managedArn);+ service.attachGroupPolicy("auth-group", boundaryArn);+ service.attachRolePolicy("auth-role", managedArn);+ service.putUserPermissionsBoundary("auth-user", boundaryArn);+ service.putRolePermissionsBoundary("auth-role", boundaryArn);+ AccessKey accessKey = service.createAccessKey("auth-user");+ clearInvocations(users, groups, roles);++ CallerContext userContext = service.resolveCallerContext(accessKey.getAccessKeyId());+ CallerContext roleContext = service.resolvePrincipalContext(role.getArn());++ assertNotNull(userContext);+ assertEquals(2, userContext.identityPolicies().size());+ assertTrue(userContext.identityPolicies().stream()+ .anyMatch(document -> document.contains("logs:CreateLogGroup")));+ assertTrue(userContext.boundaryPolicyDocument().contains("NotAction"));+ assertEquals(1, roleContext.identityPolicies().size());+ assertTrue(roleContext.identityPolicies().get(0).contains("logs:CreateLogGroup"));+ assertTrue(roleContext.boundaryPolicyDocument().contains("NotAction"));+ verify(users, never()).scan(any());+ verify(groups, never()).scan(any());+ verify(roles, never()).scan(any());+ }++ @Test+ void managedPolicyAttachmentCountIsScopedToTheCurrentAccount() {+ AtomicReference<String> accountId = new AtomicReference<>(REQUEST_ACCT);+ Instance<RequestContext> ctx = requestContextFor(accountId);+ AccountAwareStorageBackend<IamUser> users = new AccountAwareStorageBackend<>(+ new InMemoryStorage<>(), ctx, DEFAULT_ACCT);+ AccountAwareStorageBackend<IamGroup> groups = new AccountAwareStorageBackend<>(+ new InMemoryStorage<>(), ctx, DEFAULT_ACCT);+ AccountAwareStorageBackend<IamRole> roles = new AccountAwareStorageBackend<>(+ new InMemoryStorage<>(), ctx, DEFAULT_ACCT);+ AccountAwareStorageBackend<IamPolicy> policies = new AccountAwareStorageBackend<>(+ new InMemoryStorage<>(), ctx, DEFAULT_ACCT);+ IamService service = new IamService(+ users, groups, roles, policies,+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ new RegionResolver("us-east-1", DEFAULT_ACCT));+ String managedArn = AwsManagedPolicies.ARN_PREFIX + "/AdministratorAccess";++ service.createUser("account-a-user", "/");+ service.createGroup("account-a-group", "/");+ service.createRole("account-a-role", "/", "{}", null, 0, null);+ service.attachUserPolicy("account-a-user", managedArn);+ service.attachGroupPolicy("account-a-group", managedArn);+ service.attachRolePolicy("account-a-role", managedArn);++ assertEquals(3, service.getPolicy(managedArn).getAttachmentCount());+ assertEquals(3, managedPolicyFromList(service, managedArn).getAttachmentCount());+ assertEquals(managedArn, service.listAttachedUserPolicies("account-a-user", null).get(0).getArn());+ assertEquals(managedArn, service.listAttachedGroupPolicies("account-a-group", null).get(0).getArn());+ assertEquals(managedArn, service.listAttachedRolePolicies("account-a-role", null).get(0).getArn());++ accountId.set(OTHER_ACCT);+ assertEquals(0, service.getPolicy(managedArn).getAttachmentCount());+ assertEquals(0, managedPolicyFromList(service, managedArn).getAttachmentCount());+ service.createUser("account-b-user", "/");+ service.attachUserPolicy("account-b-user", managedArn);+ assertEquals(1, service.getPolicy(managedArn).getAttachmentCount());++ accountId.set(REQUEST_ACCT);+ assertEquals(3, service.getPolicy(managedArn).getAttachmentCount());+ service.detachUserPolicy("account-a-user", managedArn);+ service.detachGroupPolicy("account-a-group", managedArn);+ service.detachRolePolicy("account-a-role", managedArn);+ assertEquals(0, service.getPolicy(managedArn).getAttachmentCount());++ accountId.set(OTHER_ACCT);+ assertEquals(1, service.getPolicy(managedArn).getAttachmentCount());+ service.detachUserPolicy("account-b-user", managedArn);+ assertEquals(0, service.getPolicy(managedArn).getAttachmentCount());+ }++ private static IamPolicy managedPolicyFromList(IamService service, String managedArn) {+ return service.listPolicies("AWS", null).stream()+ .filter(policy -> managedArn.equals(policy.getArn()))+ .findFirst()+ .orElseThrow();+ }+/*** The alias is the only IAM entity keyed by a constant rather than a caller-supplied name, so* every account shares one storage key and the separation rests entirely ondiff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyAttachmentCountIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyAttachmentCountIntegrationTest.javanew file mode 100644index 0000000000..86501e0de8--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyAttachmentCountIntegrationTest.java@@ -0,0 +1,126 @@+package io.github.hectorvent.floci.services.iam;++import io.github.hectorvent.floci.core.common.XmlParser;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.response.Response;+import org.junit.jupiter.api.Test;++import java.util.List;+import java.util.Map;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.junit.jupiter.api.Assertions.assertEquals;++@QuarkusTest+class IamManagedPolicyAttachmentCountIntegrationTest {++ private static final String FIRST_ACCOUNT = "730000000421";+ private static final String SECOND_ACCOUNT = "730000000422";+ private static final String POLICY_NAME = "AmazonS3ReadOnlyAccess";+ private static final String POLICY_ARN = "arn:aws:iam::aws:policy/" + POLICY_NAME;+ private static final String TRUST_POLICY = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",+ "Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}+ """;++ @Test+ void managedPolicyCountsFollowAttachmentsWithinEachAccount() {+ String name = "attachment-count-" + Long.toString(System.nanoTime(), 36);+ try {+ for (String accountId : List.of(FIRST_ACCOUNT, SECOND_ACCOUNT)) {+ iam(accountId, "CreateUser", Map.of("UserName", name)).then().statusCode(200)+ .body("CreateUserResponse.CreateUserResult.User.Arn",+ equalTo("arn:aws:iam::" + accountId + ":user/" + name));+ iam(accountId, "CreateGroup", Map.of("GroupName", name)).then().statusCode(200);+ iam(accountId, "CreateRole", Map.of("RoleName", name,+ "AssumeRolePolicyDocument", TRUST_POLICY)).then().statusCode(200);+ }+ assertCounts(0, 0);++ changeAttachment(FIRST_ACCOUNT, "Attach", "User", name);+ changeAttachment(FIRST_ACCOUNT, "Attach", "User", name);+ assertCounts(1, 0);+ changeAttachment(FIRST_ACCOUNT, "Attach", "Group", name);+ assertCounts(2, 0);+ changeAttachment(FIRST_ACCOUNT, "Attach", "Role", name);+ assertCounts(3, 0);++ changeAttachment(SECOND_ACCOUNT, "Attach", "User", name);+ assertCounts(3, 1);+ for (String entityType : List.of("User", "Group", "Role")) {+ assertAttachedPolicy(FIRST_ACCOUNT, entityType, name);+ }+ assertAttachedPolicy(SECOND_ACCOUNT, "User", name);++ changeAttachment(FIRST_ACCOUNT, "Detach", "User", name);+ assertCounts(2, 1);+ changeAttachment(FIRST_ACCOUNT, "Detach", "Group", name);+ assertCounts(1, 1);+ changeAttachment(FIRST_ACCOUNT, "Detach", "Role", name);+ assertCounts(0, 1);+ changeAttachment(SECOND_ACCOUNT, "Detach", "User", name);+ assertCounts(0, 0);+ } finally {+ for (String accountId : List.of(FIRST_ACCOUNT, SECOND_ACCOUNT)) {+ for (String entityType : List.of("User", "Group", "Role")) {+ cleanup(accountId, "Detach" + entityType + "Policy",+ Map.of(entityType + "Name", name, "PolicyArn", POLICY_ARN));+ cleanup(accountId, "Delete" + entityType, Map.of(entityType + "Name", name));+ }+ }+ }+ }++ private void assertCounts(int firstAccountCount, int secondAccountCount) {+ assertCount(FIRST_ACCOUNT, firstAccountCount);+ assertCount(SECOND_ACCOUNT, secondAccountCount);+ }++ private void assertCount(String accountId, int expectedCount) {+ iam(accountId, "GetPolicy", Map.of("PolicyArn", POLICY_ARN)).then().statusCode(200)+ .body("GetPolicyResponse.GetPolicyResult.Policy.AttachmentCount",+ equalTo(Integer.toString(expectedCount)));+ iam(accountId, "ListPolicies", Map.of("Scope", "AWS")).then().statusCode(200)+ .body("ListPoliciesResponse.ListPoliciesResult.Policies.member.find { it.Arn == '"+ + POLICY_ARN + "' }.AttachmentCount",+ equalTo(Integer.toString(expectedCount)));+ }++ private void changeAttachment(String accountId, String action, String entityType, String name) {+ iam(accountId, action + entityType + "Policy",+ Map.of(entityType + "Name", name, "PolicyArn", POLICY_ARN)).then().statusCode(200);+ }++ private void assertAttachedPolicy(String accountId, String entityType, String name) {+ String action = "ListAttached" + entityType + "Policies";+ String result = action + "Response." + action + "Result.AttachedPolicies.member";+ String response = iam(accountId, action, Map.of(entityType + "Name", name)).then().statusCode(200)+ .body(result + ".size()", equalTo(1))+ .body(result + ".PolicyName", equalTo(POLICY_NAME))+ .body(result + ".PolicyArn", equalTo(POLICY_ARN))+ .extract().asString();+ assertEquals(List.of("PolicyName", "PolicyArn"), XmlParser.childElementNames(response, "member"));+ }++ private void cleanup(String accountId, String action, Map<String, String> parameters) {+ Response response = iam(accountId, action, parameters);+ if (response.statusCode() == 404) {+ // Creation may have failed before this principal existed.+ response.then().body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));+ } else {+ response.then().statusCode(200);+ }+ }++ private Response iam(String accountId, String action, Map<String, String> parameters) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + accountId+ + "/20260923/us-east-1/iam/aws4_request")+ .formParam("Action", action)+ .formParam("Version", "2010-05-08")+ .formParams(parameters)+ .when().post("/");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyCatalogTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyCatalogTest.javaindex f23ff91290..1f5b4d41ac 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyCatalogTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyCatalogTest.java@@ -141,6 +141,25 @@ class IamManagedPolicyCatalogTest {assertTrue(fetched.isDefaultVersion());}+ @Test+ void managedPolicySnapshotsDoNotShareMutableCatalogState() {+ String arn = "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess";+ IamPolicy fetched = iamService.getPolicy(arn);+ String originalDocument = fetched.getDefaultDocument();++ fetched.getTags().put("tampered", "true");+ fetched.getVersions().get("v3").setDocument("{}");+ fetched.getVersions().put("v99", new PolicyVersion("v99", "{}", false));++ IamPolicy listed = iamService.listPolicies("AWS", null).stream()+ .filter(policy -> arn.equals(policy.getArn()))+ .findFirst()+ .orElseThrow();+ assertFalse(listed.getTags().containsKey("tampered"));+ assertEquals(1, listed.getVersions().size());+ assertEquals(originalDocument, listed.getVersions().get("v3").getDocument());+ }+/*** The dataset only carries each policy's current document, so a superseded version cannot* be served. Answering {@code NoSuchEntity} matches what AWS returns for a version it has