fix(iam): enforce user and group inline policy quotas (#5590)

This commit is contained in:
David Phillips authored and GitHub committed 2026-10-13 19:31:32 -04:00
1 parent 04942063a7
commit 1d8f65d231
16 files changed
+1569 -222

No files matched your search

@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.IamRoleCf
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.IamPolicy;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.testutil.IamInlinePolicyMock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
@@ -49,6 +50,7 @@ class CloudFormationIamAttachmentProvisionerTest {
@BeforeEach
void setUp() {
iamService = mock(IamService.class);
IamInlinePolicyMock.configure(iamService);
provisioner = CfnProvisionerFixture.builder()
.iam(iamService)
.objectMapper(mapper)
@@ -414,6 +416,8 @@ class CloudFormationIamAttachmentProvisionerTest {
void inlinePolicyNameChangeFailureRemovesNewNameAndPreservesOldMetadata() {
String previousPolicyName = "previous-inline-policy";
String currentPolicyName = "current-inline-policy";
String previousDocument = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
when(iamService.getRolePolicy("retained-role", previousPolicyName)).thenReturn(previousDocument);
doThrow(new AwsException("NoSuchEntity", "missing user", 404))
.when(iamService).putUserPolicy("missing-user", currentPolicyName, policyDocument());
@@ -433,7 +437,9 @@ class CloudFormationIamAttachmentProvisionerTest {
assertEquals(previousPolicyName, result.getPhysicalId());
assertEquals("retained-role", result.getAttributes().get("InlineRoleTargets"));
verify(iamService).deleteRolePolicy("retained-role", currentPolicyName);
verify(iamService, never()).deleteRolePolicy("retained-role", previousPolicyName);
verify(iamService).deleteRolePolicy("retained-role", previousPolicyName);
verify(iamService).putRolePolicy("retained-role", previousPolicyName, previousDocument);
assertEquals("true", result.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
}
@Test
@@ -0,0 +1,88 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.IamService.InlinePolicyChange;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doCallRealMethod;
@QuarkusTest
class CloudFormationIamQuotaRollbackIntegrationTest {
@InjectSpy
IamService iam;
@ParameterizedTest
@ValueSource(booleans = {false, true})
void failedUserUpdateReportsActualCompensationOutcome(boolean restorationFails) {
String suffix = UUID.randomUUID().toString();
String stack = "quota-rollback-" + suffix;
String user = "quota-user-" + suffix;
cfn("CreateStack", stack, template(user, 200)).then().statusCode(200);
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
String historical = policy(2049);
iam.getUser(user).getInlinePolicies().put("owned", historical);
assertEquals(historical, iam.getUserPolicy(user, "owned"));
if (restorationFails) {
doAnswer(call -> {
InlinePolicyChange change = (InlinePolicyChange) call.callRealMethod();
return new InlinePolicyChange(change.previousDocument(), () -> {
throw new AwsException("AccessDenied", "injected compensation failure", 403);
});
}).when(iam).deleteUserPolicyWithRollback(user, "owned");
}
try {
cfn("UpdateStack", stack, template(user, 2050)).then().statusCode(200);
String expected = restorationFails ? "UPDATE_ROLLBACK_FAILED" : "UPDATE_ROLLBACK_COMPLETE";
CfnStackWaits.awaitStatus(stack, expected);
cfn("DescribeStackEvents", stack, null).then().statusCode(200)
.body(containsString("Maximum policy size of 2048 bytes exceeded"));
if (restorationFails) {
assertNull(iam.getUser(user).getInlinePolicies().get("owned"));
cfn("DescribeStackResources", stack, null).then().statusCode(200)
.body(containsString("<ResourceStatus>UPDATE_FAILED</ResourceStatus>"));
cfn("DescribeStackEvents", stack, null).then().statusCode(200)
.body(containsString("Could not restore user after failed update"));
} else {
assertEquals(historical, iam.getUserPolicy(user, "owned"));
}
} finally {
doCallRealMethod().when(iam).deleteUserPolicyWithRollback(user, "owned");
cfn("DeleteStack", stack, null).then().statusCode(200);
CfnStackWaits.awaitStackDeleted(stack);
}
}
private static Response cfn(String action, String stack, String template) {
RequestSpecification request = given().contentType("application/x-www-form-urlencoded")
.formParam("Action", action).formParam("StackName", stack);
if (template != null) {
request.formParam("TemplateBody", template);
}
return request.post("/");
}
private static String template(String user, int size) {
return "{\"Resources\":{\"User\":{\"Type\":\"AWS::IAM::User\",\"Properties\":{\"UserName\":\""
+ user + "\",\"Policies\":[{\"PolicyName\":\"owned\",\"PolicyDocument\":" + policy(size) + "}]}}}}";
}
private static String policy(int length) {
String prefix = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"";
String suffix = "\",\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
return prefix + "x".repeat(length - prefix.length() - suffix.length()) + suffix;
}
}
@@ -6,6 +6,8 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testutil.IamInlinePolicyMock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
@@ -34,6 +36,11 @@ class IamPolicyCfnProvisionerTest {
private final IamPolicyCfnProvisioner provisioner = new IamPolicyCfnProvisioner(iam);
private final ObjectMapper mapper = new ObjectMapper();
@BeforeEach
void configureInlinePolicyChanges() {
IamInlinePolicyMock.configure(iam);
}
@Test
void embedsThePolicyIntoEachPrincipalAndRefIsTheName() throws Exception {
StackResource r = resource();
@@ -8,6 +8,9 @@ import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
import io.github.hectorvent.floci.services.iam.model.IamUser;
import io.github.hectorvent.floci.testutil.IamInlinePolicyMock;
import io.github.hectorvent.floci.testutil.IamServiceTestHelper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
@@ -37,6 +40,11 @@ class IamUserCfnProvisionerTest {
private final IamUserCfnProvisioner provisioner = new IamUserCfnProvisioner(iam);
private final ObjectMapper mapper = new ObjectMapper();
@BeforeEach
void configureInlinePolicyChanges() {
IamInlinePolicyMock.configure(iam);
}
private ProvisionContext ctx() {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
@@ -51,7 +59,7 @@ class IamUserCfnProvisionerTest {
// tests use it just walks the array and calls resolve(...) per element, stubbed above.
when(engine.resolveStringList(any())).thenCallRealMethod();
when(engine.resolveJsonAttribute(any())).thenAnswer(inv -> {
when(engine.resolveJsonAttributeStrict(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node != null && node.isTextual() ? node.asText() : node.toString();
});
@@ -292,7 +300,9 @@ class IamUserCfnProvisionerTest {
verify(iam).deleteUserPolicy("my-user", "drop-inline");
verify(iam, never()).removeUserFromGroup("keep-group", "my-user");
verify(iam, never()).detachUserPolicy("my-user", "arn:aws:iam::aws:policy/Keep");
verify(iam, never()).deleteUserPolicy("my-user", "keep-inline");
InOrder policyOrder = inOrder(iam);
policyOrder.verify(iam).deleteUserPolicy("my-user", "keep-inline");
policyOrder.verify(iam).putUserPolicy(eq("my-user"), eq("keep-inline"), any());
verify(iam).tagUser("my-user", Map.of("update-tag", "new", "add-tag", "added"));
verify(iam).untagUser("my-user", List.of("drop-tag"));
}
@@ -370,6 +380,32 @@ class IamUserCfnProvisionerTest {
verify(iam, never()).attachUserPolicy(any(), any());
}
@Test
void policyRenameAndFailedReplacementPreserveQuotaAndUntrackedPolicies() throws Exception {
IamService realIam = IamServiceTestHelper.iamServiceWithUserPolicy("test", "secret", "seed", "{}");
IamUserCfnProvisioner realProvisioner = new IamUserCfnProvisioner(realIam);
StackResource r = resource();
String policy = "{\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\","
+ "\"Resource\":\"*\",\"Sid\":\"" + "x".repeat(1_200) + "\"}]}";
JsonNode original = mapper.readTree("{\"UserName\":\"app-user\",\"Policies\":["
+ "{\"PolicyName\":\"old\",\"PolicyDocument\":" + policy + "}]}");
realProvisioner.provision(r, original, ctx());
realIam.putUserPolicy("app-user", "untracked", "{}");
JsonNode renamed = mapper.readTree("{\"UserName\":\"app-user\",\"Policies\":["
+ "{\"PolicyName\":\"new\",\"PolicyDocument\":" + policy + "}]}");
realProvisioner.provision(r, renamed, updateCtx("app-user"));
assertEquals(Map.of("new", policy, "untracked", "{}"), realIam.getUser("app-user").getInlinePolicies());
JsonNode overflow = mapper.readTree("{\"UserName\":\"app-user\",\"Policies\":["
+ "{\"PolicyName\":\"replacement\",\"PolicyDocument\":" + policy + "},"
+ "{\"PolicyName\":\"overflow\",\"PolicyDocument\":" + policy + "}]}");
AwsException failure = assertThrows(AwsException.class,
() -> realProvisioner.provision(r, overflow, updateCtx("app-user")));
assertEquals("LimitExceeded", failure.getErrorCode());
assertEquals(0, failure.getSuppressed().length);
assertEquals(Map.of("new", policy, "untracked", "{}"), realIam.getUser("app-user").getInlinePolicies());
}
@Test
void failedUpdateRestoresPriorInlinePolicyAndDetachesNewManagedPolicy() {
IamUser existing = new IamUser("AIDAuser", "my-user", "/", "arn:aws:iam::" + ACCOUNT_ID + ":user/my-user");
@@ -0,0 +1,200 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamPolicyCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamUserCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ProvisionContext;
import io.github.hectorvent.floci.services.iam.model.IamGroup;
import io.github.hectorvent.floci.services.iam.model.IamUser;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class IamLegacyQuotaRollbackTest {
private final ObjectMapper mapper = new ObjectMapper();
@TempDir
Path directory;
private PersistentStorage<String, IamUser> users;
private PersistentStorage<String, IamGroup> groups;
private IamService iam;
@BeforeEach
void reload() {
users = new PersistentStorage<>(directory.resolve("users.json"), new TypeReference<>() {});
groups = new PersistentStorage<>(directory.resolve("groups.json"), new TypeReference<>() {});
users.load();
groups.load();
iam = new IamService(users, groups, new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false);
}
private void saveHistoricalDocument(String kind, String original) {
// Saved shape accepted by the pre-quota service, loaded through real JSON storage.
if ("User".equals(kind)) {
IamUser user = iam.getUser("first");
user.getInlinePolicies().put("shared", original);
users.put("first", user);
} else {
IamGroup group = iam.getGroup("first");
group.getInlinePolicies().put("shared", original);
groups.put("first", group);
}
reload();
assertEquals(original, get(kind, "first", "shared"));
}
@ParameterizedTest
@CsvSource({"User, 2048", "Group, 5120"})
void preservesHistoricalOversizedDocumentAfterLaterTargetFailure(String kind, int limit) throws Exception {
create(kind, "first");
create(kind, "second");
String original = policy(limit + 1);
saveHistoricalDocument(kind, original);
put(kind, "second", "shared", policy(500));
put(kind, "second", "other", policy(limit - 1000));
assertEquals(original, get(kind, "first", "shared"));
StackResource resource = resource("AWS::IAM::Policy", "shared");
resource.getAttributes().put("Inline" + kind + "Targets", "first\nsecond");
JsonNode props = mapper.readTree("{\"PolicyName\":\"shared\",\"PolicyDocument\":"
+ policy(1100) + ",\"" + kind + "s\":[\"first\",\"second\"]}");
AwsException error = assertThrows(AwsException.class,
() -> new IamPolicyCfnProvisioner(iam).provision(resource, props, context("shared")));
assertEquals("LimitExceeded", error.getErrorCode());
assertEquals(original, get(kind, "first", "shared"));
assertEquals("true", resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
reload();
assertEquals(original, get(kind, "first", "shared"));
assertEquals("LimitExceeded", assertThrows(AwsException.class,
() -> put(kind, "first", "other", policy(200))).getErrorCode());
}
@ParameterizedTest
@CsvSource({"User, 2048", "Group, 5120"})
void failedRenameRestoresSavedOversizedDocumentAndAllowsRetry(String kind, int limit) throws Exception {
create(kind, "first");
create(kind, "second");
String original = policy(limit + 1);
saveHistoricalDocument(kind, original);
put(kind, "second", "other", policy(200));
StackResource resource = resource("AWS::IAM::Policy", "shared");
resource.getAttributes().put("Inline" + kind + "Targets", "first");
JsonNode props = mapper.readTree("{\"PolicyName\":\"new\",\"PolicyDocument\":"
+ policy(limit) + ",\"" + kind + "s\":[\"first\",\"second\"]}");
AwsException error = assertThrows(AwsException.class,
() -> new IamPolicyCfnProvisioner(iam).provision(resource, props, context("shared")));
assertEquals("LimitExceeded", error.getErrorCode());
assertEquals(original, get(kind, "first", "shared"));
assertEquals("NoSuchEntity", assertThrows(AwsException.class,
() -> get(kind, "first", "new")).getErrorCode());
assertEquals("true", resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
reload();
assertEquals(original, get(kind, "first", "shared"));
if ("User".equals(kind)) {
iam.deleteUserPolicy("second", "other");
} else {
iam.deleteGroupPolicy("second", "other");
}
new IamPolicyCfnProvisioner(iam).provision(resource, props, context("shared"));
reload();
assertEquals(policy(limit), get(kind, "first", "new"));
assertEquals(policy(limit), get(kind, "second", "new"));
assertEquals("NoSuchEntity", assertThrows(AwsException.class,
() -> get(kind, "first", "shared")).getErrorCode());
}
@Test
void preservesHistoricalUserPolicyAfterRejectedReplacement() throws Exception {
create("User", "first");
String original = policy(2049);
saveHistoricalDocument("User", original);
assertEquals(original, get("User", "first", "shared"));
StackResource resource = resource("AWS::IAM::User", "first");
resource.getAttributes().put("__FlociInlinePolicyNames", "shared");
resource.getAttributes().put("__FlociUserId", iam.getUser("first").getUserId());
JsonNode props = mapper.readTree("{\"UserName\":\"first\",\"Policies\":[{\"PolicyName\":\"shared\",\"PolicyDocument\":"
+ policy(2050) + "}]}");
AwsException error = assertThrows(AwsException.class,
() -> new IamUserCfnProvisioner(iam)
.provision(resource, props, context("first")));
assertEquals("LimitExceeded", error.getErrorCode());
assertEquals(original, iam.getUser("first").getInlinePolicies().get("shared"));
assertNull(resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
reload();
assertEquals(Map.of("shared", original), iam.getUser("first").getInlinePolicies());
assertEquals("LimitExceeded", assertThrows(AwsException.class,
() -> iam.putUserPolicy("first", "shared", policy(2050))).getErrorCode());
}
private StackResource resource(String type, String id) {
StackResource r = new StackResource();
r.setLogicalId("Resource");
r.setResourceType(type);
r.setPhysicalId(id);
r.setAttributes(new HashMap<>());
return r;
}
private ProvisionContext context(String previous) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> ((JsonNode) inv.getArgument(0)).asText());
when(engine.resolveJsonAttributeStrict(any())).thenAnswer(inv -> inv.getArgument(0).toString());
return new ProvisionContext(engine, "us-east-1", "000000000000", "stack", previous);
}
private void create(String kind, String name) {
switch (kind) {
case "User" -> iam.createUser(name, "/");
case "Group" -> iam.createGroup(name, "/");
case "Role" -> iam.createRole(name, "/", "{}", null, 3600, null);
default -> throw new IllegalArgumentException(kind);
}
}
private void put(String kind, String name, String policyName, String document) {
switch (kind) {
case "User" -> iam.putUserPolicy(name, policyName, document);
case "Group" -> iam.putGroupPolicy(name, policyName, document);
case "Role" -> iam.putRolePolicy(name, policyName, document);
default -> throw new IllegalArgumentException(kind);
}
}
private String get(String kind, String name, String policyName) {
return switch (kind) {
case "User" -> iam.getUserPolicy(name, policyName);
case "Group" -> iam.getGroupPolicy(name, policyName);
case "Role" -> iam.getRolePolicy(name, policyName);
default -> throw new IllegalArgumentException(kind);
};
}
private static String policy(int length) {
String prefix = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"";
String suffix = "\",\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
return prefix + "x".repeat(length - prefix.length() - suffix.length()) + suffix;
}
}
@@ -0,0 +1,438 @@
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.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamPolicyCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ProvisionContext;
import io.github.hectorvent.floci.services.iam.IamService.InlinePolicyChange;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
class IamPolicyQuotaRollbackTest {
private final ObjectMapper mapper = new ObjectMapper();
private final RegionResolver resolver = spy(new RegionResolver("us-east-1", "000000000000"));
private final IamService iam = spy(new IamService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(),
resolver, false));
@ParameterizedTest
@CsvSource({"User, 2048, owned", "Group, 5120, owned", "Role, 10240, owned",
"User, 2048, added", "Group, 5120, added", "Role, 10240, added",
"User, 2048, absent", "Group, 5120, absent", "Role, 10240, absent",
"User, 2048, failure", "Group, 5120, failure", "Role, 10240, failure"})
void failedLaterTargetRestoresEarlierSameNameDocument(String kind, int limit, String state) throws Exception {
create(kind, "first");
create(kind, "second");
String original = policy(500);
if (!"absent".equals(state)) {
put(kind, "first", "shared", original);
}
if ("failure".equals(state)) {
failRestore(kind, original);
}
put(kind, "second", "shared", original);
String sibling = policy(limit - 1000);
put(kind, "second", "other", sibling);
StackResource resource = new StackResource();
resource.setLogicalId("Policy");
resource.setResourceType("AWS::IAM::Policy");
resource.setPhysicalId("shared");
resource.setAttributes(new HashMap<>());
resource.getAttributes().put("Inline" + kind + "Targets",
"added".equals(state) ? "second" : "first\nsecond");
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> ((JsonNode) inv.getArgument(0)).asText());
when(engine.resolveJsonAttributeStrict(any())).thenAnswer(inv -> inv.getArgument(0).toString());
ProvisionContext context = new ProvisionContext(engine, "us-east-1", "000000000000", "stack", "shared");
JsonNode properties = mapper.readTree("{\"PolicyName\":\"shared\",\"PolicyDocument\":"
+ policy(1100) + ",\"" + kind + "s\":[\"first\",\"second\"]}");
AwsException error = assertThrows(AwsException.class,
() -> new IamPolicyCfnProvisioner(iam).provision(resource, properties, context));
assertEquals("LimitExceeded", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
if ("absent".equals(state)) {
assertEquals("NoSuchEntity", assertThrows(AwsException.class,
() -> get(kind, "first", "shared")).getErrorCode());
} else {
assertEquals("failure".equals(state) ? policy(1100) : original, get(kind, "first", "shared"));
}
assertEquals(original, get(kind, "second", "shared"));
assertEquals(sibling, get(kind, "second", "other"));
if ("failure".equals(state)) {
assertNull(resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
assertNotNull(resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
assertEquals(1, error.getSuppressed().length);
} else {
assertEquals("true", resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
}
}
@ParameterizedTest
@CsvSource({"User", "Group", "Role"})
void failureDeletingOldNameRestoresDeletedAndOverwrittenDocuments(String kind) throws Exception {
create(kind, "first");
create(kind, "second");
String original = policy(500);
put(kind, "first", "shared", original);
put(kind, "second", "shared", original);
String collision = policy(200);
put(kind, "first", "new", collision);
AwsException deletionFailure = new AwsException("AccessDenied", "injected delete failure", 403);
switch (kind) {
case "User" -> doThrow(deletionFailure).when(iam).deleteUserPolicy("second", "shared");
case "Group" -> doThrow(deletionFailure).when(iam).deleteGroupPolicy("second", "shared");
case "Role" -> doThrow(deletionFailure).when(iam).deleteRolePolicy("second", "shared");
default -> throw new IllegalArgumentException(kind);
}
StackResource resource = new StackResource();
resource.setLogicalId("Policy");
resource.setResourceType("AWS::IAM::Policy");
resource.setPhysicalId("shared");
resource.setAttributes(new HashMap<>());
resource.getAttributes().put("Inline" + kind + "Targets", "first\nsecond");
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> ((JsonNode) inv.getArgument(0)).asText());
when(engine.resolveJsonAttributeStrict(any())).thenAnswer(inv -> inv.getArgument(0).toString());
ProvisionContext context = new ProvisionContext(engine, "us-east-1", "000000000000", "stack", "shared");
JsonNode properties = mapper.readTree("{\"PolicyName\":\"new\",\"PolicyDocument\":"
+ policy(800) + ",\"" + kind + "s\":[\"first\",\"second\"]}");
assertEquals(deletionFailure, assertThrows(AwsException.class,
() -> new IamPolicyCfnProvisioner(iam).provision(resource, properties, context)));
assertEquals(original, get(kind, "first", "shared"));
assertEquals(original, get(kind, "second", "shared"));
assertEquals(collision, get(kind, "first", "new"));
assertEquals("NoSuchEntity", assertThrows(AwsException.class,
() -> get(kind, "second", "new")).getErrorCode());
assertEquals("shared", resource.getPhysicalId());
assertEquals("true", resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
}
@ParameterizedTest
@CsvSource({"User, 2048, false", "Group, 5120, false", "Role, 10240, false",
"User, 2048, true", "Group, 5120, true", "Role, 10240, true"})
void compensationCannotConsumeCapacityAdmittedToAnotherPolicy(String kind, int limit, boolean deletion) {
create(kind, "first");
put(kind, "first", "shared", policy(limit - 548));
InlinePolicyChange change = deletion ? remove(kind, "first", "shared")
: update(kind, "first", "shared", policy(500));
String sibling = policy(limit - 648);
put(kind, "first", "other", sibling);
AwsException error = assertThrows(AwsException.class, () -> change.rollback().run());
assertEquals("ConcurrentModification", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
assertEquals(sibling, get(kind, "first", "other"));
if (deletion) {
assertEquals("NoSuchEntity", assertThrows(AwsException.class,
() -> get(kind, "first", "shared")).getErrorCode());
} else {
assertEquals(policy(500), get(kind, "first", "shared"));
}
}
@ParameterizedTest
@CsvSource({"User", "Group", "Role"})
void uncontestedCompensationPreservesAnUnrelatedPolicyWhenQuotaAllows(String kind) {
create(kind, "first");
put(kind, "first", "shared", policy(500));
InlinePolicyChange change = update(kind, "first", "shared", policy(200));
put(kind, "first", "other", policy(300));
change.rollback().run();
assertEquals(policy(500), get(kind, "first", "shared"));
assertEquals(policy(300), get(kind, "first", "other"));
}
@ParameterizedTest
@CsvSource({"User, false", "Group, false", "Role, false",
"User, true", "Group, true", "Role, true"})
void refusedCompensationDoesNotQueueDeletionOfAnotherWritersPolicy(String kind, boolean replace) throws Exception {
create(kind, "first");
create(kind, "second");
put(kind, "second", "shared", policy(500));
AwsException failure = new AwsException("AccessDenied", "later target refused", 403);
Runnable concurrentWrite = () -> {
if (replace) {
remove(kind, "first", "shared");
switch (kind) {
case "User" -> iam.deleteUser("first");
case "Group" -> iam.deleteGroup("first");
case "Role" -> iam.deleteRole("first");
default -> throw new IllegalArgumentException(kind);
}
create(kind, "first");
}
put(kind, "first", "shared", policy(300));
};
switch (kind) {
case "User" -> doAnswer(call -> { concurrentWrite.run(); throw failure; })
.when(iam).putUserPolicy("second", "shared", policy(200));
case "Group" -> doAnswer(call -> { concurrentWrite.run(); throw failure; })
.when(iam).putGroupPolicy("second", "shared", policy(200));
case "Role" -> doAnswer(call -> { concurrentWrite.run(); throw failure; })
.when(iam).putRolePolicy("second", "shared", policy(200));
default -> throw new IllegalArgumentException(kind);
}
StackResource resource = new StackResource();
resource.setLogicalId("Policy");
resource.setResourceType("AWS::IAM::Policy");
resource.setPhysicalId("shared");
resource.setAttributes(new HashMap<>());
resource.getAttributes().put("Inline" + kind + "Targets", "second");
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(call -> ((JsonNode) call.getArgument(0)).asText());
when(engine.resolveJsonAttributeStrict(any())).thenAnswer(call -> call.getArgument(0).toString());
ProvisionContext context = new ProvisionContext(engine, "us-east-1", "000000000000", "stack", "shared");
JsonNode props = mapper.readTree("{\"PolicyName\":\"shared\",\"PolicyDocument\":"
+ policy(200) + ",\"" + kind + "s\":[\"first\",\"second\"]}");
IamPolicyCfnProvisioner provisioner = new IamPolicyCfnProvisioner(iam);
assertEquals(failure, assertThrows(AwsException.class,
() -> provisioner.provision(resource, props, context)));
assertEquals("ConcurrentModification", ((AwsException) failure.getSuppressed()[0]).getErrorCode());
assertNotNull(resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
assertNull(resource.getAttributes().get("__FlociInlineCleanupPolicyName"));
provisioner.delete(resource, "us-east-1");
assertEquals(policy(300), get(kind, "first", "shared"));
}
@ParameterizedTest
@CsvSource({"User", "Group", "Role"})
void compensationRefusesADifferentAmbientAccount(String kind) {
create(kind, "first");
put(kind, "first", "shared", policy(500));
InlinePolicyChange change = update(kind, "first", "shared", policy(200));
when(resolver.getAccountId()).thenReturn("111122223333");
assertEquals("ConcurrentModification", assertThrows(AwsException.class,
() -> change.rollback().run()).getErrorCode());
assertEquals(policy(200), get(kind, "first", "shared"));
when(resolver.getAccountId()).thenReturn("000000000000");
change.rollback().run();
assertEquals(policy(500), get(kind, "first", "shared"));
}
@ParameterizedTest
@CsvSource({"User", "Group", "Role"})
void nestedReverseCompensationRestoresTheOriginalDocuments(String kind) {
create(kind, "first");
put(kind, "first", "shared", policy(500));
InlinePolicyChange removed = remove(kind, "first", "shared");
InlinePolicyChange written = update(kind, "first", "shared", policy(200));
put(kind, "first", "unrelated", policy(200));
assertEquals("ConcurrentModification", assertThrows(AwsException.class,
() -> removed.rollback().run()).getErrorCode());
written.rollback().run();
removed.rollback().run();
assertEquals(policy(500), get(kind, "first", "shared"));
assertEquals(policy(200), get(kind, "first", "unrelated"));
assertEquals("ConcurrentModification", assertThrows(AwsException.class,
() -> written.rollback().run()).getErrorCode());
}
@ParameterizedTest
@CsvSource({"User, missing, false", "Group, missing, false", "Role, missing, false",
"User, missing, true", "Group, missing, true", "Role, missing, true",
"Role, bad/name, false", "Role, bad/name, true"})
void capturedWritesPreserveOrdinaryPrincipalErrors(String kind, String principal, boolean deletion) {
AwsException ordinary = assertThrows(AwsException.class, () -> {
if (deletion) {
delete(kind, principal, "shared");
} else {
put(kind, principal, "shared", policy(200));
}
});
AwsException captured = assertThrows(AwsException.class, () -> {
if (deletion) {
remove(kind, principal, "shared");
} else {
update(kind, principal, "shared", policy(200));
}
});
assertEquals(ordinary.getErrorCode(), captured.getErrorCode());
assertEquals(ordinary.getHttpStatus(), captured.getHttpStatus());
assertEquals(ordinary.getMessage(), captured.getMessage());
}
@ParameterizedTest
@CsvSource({"User, 2048", "Group, 5120", "Role, 10240"})
void rejectedWriteAndOtherPrincipalDoNotInvalidateCompensation(String kind, int limit) {
create(kind, "first");
create(kind, "second");
put(kind, "first", "shared", policy(500));
InlinePolicyChange change = update(kind, "first", "shared", policy(200));
assertEquals("LimitExceeded", assertThrows(AwsException.class,
() -> put(kind, "first", "shared", policy(limit + 1))).getErrorCode());
put(kind, "second", "shared", policy(200));
change.rollback().run();
assertEquals(policy(500), get(kind, "first", "shared"));
assertEquals(policy(200), get(kind, "second", "shared"));
}
@ParameterizedTest
@CsvSource({"User, 2048, false, false", "Group, 5120, false, false", "Role, 10240, false, false",
"User, 2048, true, false", "Group, 5120, true, false", "Role, 10240, true, false",
"User, 2048, false, true", "Group, 5120, false, true", "Role, 10240, false, true",
"User, 2048, true, true", "Group, 5120, true, true", "Role, 10240, true, true"})
void renameAtQuotaRetainsFinalStateAndRestoresActualCollisionOnFailure(
String kind, int limit, boolean collision, boolean failure) throws Exception {
create(kind, "first");
create(kind, "second");
create(kind, "removed");
String original = policy(limit - (collision ? 200 : 0));
put(kind, "first", "shared", original);
put(kind, "removed", "shared", original);
if (collision) {
put(kind, "first", "new", policy(200));
}
AwsException injected = new AwsException("AccessDenied", "later target refused", 403);
if (failure) {
switch (kind) {
case "User" -> doThrow(injected).when(iam).putUserPolicy("second", "new", policy(limit));
case "Group" -> doThrow(injected).when(iam).putGroupPolicy("second", "new", policy(limit));
case "Role" -> doThrow(injected).when(iam).putRolePolicy("second", "new", policy(limit));
default -> throw new IllegalArgumentException(kind);
}
}
StackResource resource = new StackResource();
resource.setLogicalId("Policy");
resource.setResourceType("AWS::IAM::Policy");
resource.setPhysicalId("shared");
resource.setAttributes(new HashMap<>());
resource.getAttributes().put("Inline" + kind + "Targets", "first\nremoved");
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(call -> ((JsonNode) call.getArgument(0)).asText());
when(engine.resolveJsonAttributeStrict(any())).thenAnswer(call -> call.getArgument(0).toString());
ProvisionContext context = new ProvisionContext(engine, "us-east-1", "000000000000", "stack", "shared");
JsonNode props = mapper.readTree("{\"PolicyName\":\"new\",\"PolicyDocument\":"
+ policy(limit) + ",\"" + kind + "s\":[\"first\",\"second\"]}");
IamPolicyCfnProvisioner provisioner = new IamPolicyCfnProvisioner(iam);
if (failure) {
assertEquals(injected, assertThrows(AwsException.class,
() -> provisioner.provision(resource, props, context)));
assertEquals(original, get(kind, "first", "shared"));
assertEquals(original, get(kind, "removed", "shared"));
if (collision) {
assertEquals(policy(200), get(kind, "first", "new"));
} else {
assertEquals("NoSuchEntity", assertThrows(AwsException.class,
() -> get(kind, "first", "new")).getErrorCode());
}
assertEquals("NoSuchEntity", assertThrows(AwsException.class,
() -> get(kind, "second", "new")).getErrorCode());
assertEquals("true", resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
assertEquals("shared", resource.getPhysicalId());
} else {
provisioner.provision(resource, props, context);
assertEquals(policy(limit), get(kind, "first", "new"));
assertEquals(policy(limit), get(kind, "second", "new"));
assertEquals("NoSuchEntity", assertThrows(AwsException.class,
() -> get(kind, "first", "shared")).getErrorCode());
assertEquals("NoSuchEntity", assertThrows(AwsException.class,
() -> get(kind, "removed", "shared")).getErrorCode());
assertEquals("new", resource.getPhysicalId());
ProvisionContext retry = new ProvisionContext(engine, "us-east-1", "000000000000", "stack", "new");
provisioner.provision(resource, props, retry);
assertEquals(policy(limit), get(kind, "first", "new"));
}
}
private void delete(String kind, String principal, String name) {
switch (kind) {
case "User" -> iam.deleteUserPolicy(principal, name);
case "Group" -> iam.deleteGroupPolicy(principal, name);
case "Role" -> iam.deleteRolePolicy(principal, name);
default -> throw new IllegalArgumentException(kind);
}
}
private InlinePolicyChange update(String kind, String principal, String name, String document) {
return switch (kind) {
case "User" -> iam.putUserPolicyWithRollback(principal, name, document);
case "Group" -> iam.putGroupPolicyWithRollback(principal, name, document);
case "Role" -> iam.putRolePolicyWithRollback(principal, name, document);
default -> throw new IllegalArgumentException(kind);
};
}
private InlinePolicyChange remove(String kind, String principal, String name) {
return switch (kind) {
case "User" -> iam.deleteUserPolicyWithRollback(principal, name);
case "Group" -> iam.deleteGroupPolicyWithRollback(principal, name);
case "Role" -> iam.deleteRolePolicyWithRollback(principal, name);
default -> throw new IllegalArgumentException(kind);
};
}
private void failRestore(String kind, String original) {
AwsException failure = new AwsException("AccessDenied", "injected restoration failure", 403);
switch (kind) {
case "User" -> doAnswer(call -> {
InlinePolicyChange change = (InlinePolicyChange) call.callRealMethod();
return new InlinePolicyChange(change.previousDocument(), () -> { throw failure; });
}).when(iam).putUserPolicyWithRollback("first", "shared", policy(1100));
case "Group" -> doAnswer(call -> {
InlinePolicyChange change = (InlinePolicyChange) call.callRealMethod();
return new InlinePolicyChange(change.previousDocument(), () -> { throw failure; });
}).when(iam).putGroupPolicyWithRollback("first", "shared", policy(1100));
case "Role" -> doAnswer(call -> {
InlinePolicyChange change = (InlinePolicyChange) call.callRealMethod();
return new InlinePolicyChange(change.previousDocument(), () -> { throw failure; });
}).when(iam).putRolePolicyWithRollback("first", "shared", policy(1100));
default -> throw new IllegalArgumentException(kind);
}
}
private void create(String kind, String name) {
switch (kind) {
case "User" -> iam.createUser(name, "/");
case "Group" -> iam.createGroup(name, "/");
case "Role" -> iam.createRole(name, "/", "{}", null, 3600, null);
default -> throw new IllegalArgumentException(kind);
}
}
private void put(String kind, String name, String policyName, String document) {
switch (kind) {
case "User" -> iam.putUserPolicy(name, policyName, document);
case "Group" -> iam.putGroupPolicy(name, policyName, document);
case "Role" -> iam.putRolePolicy(name, policyName, document);
default -> throw new IllegalArgumentException(kind);
}
}
private String get(String kind, String name, String policyName) {
return switch (kind) {
case "User" -> iam.getUserPolicy(name, policyName);
case "Group" -> iam.getGroupPolicy(name, policyName);
case "Role" -> iam.getRolePolicy(name, policyName);
default -> throw new IllegalArgumentException(kind);
};
}
private static String policy(int length) {
String prefix = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"";
String suffix = "\",\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
return prefix + "x".repeat(length - prefix.length() - suffix.length()) + suffix;
}
}
@@ -71,6 +71,58 @@ class IamServicePersistenceTest {
assertEquals(secondPolicy, restarted.getRolePolicy("R", "second"));
}
@Test
void userInlinePolicyQuotaUsesPersistedAggregateAfterRestart(@TempDir Path directory) {
IamService first = newService(directory);
first.createUser("R", "/");
String firstPolicy = policyWithNonWhitespaceLength(1_200);
String secondPolicy = policyWithNonWhitespaceLength(800);
first.putUserPolicy("R", "first", firstPolicy);
first.putUserPolicy("R", "second", secondPolicy);
IamService restarted = newService(directory);
assertEquals(firstPolicy, restarted.getUserPolicy("R", "first"));
assertEquals(secondPolicy, restarted.getUserPolicy("R", "second"));
AwsException aggregateError = assertThrows(AwsException.class,
() -> restarted.putUserPolicy("R", "third", policyWithNonWhitespaceLength(200)));
assertEquals("LimitExceeded", aggregateError.getErrorCode());
assertEquals(409, aggregateError.getHttpStatus());
AwsException replacementError = assertThrows(AwsException.class,
() -> restarted.putUserPolicy("R", "first", policyWithNonWhitespaceLength(1_249)));
assertEquals("LimitExceeded", replacementError.getErrorCode());
assertEquals(409, replacementError.getHttpStatus());
assertEquals(firstPolicy, restarted.getUserPolicy("R", "first"));
assertEquals(secondPolicy, restarted.getUserPolicy("R", "second"));
}
@Test
void groupInlinePolicyQuotaUsesPersistedAggregateAfterRestart(@TempDir Path directory) {
IamService first = newService(directory);
first.createGroup("R", "/");
String firstPolicy = policyWithNonWhitespaceLength(3_000);
String secondPolicy = policyWithNonWhitespaceLength(2_000);
first.putGroupPolicy("R", "first", firstPolicy);
first.putGroupPolicy("R", "second", secondPolicy);
IamService restarted = newService(directory);
assertEquals(firstPolicy, restarted.getGroupPolicy("R", "first"));
assertEquals(secondPolicy, restarted.getGroupPolicy("R", "second"));
AwsException aggregateError = assertThrows(AwsException.class,
() -> restarted.putGroupPolicy("R", "third", policyWithNonWhitespaceLength(200)));
assertEquals("LimitExceeded", aggregateError.getErrorCode());
assertEquals(409, aggregateError.getHttpStatus());
AwsException replacementError = assertThrows(AwsException.class,
() -> restarted.putGroupPolicy("R", "first", policyWithNonWhitespaceLength(3_121)));
assertEquals("LimitExceeded", replacementError.getErrorCode());
assertEquals(409, replacementError.getHttpStatus());
assertEquals(firstPolicy, restarted.getGroupPolicy("R", "first"));
assertEquals(secondPolicy, restarted.getGroupPolicy("R", "second"));
}
@Test
void openIdConnectProviderSurvivesRestart(@TempDir Path dir) {
IamService first = newService(dir);
@@ -149,6 +149,130 @@ class IamServiceTest {
assertEquals(1, iamService.listRolePolicies("R").size());
}
@Test
void userInlinePolicyQuotaIgnoresWhitespaceAndPreservesRejectedReplacement() {
iamService.createUser("R", "/");
String exactLimit = policyWithNonWhitespaceLength(2_048);
String padded = exactLimit.substring(0, 1) + " \n\t\r ".repeat(1_000) + exactLimit.substring(1);
iamService.putUserPolicy("R", "inline-exec", padded);
AwsException error = assertThrows(AwsException.class,
() -> iamService.putUserPolicy("R", "inline-exec", policyWithNonWhitespaceLength(2_049)));
assertEquals("LimitExceeded", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
assertEquals(padded, iamService.getUserPolicy("R", "inline-exec"));
iamService.putUserPolicy("R", "inline-exec", exactLimit);
assertEquals(exactLimit, iamService.getUserPolicy("R", "inline-exec"));
}
@Test
void userInlinePolicyQuotaCountsAllPolicies() {
iamService.createUser("R", "/");
iamService.putUserPolicy("R", "first", policyWithNonWhitespaceLength(1_200));
iamService.putUserPolicy("R", "second", policyWithNonWhitespaceLength(649));
AwsException error = assertThrows(AwsException.class,
() -> iamService.putUserPolicy("R", "third", policyWithNonWhitespaceLength(200)));
assertEquals("LimitExceeded", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
assertEquals(List.of("first", "second"), iamService.listUserPolicies("R").stream().sorted().toList());
}
@Test
void userInlinePolicyQuotaIsAtomicAcrossConcurrentWrites() throws Exception {
iamService.createUser("R", "/");
CountDownLatch start = new CountDownLatch(1);
AtomicInteger accepted = new AtomicInteger();
AtomicInteger rejected = new AtomicInteger();
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
for (String policyName : List.of("first", "second")) {
executor.submit(() -> {
start.await();
try {
iamService.putUserPolicy("R", policyName, policyWithNonWhitespaceLength(1_200));
accepted.incrementAndGet();
} catch (AwsException error) {
assertEquals("LimitExceeded", error.getErrorCode());
rejected.incrementAndGet();
}
return null;
});
}
start.countDown();
executor.shutdown();
assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
}
assertEquals(1, accepted.get());
assertEquals(1, rejected.get());
assertEquals(1, iamService.listUserPolicies("R").size());
}
@Test
void groupInlinePolicyQuotaIgnoresWhitespaceAndPreservesRejectedReplacement() {
iamService.createGroup("R", "/");
String exactLimit = policyWithNonWhitespaceLength(5_120);
String padded = exactLimit.substring(0, 1) + " \n\t\r ".repeat(1_000) + exactLimit.substring(1);
iamService.putGroupPolicy("R", "inline-exec", padded);
AwsException error = assertThrows(AwsException.class,
() -> iamService.putGroupPolicy("R", "inline-exec", policyWithNonWhitespaceLength(5_121)));
assertEquals("LimitExceeded", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
assertEquals(padded, iamService.getGroupPolicy("R", "inline-exec"));
iamService.putGroupPolicy("R", "inline-exec", exactLimit);
assertEquals(exactLimit, iamService.getGroupPolicy("R", "inline-exec"));
}
@Test
void groupInlinePolicyQuotaCountsAllPolicies() {
iamService.createGroup("R", "/");
iamService.putGroupPolicy("R", "first", policyWithNonWhitespaceLength(3_000));
iamService.putGroupPolicy("R", "second", policyWithNonWhitespaceLength(1_921));
AwsException error = assertThrows(AwsException.class,
() -> iamService.putGroupPolicy("R", "third", policyWithNonWhitespaceLength(200)));
assertEquals("LimitExceeded", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
assertEquals(List.of("first", "second"), iamService.listGroupPolicies("R").stream().sorted().toList());
}
@Test
void groupInlinePolicyQuotaIsAtomicAcrossConcurrentWrites() throws Exception {
iamService.createGroup("R", "/");
CountDownLatch start = new CountDownLatch(1);
AtomicInteger accepted = new AtomicInteger();
AtomicInteger rejected = new AtomicInteger();
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
for (String policyName : List.of("first", "second")) {
executor.submit(() -> {
start.await();
try {
iamService.putGroupPolicy("R", policyName, policyWithNonWhitespaceLength(3_000));
accepted.incrementAndGet();
} catch (AwsException error) {
assertEquals("LimitExceeded", error.getErrorCode());
rejected.incrementAndGet();
}
return null;
});
}
start.countDown();
executor.shutdown();
assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
}
assertEquals(1, accepted.get());
assertEquals(1, rejected.get());
assertEquals(1, iamService.listGroupPolicies("R").size());
}
/** The STS global endpoint, and so the token version it reports, exists only in the commercial partition. */
@Test
void accountSummaryReportsTheGlobalEndpointTokenVersionOnlyWhereStsHasAGlobalHost() {
@@ -636,6 +760,9 @@ class IamServiceTest {
assertEquals(10L, empty.get("AttachedPoliciesPerGroupQuota"));
assertEquals(20L, empty.get("AttachedPoliciesPerRoleQuota"));
assertEquals(6144L, empty.get("PolicySizeQuota"));
assertEquals(2048L, empty.get("UserPolicySizeQuota"));
assertEquals(5120L, empty.get("GroupPolicySizeQuota"));
assertEquals(10240L, empty.get("RolePolicySizeQuota"));
assertEquals(0L, empty.get("Providers"));
assertEquals(0L, empty.get("AccountAccessKeysPresent"));
@@ -0,0 +1,97 @@
package io.github.hectorvent.floci.testutil;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.IamService.InlinePolicyChange;
import io.github.hectorvent.floci.services.iam.model.IamUser;
import java.util.function.Consumer;
import java.util.function.Supplier;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.lenient;
/** Adapts existing provisioner mocks; real compensation is exercised in the IAM rollback tests. */
public final class IamInlinePolicyMock {
private IamInlinePolicyMock() {}
public static void configure(IamService iam) {
lenient().when(iam.putUserPolicyWithRollback(anyString(), anyString(), anyString())).thenAnswer(call -> {
String principal = call.getArgument(0);
String name = call.getArgument(1);
String document = call.getArgument(2);
String previous = previous(() -> userDocument(iam, principal, name));
iam.putUserPolicy(principal, name, document);
return change(previous, () -> iam.deleteUserPolicy(principal, name),
restored -> iam.putUserPolicy(principal, name, restored));
});
lenient().when(iam.deleteUserPolicyWithRollback(anyString(), anyString())).thenAnswer(call -> {
String principal = call.getArgument(0);
String name = call.getArgument(1);
String previous = previous(() -> userDocument(iam, principal, name));
iam.deleteUserPolicy(principal, name);
return change(previous, () -> iam.deleteUserPolicy(principal, name),
restored -> iam.putUserPolicy(principal, name, restored));
});
lenient().when(iam.putGroupPolicyWithRollback(anyString(), anyString(), anyString())).thenAnswer(call -> {
String principal = call.getArgument(0);
String name = call.getArgument(1);
String document = call.getArgument(2);
String previous = previous(() -> iam.getGroupPolicy(principal, name));
iam.putGroupPolicy(principal, name, document);
return change(previous, () -> iam.deleteGroupPolicy(principal, name),
restored -> iam.putGroupPolicy(principal, name, restored));
});
lenient().when(iam.deleteGroupPolicyWithRollback(anyString(), anyString())).thenAnswer(call -> {
String principal = call.getArgument(0);
String name = call.getArgument(1);
String previous = previous(() -> iam.getGroupPolicy(principal, name));
iam.deleteGroupPolicy(principal, name);
return change(previous, () -> iam.deleteGroupPolicy(principal, name),
restored -> iam.putGroupPolicy(principal, name, restored));
});
lenient().when(iam.putRolePolicyWithRollback(anyString(), anyString(), anyString())).thenAnswer(call -> {
String principal = call.getArgument(0);
String name = call.getArgument(1);
String document = call.getArgument(2);
String previous = previous(() -> iam.getRolePolicy(principal, name));
iam.putRolePolicy(principal, name, document);
return change(previous, () -> iam.deleteRolePolicy(principal, name),
restored -> iam.putRolePolicy(principal, name, restored));
});
lenient().when(iam.deleteRolePolicyWithRollback(anyString(), anyString())).thenAnswer(call -> {
String principal = call.getArgument(0);
String name = call.getArgument(1);
String previous = previous(() -> iam.getRolePolicy(principal, name));
iam.deleteRolePolicy(principal, name);
return change(previous, () -> iam.deleteRolePolicy(principal, name),
restored -> iam.putRolePolicy(principal, name, restored));
});
}
private static String userDocument(IamService iam, String principal, String name) {
IamUser user = iam.getUser(principal);
return user == null ? iam.getUserPolicy(principal, name) : user.getInlinePolicies().get(name);
}
private static String previous(Supplier<String> read) {
try {
return read.get();
} catch (AwsException error) {
if ("NoSuchEntity".equals(error.getErrorCode())) {
return null;
}
throw error;
}
}
private static InlinePolicyChange change(String previous, Runnable delete, Consumer<String> write) {
return new InlinePolicyChange(previous, () -> {
if (previous == null) {
delete.run();
} else {
write.accept(previous);
}
});
}
}