fix(iam): scope managed policy attachment counts (#4213)

* fix(iam): scope managed policy attachment counts

* fix(iam): keep attachment counting out of policy resolution

* fix(iam): isolate managed policy snapshots

Copy mutable managed-policy state before returning account-scoped snapshots and cover catalog isolation with a regression test.
This commit is contained in:
XuJian authored and GitHub committed 2026-09-23 14:09:02 -04:00
1 parent addee350ba
commit c15af65bf0
4 files changed
+349 -37

No files matched your search

@@ -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;
}
@Test
void 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 on
@@ -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("/");
}
}
@@ -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