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

@@ -0,0 +1,20 @@
package com.floci.test;
final class IamInlinePolicyTestHelper {
private IamInlinePolicyTestHelper() {
}
static String policyWithNonWhitespaceLength(int targetLength) {
String prefix = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"";
String suffix = "\",\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
return prefix + "x".repeat(targetLength - prefix.length() - suffix.length()) + suffix;
}
static String removeCountedWhitespace(String policyDocument) {
return policyDocument.replace(" ", "")
.replace("\t", "")
.replace("\n", "")
.replace("\r", "");
}
}
@@ -10,6 +10,8 @@ import software.amazon.awssdk.services.iam.model.LimitExceededException;
import software.amazon.awssdk.services.iam.model.ListRolePoliciesRequest;
import software.amazon.awssdk.services.iam.model.PutRolePolicyRequest;
import static com.floci.test.IamInlinePolicyTestHelper.policyWithNonWhitespaceLength;
import static com.floci.test.IamInlinePolicyTestHelper.removeCountedWhitespace;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -101,16 +103,4 @@ class IamRoleInlinePolicyQuotaTest {
iam.deleteRole(DeleteRoleRequest.builder().roleName(roleName).build());
}
private static String policyWithNonWhitespaceLength(int targetLength) {
String prefix = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"";
String suffix = "\",\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
return prefix + "x".repeat(targetLength - prefix.length() - suffix.length()) + suffix;
}
private static String removeCountedWhitespace(String policyDocument) {
return policyDocument.replace(" ", "")
.replace("\t", "")
.replace("\n", "")
.replace("\r", "");
}
}
@@ -0,0 +1,79 @@
package com.floci.test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.LimitExceededException;
import java.util.List;
import static com.floci.test.IamInlinePolicyTestHelper.policyWithNonWhitespaceLength;
import static com.floci.test.IamInlinePolicyTestHelper.removeCountedWhitespace;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class IamUserGroupInlinePolicyQuotaTest {
@ParameterizedTest
@CsvSource({"true, 2048", "false, 5120"})
void enforcesAggregateQuotaAndPreservesRejectedWrites(boolean user, int limit) {
String name = TestFixtures.uniqueName("sdk-inline-quota");
try (IamClient iam = TestFixtures.iamClient()) {
if (user) {
iam.createUser(request -> request.userName(name));
} else {
iam.createGroup(request -> request.groupName(name));
}
try {
String exact = policyWithNonWhitespaceLength(limit);
String padded = exact.substring(0, 1) + " \n\t\r ".repeat(500) + exact.substring(1);
put(iam, user, name, "first", padded);
assertThatThrownBy(() -> put(iam, user, name, "first", policyWithNonWhitespaceLength(limit + 1)))
.isInstanceOf(LimitExceededException.class)
.satisfies(error -> assertThat(((LimitExceededException) error).statusCode()).isEqualTo(409));
assertThat(removeCountedWhitespace(get(iam, user, name, "first"))).isEqualTo(exact);
String half = policyWithNonWhitespaceLength(limit / 2);
put(iam, user, name, "first", half);
put(iam, user, name, "second", half);
assertThatThrownBy(() -> put(iam, user, name, "third", policyWithNonWhitespaceLength(200)))
.isInstanceOf(LimitExceededException.class)
.satisfies(error -> assertThat(((LimitExceededException) error).statusCode()).isEqualTo(409));
assertThat(list(iam, user, name)).containsExactlyInAnyOrder("first", "second");
assertThat(get(iam, user, name, "first")).isEqualTo(half);
assertThat(get(iam, user, name, "second")).isEqualTo(half);
} finally {
for (String policy : list(iam, user, name)) {
if (user) {
iam.deleteUserPolicy(request -> request.userName(name).policyName(policy));
} else {
iam.deleteGroupPolicy(request -> request.groupName(name).policyName(policy));
}
}
if (user) {
iam.deleteUser(request -> request.userName(name));
} else {
iam.deleteGroup(request -> request.groupName(name));
}
}
}
}
private static void put(IamClient iam, boolean user, String name, String policy, String document) {
if (user) {
iam.putUserPolicy(request -> request.userName(name).policyName(policy).policyDocument(document));
} else {
iam.putGroupPolicy(request -> request.groupName(name).policyName(policy).policyDocument(document));
}
}
private static String get(IamClient iam, boolean user, String name, String policy) {
return user ? iam.getUserPolicy(request -> request.userName(name).policyName(policy)).policyDocument()
: iam.getGroupPolicy(request -> request.groupName(name).policyName(policy)).policyDocument();
}
private static List<String> list(IamClient iam, boolean user, String name) {
return user ? iam.listUserPolicies(request -> request.userName(name)).policyNames()
: iam.listGroupPolicies(request -> request.groupName(name)).policyNames();
}
}
+13
View File
@@ -145,6 +145,19 @@ policies are listed in name order so a `Marker` resumes where the previous page
| DeleteRolePolicy | Deletes an inline policy from a role. |
| ListRolePolicies | Lists inline policy names stored on a role. |
Inline policies share an aggregate size limit per principal: 2,048 characters for a user,
5,120 for a group, and 10,240 for a role. Whitespace does not count. A replacement counts
instead of the previous document with the same policy name; exceeding the limit returns
`LimitExceeded` (HTTP 409) and preserves the stored policies. These limits match the
[AWS IAM quotas](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html).
When CloudFormation renames an inline policy, Floci releases its tracked old name on
retained principals before writing the replacement. Failed updates restore the captured
previous policies, including historical documents saved before these limits were enforced.
Compensation checks the current principal and document before restoration. Historical
oversized documents can be restored only when the other policies still match their captured
state. A failed compensation is reported as a rollback failure.
### Instance Profiles
| Action | Description |
@@ -5,18 +5,20 @@ 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.services.iam.IamService.InlinePolicyChange;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* CloudFormation provisioning for {@code AWS::IAM::Policy}, which in AWS is an <em>inline</em>
@@ -90,36 +92,44 @@ public class IamPolicyCfnProvisioner implements CfnResourceProvisioner {
List<String> roleTargets = new ArrayList<>();
List<String> userTargets = new ArrayList<>();
List<String> groupTargets = new ArrayList<>();
List<InlinePolicyUndo> writtenPolicies = new ArrayList<>();
List<InlinePolicyUndo> removedPolicies = new ArrayList<>();
try {
List<String> desiredRoles = resolveInlineTargets(props, "Roles", engine);
List<String> desiredUsers = resolveInlineTargets(props, "Users", engine);
List<String> desiredGroups = resolveInlineTargets(props, "Groups", engine);
cleanupPendingInlinePolicies(r);
putInlinePolicy(props, "Roles", engine, roleTargets,
principal -> iamService.putRolePolicy(principal, name, doc));
putInlinePolicy(props, "Users", engine, userTargets,
principal -> iamService.putUserPolicy(principal, name, doc));
putInlinePolicy(props, "Groups", engine, groupTargets,
principal -> iamService.putGroupPolicy(principal, name, doc));
if (!legacyManagedPolicy && previousPolicyName != null && !previousPolicyName.equals(name)) {
removeRenamedInlinePolicies(previousRoleTargets, desiredRoles,
policyAccess("Role", previousPolicyName), removedPolicies);
removeRenamedInlinePolicies(previousUserTargets, desiredUsers,
policyAccess("User", previousPolicyName), removedPolicies);
removeRenamedInlinePolicies(previousGroupTargets, desiredGroups,
policyAccess("Group", previousPolicyName), removedPolicies);
}
putInlinePolicy(desiredRoles, roleTargets, doc,
policyAccess("Role", name), previousPolicyName != null, writtenPolicies);
putInlinePolicy(desiredUsers, userTargets, doc,
policyAccess("User", name), previousPolicyName != null, writtenPolicies);
putInlinePolicy(desiredGroups, groupTargets, doc,
policyAccess("Group", name), previousPolicyName != null, writtenPolicies);
if (legacyManagedPolicy) {
migrateLegacyManagedPolicy(r);
} else {
deleteRemovedInlinePolicies(previousRoleTargets, roleTargets,
previousPolicyName, policyName,
principal -> iamService.deleteRolePolicy(principal, previousPolicyName));
previousPolicyName, policyAccess("Role", previousPolicyName), removedPolicies);
deleteRemovedInlinePolicies(previousUserTargets, userTargets,
previousPolicyName, policyName,
principal -> iamService.deleteUserPolicy(principal, previousPolicyName));
previousPolicyName, policyAccess("User", previousPolicyName), removedPolicies);
deleteRemovedInlinePolicies(previousGroupTargets, groupTargets,
previousPolicyName, policyName,
principal -> iamService.deleteGroupPolicy(principal, previousPolicyName));
previousPolicyName, policyAccess("Group", previousPolicyName), removedPolicies);
}
} catch (RuntimeException failure) {
if (previousPolicyName == null) {
r.setPhysicalId(policyName);
recordInlinePolicyTargets(r, roleTargets, userTargets, groupTargets);
} else {
rollbackInlinePolicyUpdate(r, failure, previousPolicyName, policyName,
previousRoleTargets, previousUserTargets, previousGroupTargets,
roleTargets, userTargets, groupTargets);
rollbackInlinePolicyUpdate(r, failure, policyName, writtenPolicies, removedPolicies);
}
throw failure;
}
@@ -152,18 +162,70 @@ public class IamPolicyCfnProvisioner implements CfnResourceProvisioner {
return node != null && node.isArray() && !node.isEmpty();
}
private void putInlinePolicy(JsonNode props, String propName, CloudFormationTemplateEngine engine,
List<String> successfulTargets, Consumer<String> op) {
if (props == null || !props.has(propName)) {
return;
private record InlinePolicyAccess(String kind, String name, BiConsumer<String, String> write,
BiFunction<String, String, InlinePolicyChange> update,
Function<String, InlinePolicyChange> remove) {}
private record InlinePolicyUndo(InlinePolicyAccess access, String principal, InlinePolicyChange change) {
void restore() {
change.rollback().run();
}
for (JsonNode entry : props.get(propName)) {
String name = engine.resolve(entry);
if (name != null && !name.isBlank()) {
op.accept(name);
successfulTargets.add(name);
}
private InlinePolicyAccess policyAccess(String kind, String name) {
return switch (kind) {
case "Role" -> new InlinePolicyAccess(kind, name,
(principal, document) -> iamService.putRolePolicy(principal, name, document),
(principal, document) -> iamService.putRolePolicyWithRollback(principal, name, document),
principal -> iamService.deleteRolePolicyWithRollback(principal, name));
case "User" -> new InlinePolicyAccess(kind, name,
(principal, document) -> iamService.putUserPolicy(principal, name, document),
(principal, document) -> iamService.putUserPolicyWithRollback(principal, name, document),
principal -> iamService.deleteUserPolicyWithRollback(principal, name));
case "Group" -> new InlinePolicyAccess(kind, name,
(principal, document) -> iamService.putGroupPolicy(principal, name, document),
(principal, document) -> iamService.putGroupPolicyWithRollback(principal, name, document),
principal -> iamService.deleteGroupPolicyWithRollback(principal, name));
default -> throw new IllegalArgumentException(kind);
};
}
private List<String> resolveInlineTargets(JsonNode props, String propName, CloudFormationTemplateEngine engine) {
List<String> targets = new ArrayList<>();
if (props != null && props.has(propName)) {
for (JsonNode entry : props.get(propName)) {
String name = engine.resolve(entry);
if (name != null && !name.isBlank()) {
targets.add(name);
}
}
}
return targets;
}
private void putInlinePolicy(List<String> targets, List<String> successfulTargets,
String document, InlinePolicyAccess access,
boolean updating, List<InlinePolicyUndo> writtenPolicies) {
for (String name : targets) {
if (updating) {
InlinePolicyChange change = access.update().apply(name, document);
writtenPolicies.add(new InlinePolicyUndo(access, name, change));
} else {
access.write().accept(name, document);
}
successfulTargets.add(name);
}
}
private void removeRenamedInlinePolicies(String previousTargets, List<String> desiredTargets,
InlinePolicyAccess access, List<InlinePolicyUndo> removedPolicies) {
Set<String> retainedTargets = new HashSet<>(desiredTargets);
detachInline(previousTargets, name -> {
if (retainedTargets.contains(name)) {
InlinePolicyChange change = access.remove().apply(name);
removedPolicies.add(new InlinePolicyUndo(access, name, change));
}
});
}
private void recordInlinePolicyTargets(StackResource resource, List<String> roleTargets,
@@ -178,44 +240,42 @@ public class IamPolicyCfnProvisioner implements CfnResourceProvisioner {
}
private void rollbackInlinePolicyUpdate(StackResource resource, RuntimeException failure,
String previousPolicyName, String currentPolicyName,
String previousRoleTargets, String previousUserTargets,
String previousGroupTargets, List<String> appliedRoleTargets,
List<String> appliedUserTargets, List<String> appliedGroupTargets) {
List<String> pendingRoles = rollbackAppliedInlinePolicies(
failure, previousRoleTargets, appliedRoleTargets, previousPolicyName, currentPolicyName,
principal -> iamService.deleteRolePolicy(principal, currentPolicyName));
List<String> pendingUsers = rollbackAppliedInlinePolicies(
failure, previousUserTargets, appliedUserTargets, previousPolicyName, currentPolicyName,
principal -> iamService.deleteUserPolicy(principal, currentPolicyName));
List<String> pendingGroups = rollbackAppliedInlinePolicies(
failure, previousGroupTargets, appliedGroupTargets, previousPolicyName, currentPolicyName,
principal -> iamService.deleteGroupPolicy(principal, currentPolicyName));
String currentPolicyName, List<InlinePolicyUndo> writtenPolicies,
List<InlinePolicyUndo> removedPolicies) {
List<String> pendingRoles = new ArrayList<>();
List<String> pendingUsers = new ArrayList<>();
List<String> pendingGroups = new ArrayList<>();
// Undo puts first so restored old names do not compete with this attempt's new names for quota.
List<InlinePolicyUndo> rollback = new ArrayList<>(writtenPolicies.reversed());
rollback.addAll(removedPolicies.reversed());
boolean restored = true;
for (InlinePolicyUndo undo : rollback) {
String description = "restore inline policy " + undo.access().name() + " on " + undo.principal();
if (!CfnRollback.attemptIamCleanup(failure, description, undo::restore)) {
restored = false;
Throwable[] cleanupFailures = failure.getSuppressed();
Throwable cleanupFailure = cleanupFailures[cleanupFailures.length - 1];
boolean ownershipChanged = cleanupFailure instanceof AwsException aws
&& "ConcurrentModification".equals(aws.getErrorCode());
if (!ownershipChanged && undo.change().previousDocument() == null
&& currentPolicyName.equals(undo.access().name())) {
switch (undo.access().kind()) {
case "Role" -> pendingRoles.add(undo.principal());
case "User" -> pendingUsers.add(undo.principal());
case "Group" -> pendingGroups.add(undo.principal());
default -> throw new IllegalArgumentException(undo.access().kind());
}
}
}
}
recordPendingInlineCleanup(resource, currentPolicyName, pendingRoles, pendingUsers, pendingGroups);
resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true");
}
private List<String> rollbackAppliedInlinePolicies(RuntimeException failure, String previousTargets,
List<String> appliedTargets, String previousPolicyName,
String currentPolicyName, Consumer<String> cleanup) {
Set<String> previous = inlineTargetSet(previousTargets);
List<String> rollbackTargets = new ArrayList<>();
for (String target : new LinkedHashSet<>(appliedTargets)) {
if (!previousPolicyName.equals(currentPolicyName) || !previous.contains(target)) {
rollbackTargets.add(target);
}
resource.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR);
if (restored) {
resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true");
} else {
resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR,
"Could not restore inline policies after failed update: " + failure.getMessage());
}
Collections.reverse(rollbackTargets);
List<String> pendingTargets = new ArrayList<>();
for (String target : rollbackTargets) {
String description = "delete inline policy " + currentPolicyName + " from " + target;
if (!CfnRollback.attemptIamCleanup(failure, description, () -> detachInline(target, cleanup))) {
pendingTargets.add(target);
}
}
Collections.reverse(pendingTargets);
return pendingTargets;
}
private void recordPendingInlineCleanup(StackResource resource, String policyName,
@@ -248,27 +308,21 @@ public class IamPolicyCfnProvisioner implements CfnResourceProvisioner {
}
private void deleteRemovedInlinePolicies(String previousTargets, List<String> currentTargets,
String previousPolicyName, String currentPolicyName,
Consumer<String> op) {
String previousPolicyName,
InlinePolicyAccess access, List<InlinePolicyUndo> removedPolicies) {
if (previousPolicyName == null) {
return;
}
Set<String> retainedTargets = new HashSet<>(currentTargets);
detachInline(previousTargets, name -> {
if (!previousPolicyName.equals(currentPolicyName) || !retainedTargets.contains(name)) {
op.accept(name);
if (!retainedTargets.contains(name)) {
InlinePolicyChange change = access.remove().apply(name);
removedPolicies.add(new InlinePolicyUndo(access, name, change));
}
});
}
private Set<String> inlineTargetSet(String targets) {
if (targets == null || targets.isBlank()) {
return Set.of();
}
return new HashSet<>(Arrays.asList(targets.split("\n")));
}
private void detachInline(String targets, Consumer<String> op) {
private static void detachInline(String targets, Consumer<String> op) {
if (targets == null || targets.isBlank()) {
return;
}
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
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.AccessKey;
import io.github.hectorvent.floci.services.iam.model.IamUser;
import jakarta.enterprise.context.ApplicationScoped;
@@ -15,6 +16,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
@@ -42,6 +44,8 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
this.iamService = iamService;
}
private record InlinePolicyUndo(String name, InlinePolicyChange change) {}
@Override
public Set<String> resourceTypes() {
return Set.of("AWS::IAM::User");
@@ -130,7 +134,7 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
LinkedHashSet<String> attachedByThisAttempt = new LinkedHashSet<>();
LinkedHashSet<String> detachedByThisAttempt = new LinkedHashSet<>();
LinkedHashSet<String> inlineWrittenByThisAttempt = new LinkedHashSet<>();
LinkedHashSet<String> inlineRemovedByThisAttempt = new LinkedHashSet<>();
List<InlinePolicyUndo> inlineChanges = new ArrayList<>();
boolean tagMutationStarted = false;
final String pathToRestore = priorPath;
@@ -165,6 +169,7 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
}
}
Map<String, String> desiredInlinePolicies = new LinkedHashMap<>();
if (props != null && props.has("Policies")) {
for (JsonNode policy : props.get("Policies")) {
String declaredName = ctx.resolveOptional(policy, "PolicyName");
@@ -179,19 +184,23 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
"Inline policy '" + policyName + "' on user " + resolvedUserName
+ " has no PolicyDocument.", 400);
}
iamService.putUserPolicy(resolvedUserName, policyName,
ctx.engine().resolveJsonAttributeStrict(document));
inlineWrittenByThisAttempt.add(policyName);
desiredInlinePolicies.put(policyName, ctx.engine().resolveJsonAttributeStrict(document));
}
}
for (String stale : previousInlineNames) {
if (!inlineWrittenByThisAttempt.contains(stale)
&& originalInlinePolicies.containsKey(stale)) {
iamService.deleteUserPolicy(resolvedUserName, stale);
inlineRemovedByThisAttempt.add(stale);
if (originalInlinePolicies.containsKey(stale)
&& !originalInlinePolicies.get(stale).equals(desiredInlinePolicies.get(stale))) {
inlineChanges.add(new InlinePolicyUndo(stale,
iamService.deleteUserPolicyWithRollback(resolvedUserName, stale)));
}
}
// Release replaced documents before writing, including policies that retain their names.
for (Map.Entry<String, String> policy : desiredInlinePolicies.entrySet()) {
inlineChanges.add(new InlinePolicyUndo(policy.getKey(), iamService.putUserPolicyWithRollback(
resolvedUserName, policy.getKey(), policy.getValue())));
inlineWrittenByThisAttempt.add(policy.getKey());
}
for (String stale : previousManagedArns) {
if (!managedPolicyArns.contains(stale) && originalPolicyArns.contains(stale)) {
iamService.detachUserPolicy(resolvedUserName, stale);
@@ -240,17 +249,6 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
cleanupSucceeded = false;
}
}
for (String policyName : inlineRemovedByThisAttempt) {
String prior = originalInlinePolicies.get(policyName);
if (prior == null) {
continue;
}
if (!CfnRollback.attemptIamCleanup(failure,
"restore inline policy " + policyName + " on user " + resolvedUserName,
() -> iamService.putUserPolicy(resolvedUserName, policyName, prior))) {
cleanupSucceeded = false;
}
}
for (String policyArn : detachedByThisAttempt) {
if (!CfnRollback.attemptIamCleanup(failure,
"reattach policy " + policyArn + " to user " + resolvedUserName,
@@ -259,19 +257,11 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
}
}
List<String> inlineRollback = new ArrayList<>(inlineWrittenByThisAttempt);
Collections.reverse(inlineRollback);
for (String policyName : inlineRollback) {
String prior = originalInlinePolicies.get(policyName);
String cleanupDescription = (prior == null ? "remove" : "restore")
+ " inline policy " + policyName + " on user " + resolvedUserName;
if (!CfnRollback.attemptIamCleanup(failure, cleanupDescription, () -> {
if (prior == null) {
iamService.deleteUserPolicy(resolvedUserName, policyName);
} else {
iamService.putUserPolicy(resolvedUserName, policyName, prior);
}
})) {
for (InlinePolicyUndo undo : inlineChanges.reversed()) {
String operation = undo.change().previousDocument() == null ? "remove" : "restore";
if (!CfnRollback.attemptIamCleanup(failure,
operation + " inline policy " + undo.name() + " on user " + resolvedUserName,
undo.change().rollback())) {
cleanupSucceeded = false;
}
}
@@ -325,6 +315,11 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
}
}
if (!createdUser && !cleanupSucceeded) {
r.getAttributes().remove(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR);
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR,
"Could not restore user after failed update: " + failure.getMessage());
}
throw failure;
}
@@ -104,6 +104,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public static final String FEDERATION_TOKEN_SESSION_MESSAGE =
"Cannot call GetFederationToken with session credentials";
private static final int USER_INLINE_POLICY_SIZE_LIMIT = 2_048;
private static final int GROUP_INLINE_POLICY_SIZE_LIMIT = 5_120;
private static final int ROLE_INLINE_POLICY_SIZE_LIMIT = 10_240;
private static final Logger LOG = Logger.getLogger(IamService.class);
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
@@ -771,61 +773,63 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
public void deleteUser(String userName) {
IamUser user = getUser(userName);
if (!user.getAttachedPolicyArns().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must detach all policies first.", 409);
}
if (!user.getGroupNames().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must remove from all groups first.", 409);
}
if (loginProfiles.get(userName).isPresent()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must delete login profile first.", 409);
}
if (!user.getInlinePolicies().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must delete policies first.", 409);
}
if (!userAccessKeys(userName).isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must delete access keys first.", 409);
}
// Both locks are held across the delete rather than just the checks: UploadSigningCertificate
// UploadSigningCertificate and EnableMFADevice confirm the user under their own lock, so
// none of them can interleave into a credential owned by a deleted user. Taken in this
// order here and in UpdateUser, and nowhere else in more than one, so it cannot deadlock.
synchronized (serviceCredentialLock) {
// AWS lists these among the items to remove first, under their CodeCommit
// name: "Git credentials (DeleteServiceSpecificCredential)". Unlike the
// cases above it has no message of its own: AWS falls back to the generic
// referenced-objects wording here.
if (!userServiceCredentials(userName).isEmpty()) {
synchronized (resourceNameLock) {
IamUser user = getUser(userName);
if (!user.getAttachedPolicyArns().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must remove referenced objects first.", 409);
"Cannot delete entity, must detach all policies first.", 409);
}
synchronized (sshPublicKeyLock) {
if (!userSshPublicKeys(userName).isEmpty()) {
if (!user.getGroupNames().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must remove from all groups first.", 409);
}
if (loginProfiles.get(userName).isPresent()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must delete login profile first.", 409);
}
if (!user.getInlinePolicies().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must delete policies first.", 409);
}
if (!userAccessKeys(userName).isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must delete access keys first.", 409);
}
// Both locks are held across the delete rather than just the checks: UploadSigningCertificate
// UploadSigningCertificate and EnableMFADevice confirm the user under their own lock, so
// none of them can interleave into a credential owned by a deleted user. Taken in this
// order here and in UpdateUser, and nowhere else in more than one, so it cannot deadlock.
synchronized (serviceCredentialLock) {
// AWS lists these among the items to remove first, under their CodeCommit
// name: "Git credentials (DeleteServiceSpecificCredential)". Unlike the
// cases above it has no message of its own: AWS falls back to the generic
// referenced-objects wording here.
if (!userServiceCredentials(userName).isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must delete SSH public keys first.", 409);
"Cannot delete entity, must remove referenced objects first.", 409);
}
synchronized (signingCertificateLock) {
if (!userSigningCertificates(userName).isEmpty()) {
synchronized (sshPublicKeyLock) {
if (!userSshPublicKeys(userName).isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must delete signing certificates first.", 409);
"Cannot delete entity, must delete SSH public keys first.", 409);
}
synchronized (mfaDeviceLock) {
if (!mfaDevicesForUser(userName).isEmpty()) {
synchronized (signingCertificateLock) {
if (!userSigningCertificates(userName).isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must deactivate MFA device first.", 409);
"Cannot delete entity, must delete signing certificates first.", 409);
}
synchronized (mfaDeviceLock) {
if (!mfaDevicesForUser(userName).isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must deactivate MFA device first.", 409);
}
users.delete(userName);
}
users.delete(userName);
}
}
}
LOG.infov("Deleted IAM user: {0}", userName);
}
LOG.infov("Deleted IAM user: {0}", userName);
}
public List<IamUser> listUsers(String pathPrefix) {
@@ -1029,17 +1033,19 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
public void deleteGroup(String groupName) {
IamGroup group = getGroup(groupName);
if (!group.getAttachedPolicyArns().isEmpty() || !group.getInlinePolicies().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must detach all policies first.", 409);
synchronized (resourceNameLock) {
IamGroup group = getGroup(groupName);
if (!group.getAttachedPolicyArns().isEmpty() || !group.getInlinePolicies().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must detach all policies first.", 409);
}
if (!group.getUserNames().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must remove all users from group first.", 409);
}
groups.delete(groupName);
LOG.infov("Deleted IAM group: {0}", groupName);
}
if (!group.getUserNames().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must remove all users from group first.", 409);
}
groups.delete(groupName);
LOG.infov("Deleted IAM group: {0}", groupName);
}
public List<IamGroup> listGroups(String pathPrefix) {
@@ -1211,15 +1217,17 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
public void deleteRole(String roleName) {
validateRoleName(roleName);
IamRole role = getRole(roleName);
requireNotServiceLinked(role, roleName);
if (!role.getAttachedPolicyArns().isEmpty() || !role.getInlinePolicies().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must detach all policies first.", 409);
synchronized (resourceNameLock) {
validateRoleName(roleName);
IamRole role = getRole(roleName);
requireNotServiceLinked(role, roleName);
if (!role.getAttachedPolicyArns().isEmpty() || !role.getInlinePolicies().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must detach all policies first.", 409);
}
roles.delete(roleName);
LOG.infov("Deleted IAM role: {0}", roleName);
}
roles.delete(roleName);
LOG.infov("Deleted IAM role: {0}", roleName);
}
/**
@@ -1631,9 +1639,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
summary.put("AttachedPoliciesPerUserQuota", 10L);
summary.put("AttachedPoliciesPerGroupQuota", 10L);
summary.put("AttachedPoliciesPerRoleQuota", 20L);
summary.put("GroupPolicySizeQuota", 5120L);
summary.put("UserPolicySizeQuota", 2048L);
summary.put("RolePolicySizeQuota", 10240L);
summary.put("GroupPolicySizeQuota", (long) GROUP_INLINE_POLICY_SIZE_LIMIT);
summary.put("UserPolicySizeQuota", (long) USER_INLINE_POLICY_SIZE_LIMIT);
summary.put("RolePolicySizeQuota", (long) ROLE_INLINE_POLICY_SIZE_LIMIT);
summary.put("AccessKeysPerUserQuota", 2L);
summary.put("SigningCertificatesPerUserQuota", 2L);
summary.put("ServerCertificates", (long) serverCertificates.scan(k -> true).size());
@@ -1884,9 +1892,16 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
// =========================================================================
public void putUserPolicy(String userName, String policyName, String policyDocument) {
IamUser user = getUser(userName);
user.getInlinePolicies().put(policyName, policyDocument);
users.put(userName, user);
synchronized (resourceNameLock) {
IamUser user = getUser(userName);
Map<String, String> inlinePolicies = user.getInlinePolicies();
synchronized (inlinePolicies) {
checkInlinePolicyQuota(inlinePolicies, policyName, policyDocument,
USER_INLINE_POLICY_SIZE_LIMIT, "user " + userName);
inlinePolicies.put(policyName, policyDocument);
users.put(userName, user);
}
}
}
public String getUserPolicy(String userName, String policyName) {
@@ -1900,12 +1915,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
public void deleteUserPolicy(String userName, String policyName) {
IamUser user = getUser(userName);
if (user.getInlinePolicies().remove(policyName) == null) {
throw new AwsException("NoSuchEntity",
"Policy " + policyName + " not found for user " + userName + ".", 404);
synchronized (resourceNameLock) {
IamUser user = getUser(userName);
if (user.getInlinePolicies().remove(policyName) == null) {
throw new AwsException("NoSuchEntity",
"Policy " + policyName + " not found for user " + userName + ".", 404);
}
users.put(userName, user);
}
users.put(userName, user);
}
public List<String> listUserPolicies(String userName) {
@@ -1917,9 +1934,16 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
// =========================================================================
public void putGroupPolicy(String groupName, String policyName, String policyDocument) {
IamGroup group = getGroup(groupName);
group.getInlinePolicies().put(policyName, policyDocument);
groups.put(groupName, group);
synchronized (resourceNameLock) {
IamGroup group = getGroup(groupName);
Map<String, String> inlinePolicies = group.getInlinePolicies();
synchronized (inlinePolicies) {
checkInlinePolicyQuota(inlinePolicies, policyName, policyDocument,
GROUP_INLINE_POLICY_SIZE_LIMIT, "group " + groupName);
inlinePolicies.put(policyName, policyDocument);
groups.put(groupName, group);
}
}
}
public String getGroupPolicy(String groupName, String policyName) {
@@ -1933,12 +1957,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
public void deleteGroupPolicy(String groupName, String policyName) {
IamGroup group = getGroup(groupName);
if (group.getInlinePolicies().remove(policyName) == null) {
throw new AwsException("NoSuchEntity",
"Policy " + policyName + " not found for group " + groupName + ".", 404);
synchronized (resourceNameLock) {
IamGroup group = getGroup(groupName);
if (group.getInlinePolicies().remove(policyName) == null) {
throw new AwsException("NoSuchEntity",
"Policy " + policyName + " not found for group " + groupName + ".", 404);
}
groups.put(groupName, group);
}
groups.put(groupName, group);
}
public List<String> listGroupPolicies(String groupName) {
@@ -1950,24 +1976,141 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
// =========================================================================
public void putRolePolicy(String roleName, String policyName, String policyDocument) {
validateRoleName(roleName);
IamRole role = getRole(roleName);
requireNotServiceLinked(role, roleName);
Map<String, String> inlinePolicies = role.getInlinePolicies();
synchronized (inlinePolicies) {
long aggregateSize = inlinePolicies.entrySet().stream()
.filter(entry -> !entry.getKey().equals(policyName))
.mapToLong(entry -> nonWhitespaceLength(entry.getValue()))
.sum() + nonWhitespaceLength(policyDocument);
if (aggregateSize > ROLE_INLINE_POLICY_SIZE_LIMIT) {
throw new AwsException("LimitExceeded",
"Maximum policy size of 10240 bytes exceeded for role " + roleName, 409);
synchronized (resourceNameLock) {
validateRoleName(roleName);
IamRole role = getRole(roleName);
requireNotServiceLinked(role, roleName);
Map<String, String> inlinePolicies = role.getInlinePolicies();
synchronized (inlinePolicies) {
checkInlinePolicyQuota(inlinePolicies, policyName, policyDocument,
ROLE_INLINE_POLICY_SIZE_LIMIT, "role " + roleName);
inlinePolicies.put(policyName, policyDocument);
roles.put(roleName, role);
}
inlinePolicies.put(policyName, policyDocument);
roles.put(roleName, role);
}
}
/**
* CloudFormation compensation captures the stored document with the write. The returned
* operation can restore that exact historical value, including policies saved before quotas
* were enforced; it cannot admit a caller-supplied oversized replacement.
*/
public InlinePolicyChange putUserPolicyWithRollback(String userName, String policyName, String document) {
return changeInlinePolicy(users, userName, policyName, () -> getUser(userName),
IamUser::getUserId,
IamUser::getInlinePolicies, () -> putUserPolicy(userName, policyName, document),
document, USER_INLINE_POLICY_SIZE_LIMIT);
}
public InlinePolicyChange deleteUserPolicyWithRollback(String userName, String policyName) {
return changeInlinePolicy(users, userName, policyName, () -> getUser(userName),
IamUser::getUserId,
IamUser::getInlinePolicies, () -> deleteUserPolicy(userName, policyName),
null, USER_INLINE_POLICY_SIZE_LIMIT);
}
public InlinePolicyChange putGroupPolicyWithRollback(String groupName, String policyName, String document) {
return changeInlinePolicy(groups, groupName, policyName, () -> getGroup(groupName),
IamGroup::getGroupId,
IamGroup::getInlinePolicies, () -> putGroupPolicy(groupName, policyName, document),
document, GROUP_INLINE_POLICY_SIZE_LIMIT);
}
public InlinePolicyChange deleteGroupPolicyWithRollback(String groupName, String policyName) {
return changeInlinePolicy(groups, groupName, policyName, () -> getGroup(groupName),
IamGroup::getGroupId,
IamGroup::getInlinePolicies, () -> deleteGroupPolicy(groupName, policyName),
null, GROUP_INLINE_POLICY_SIZE_LIMIT);
}
public InlinePolicyChange putRolePolicyWithRollback(String roleName, String policyName, String document) {
return changeInlinePolicy(roles, roleName, policyName, () -> getValidatedRole(roleName),
IamRole::getRoleId,
IamRole::getInlinePolicies, () -> putRolePolicy(roleName, policyName, document),
document, ROLE_INLINE_POLICY_SIZE_LIMIT);
}
public InlinePolicyChange deleteRolePolicyWithRollback(String roleName, String policyName) {
return changeInlinePolicy(roles, roleName, policyName, () -> getValidatedRole(roleName),
IamRole::getRoleId,
IamRole::getInlinePolicies, () -> deleteRolePolicy(roleName, policyName),
null, ROLE_INLINE_POLICY_SIZE_LIMIT);
}
private <T> InlinePolicyChange changeInlinePolicy(StorageBackend<String, T> store, String principal,
String policyName, Supplier<T> lookup, Function<T, String> identity,
Function<T, Map<String, String>> policies,
Runnable change, String expectedDocument, int limit) {
synchronized (resourceNameLock) {
T original = lookup.get();
String account = regionResolver.getAccountId();
String principalId = identity.apply(original);
Map<String, String> inlinePolicies = policies.apply(original);
synchronized (inlinePolicies) {
String previousDocument = inlinePolicies.get(policyName);
Map<String, String> previousSiblings = new LinkedHashMap<>(inlinePolicies);
previousSiblings.remove(policyName);
change.run();
return new InlinePolicyChange(previousDocument, () -> {
synchronized (resourceNameLock) {
if (!account.equals(regionResolver.getAccountId())) {
throw inlinePolicyRollbackConflict(principal, policyName);
}
T current = store.get(principal).orElseThrow(() ->
inlinePolicyRollbackConflict(principal, policyName));
if (!Objects.equals(principalId, identity.apply(current))) {
throw inlinePolicyRollbackConflict(principal, policyName);
}
Map<String, String> currentPolicies = policies.apply(current);
synchronized (currentPolicies) {
if (!Objects.equals(expectedDocument, currentPolicies.get(policyName))) {
throw inlinePolicyRollbackConflict(principal, policyName);
}
if (previousDocument != null
&& inlinePolicySize(currentPolicies, policyName, previousDocument) > limit) {
Map<String, String> currentSiblings = new LinkedHashMap<>(currentPolicies);
currentSiblings.remove(policyName);
if (!previousSiblings.equals(currentSiblings)) {
throw inlinePolicyRollbackConflict(principal, policyName);
}
}
if (previousDocument == null) {
currentPolicies.remove(policyName);
} else {
currentPolicies.put(policyName, previousDocument);
}
store.put(principal, current);
}
}
});
}
}
}
public record InlinePolicyChange(String previousDocument, Runnable rollback) {}
private static AwsException inlinePolicyRollbackConflict(String principal, String policyName) {
return new AwsException("ConcurrentModification",
"Cannot restore inline policy " + policyName + " on " + principal
+ " because its principal or document changed after the update.", 409);
}
private static void checkInlinePolicyQuota(Map<String, String> inlinePolicies, String policyName,
String policyDocument, int limit, String principal) {
long aggregateSize = inlinePolicySize(inlinePolicies, policyName, policyDocument);
if (aggregateSize > limit) {
throw new AwsException("LimitExceeded",
"Maximum policy size of " + limit + " bytes exceeded for " + principal, 409);
}
}
private static long inlinePolicySize(Map<String, String> policies, String name, String document) {
return policies.entrySet().stream()
.filter(entry -> !entry.getKey().equals(name))
.mapToLong(entry -> nonWhitespaceLength(entry.getValue()))
.sum() + nonWhitespaceLength(document);
}
private static int nonWhitespaceLength(String policyDocument) {
int size = 0;
for (int i = 0; i < policyDocument.length(); i++) {
@@ -1991,14 +2134,16 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
public void deleteRolePolicy(String roleName, String policyName) {
validateRoleName(roleName);
IamRole role = getRole(roleName);
requireNotServiceLinked(role, roleName);
if (role.getInlinePolicies().remove(policyName) == null) {
throw new AwsException("NoSuchEntity",
"Policy " + policyName + " not found for role " + roleName + ".", 404);
synchronized (resourceNameLock) {
validateRoleName(roleName);
IamRole role = getRole(roleName);
requireNotServiceLinked(role, roleName);
if (role.getInlinePolicies().remove(policyName) == null) {
throw new AwsException("NoSuchEntity",
"Policy " + policyName + " not found for role " + roleName + ".", 404);
}
roles.put(roleName, role);
}
roles.put(roleName, role);
}
public List<String> listRolePolicies(String roleName) {
@@ -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);
}
});
}
}