diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamManagedPolicyCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamManagedPolicyCfnProvisioner.java
index 9451555f8a..16c10df645 100644
--- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamManagedPolicyCfnProvisioner.java
+++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamManagedPolicyCfnProvisioner.java
@@ -4,29 +4,36 @@ import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.iam.IamService;
+import io.floci.aws.services.iam.model.IamGroup;
import io.floci.aws.services.iam.model.IamPolicy;
+import io.floci.aws.services.iam.model.IamRole;
+import io.floci.aws.services.iam.model.IamUser;
import io.floci.aws.services.iam.model.PolicyVersion;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.function.Function;
import java.util.stream.Collectors;
/**
* CloudFormation provisioning for {@code AWS::IAM::ManagedPolicy}, a standalone customer-managed
- * policy with an ARN that must be detached from its roles before deletion. {@code Ref} and
+ * policy with an ARN that must be detached from its principals before deletion. {@code Ref} and
* {@code Fn::GetAtt PolicyArn} return the policy ARN. A managed policy name is account-global, so
* the physical name is honoured verbatim from {@code ManagedPolicyName} when set.
*
*
On {@code UpdateStack} with an unchanged name the policy this stack provisioned already
* exists, so {@code PolicyDocument} is applied as a new default version in place (pruning the
- * oldest versions to stay under IAM's five-version cap) and roles no longer listed are detached,
+ * oldest versions to stay under IAM's five-version cap) and principals no longer listed are detached,
* matching CloudFormation. A failure mid-update restores the version and attachment state this pass
* changed rather than leaving the policy half-migrated.
*/
@@ -55,14 +62,31 @@ public class IamManagedPolicyCfnProvisioner implements CfnResourceProvisioner {
}
String document = ctx.resolvePolicyDocument(props);
List roleNames = ctx.resolveStringList(props, "Roles");
+ List userNames = ctx.resolveStringList(props, "Users");
+ List groupNames = ctx.resolveStringList(props, "Groups");
String existingArn = r.getPhysicalId();
+ // Check every declared target before creating a policy or publishing a new version.
+ List declaredRoles = roleNames.stream().map(iamService::getRole).toList();
+ List declaredUsers = userNames.stream().map(iamService::getUser).toList();
+ List declaredGroups = groupNames.stream().map(iamService::getGroup).toList();
+ String roleTargetIds = targetIds(declaredRoles, IamRole::getRoleId);
+ String userTargetIds = targetIds(declaredUsers, IamUser::getUserId);
+ String groupTargetIds = targetIds(declaredGroups, IamGroup::getGroupId);
+
IamPolicy policy;
+ IamService.PolicyEntities priorEntities = null;
boolean createdPolicy = false;
String previousDefaultVersionId = null;
PolicyVersion createdVersionForRollback = null;
List prunedVersionsForRollback = new ArrayList<>();
- List detachedObsoleteRoles = new ArrayList<>();
+ AttachmentChanges changes = new AttachmentChanges();
+ String previousRoleTargets = r.getAttributes().get("ManagedPolicyRoleTargets");
+ String previousUserTargets = r.getAttributes().get("ManagedPolicyUserTargets");
+ String previousGroupTargets = r.getAttributes().get("ManagedPolicyGroupTargets");
+ String previousRoleTargetIds = r.getAttributes().get("ManagedPolicyRoleTargetIds");
+ String previousUserTargetIds = r.getAttributes().get("ManagedPolicyUserTargetIds");
+ String previousGroupTargetIds = r.getAttributes().get("ManagedPolicyGroupTargetIds");
try {
policy = iamService.createPolicy(policyName, "/", null, document, Map.of());
createdPolicy = true;
@@ -87,6 +111,7 @@ public class IamManagedPolicyCfnProvisioner implements CfnResourceProvisioner {
if (policyId == null || !policyId.equals(policy.getPolicyId())) {
throw e;
}
+ priorEntities = iamService.listEntitiesForPolicy(existingArn);
previousDefaultVersionId = policy.getDefaultVersionId();
// IAM caps a managed policy at 5 versions; prune the oldest non-default ones the way
// CloudFormation does, so repeated stack updates never die on LimitExceeded.
@@ -103,28 +128,38 @@ public class IamManagedPolicyCfnProvisioner implements CfnResourceProvisioner {
iamService.deletePolicyVersion(existingArn, pruned.getVersionId());
}
createdVersionForRollback = iamService.createPolicyVersion(existingArn, document, true);
- // Roles this stack attached on the previous pass but no longer listed in the template
- // are detached, matching CloudFormation's update semantics.
- String previousTargets = r.getAttributes().get("ManagedPolicyRoleTargets");
- if (previousTargets != null && !previousTargets.isBlank()) {
- for (String previousRole : previousTargets.split("\n")) {
- if (!roleNames.contains(previousRole)) {
- try {
- iamService.detachRolePolicy(previousRole, existingArn);
- detachedObsoleteRoles.add(previousRole);
- } catch (AwsException detachFailure) {
- // Update is idempotent like the delete path: the attachment can already
- // be gone on a retry, but other failures must surface and still restore
- // the version/attachments this pass changed, the same as a failure in
- // the attach loop below (this loop runs first, so that loop's own catch
- // never sees this failure).
- if (!"NoSuchEntity".equals(detachFailure.getErrorCode())) {
- restoreOnUpdateFailure(detachFailure, r, existingArn,
- false, Set.of(), detachedObsoleteRoles,
- previousDefaultVersionId, createdVersionForRollback,
- prunedVersionsForRollback);
- throw detachFailure;
- }
+ // Targets this stack attached on the previous pass but no longer listed in the
+ // template are detached, matching CloudFormation's update semantics.
+ List detachActions = List.of(
+ new PrincipalDetachAction(IamManagedPolicyDeletes.recordedTargets(
+ previousRoleTargets, previousRoleTargetIds, priorEntities.roles(),
+ IamRole::getRoleId, IamRole::getRoleName),
+ roleNames, iamService::detachRolePolicy, changes.detachedRoles),
+ new PrincipalDetachAction(IamManagedPolicyDeletes.recordedTargets(
+ previousUserTargets, previousUserTargetIds, priorEntities.users(),
+ IamUser::getUserId, IamUser::getUserName),
+ userNames, iamService::detachUserPolicy, changes.detachedUsers),
+ new PrincipalDetachAction(IamManagedPolicyDeletes.recordedTargets(
+ previousGroupTargets, previousGroupTargetIds, priorEntities.groups(),
+ IamGroup::getGroupId, IamGroup::getGroupName),
+ groupNames, iamService::detachGroupPolicy, changes.detachedGroups));
+ for (PrincipalDetachAction action : detachActions) {
+ for (String previousName : action.previousNames()) {
+ if (action.desiredNames().contains(previousName)) {
+ continue;
+ }
+ try {
+ action.detach().accept(previousName, existingArn);
+ action.detachedNames().add(previousName);
+ } catch (AwsException detachFailure) {
+ if (!"NoSuchEntity".equals(detachFailure.getErrorCode())) {
+ restoreOnUpdateFailure(detachFailure, r, existingArn,
+ false, changes,
+ previousRoleTargets, previousUserTargets, previousGroupTargets,
+ previousRoleTargetIds, previousUserTargetIds, previousGroupTargetIds,
+ previousDefaultVersionId, createdVersionForRollback,
+ prunedVersionsForRollback);
+ throw detachFailure;
}
}
}
@@ -142,25 +177,50 @@ public class IamManagedPolicyCfnProvisioner implements CfnResourceProvisioner {
r.getAttributes().put("PolicyArn", policy.getArn());
r.getAttributes().put("DefaultVersionId", policy.getDefaultVersionId());
r.getAttributes().put("ManagedPolicyRoleTargets", String.join("\n", roleNames));
+ r.getAttributes().put("ManagedPolicyUserTargets", String.join("\n", userNames));
+ r.getAttributes().put("ManagedPolicyGroupTargets", String.join("\n", groupNames));
+ putTargetIds(r, "ManagedPolicyRoleTargetIds", roleTargetIds);
+ putTargetIds(r, "ManagedPolicyUserTargetIds", userTargetIds);
+ putTargetIds(r, "ManagedPolicyGroupTargetIds", groupTargetIds);
String policyArn = policy.getArn();
// On adopt, attachments from the previous pass are not this attempt's to undo.
- Set previouslyAttached = createdPolicy
- ? Set.of()
- : iamService.listEntitiesForPolicy(policyArn).roles().stream()
- .map(role -> role.getRoleName())
+ Set previouslyAttachedRoles = priorEntities == null
+ ? Set.of() : priorEntities.roles().stream()
+ .map(IamRole::getRoleName)
+ .collect(Collectors.toSet());
+ Set previouslyAttachedUsers = priorEntities == null
+ ? Set.of() : priorEntities.users().stream()
+ .map(IamUser::getUserName)
+ .collect(Collectors.toSet());
+ Set previouslyAttachedGroups = priorEntities == null
+ ? Set.of() : priorEntities.groups().stream()
+ .map(IamGroup::getGroupName)
.collect(Collectors.toSet());
- LinkedHashSet attachedRoleNames = new LinkedHashSet<>();
try {
for (String roleName : roleNames) {
iamService.attachRolePolicy(roleName, policyArn);
- if (!previouslyAttached.contains(roleName)) {
- attachedRoleNames.add(roleName);
+ if (!previouslyAttachedRoles.contains(roleName)) {
+ changes.attachedRoles.add(roleName);
+ }
+ }
+ for (String userName : userNames) {
+ iamService.attachUserPolicy(userName, policyArn);
+ if (!previouslyAttachedUsers.contains(userName)) {
+ changes.attachedUsers.add(userName);
+ }
+ }
+ for (String groupName : groupNames) {
+ iamService.attachGroupPolicy(groupName, policyArn);
+ if (!previouslyAttachedGroups.contains(groupName)) {
+ changes.attachedGroups.add(groupName);
}
}
} catch (RuntimeException failure) {
- restoreOnUpdateFailure(failure, r, policyArn, createdPolicy, attachedRoleNames,
- detachedObsoleteRoles, previousDefaultVersionId, createdVersionForRollback,
+ restoreOnUpdateFailure(failure, r, policyArn, createdPolicy, changes,
+ previousRoleTargets, previousUserTargets, previousGroupTargets,
+ previousRoleTargetIds, previousUserTargetIds, previousGroupTargetIds,
+ previousDefaultVersionId, createdVersionForRollback,
prunedVersionsForRollback);
throw failure;
}
@@ -168,42 +228,37 @@ public class IamManagedPolicyCfnProvisioner implements CfnResourceProvisioner {
/**
* Undoes whatever this update attempt already did to the managed policy before it failed:
- * shared by the attach loop and the obsolete-role detach loop, since a detach failure can
+ * shared by the attach loop and the obsolete-target detach loops, since a detach failure can
* escape before the attach loop even runs and must still restore the version and attachment
* state already changed in this pass.
*/
private void restoreOnUpdateFailure(RuntimeException failure, StackResource r, String policyArn,
- boolean createdPolicy, Set attachedRoleNames,
- List detachedObsoleteRoles, String previousDefaultVersionId,
+ boolean createdPolicy, AttachmentChanges changes,
+ String previousRoleTargets, String previousUserTargets,
+ String previousGroupTargets,
+ String previousRoleTargetIds, String previousUserTargetIds,
+ String previousGroupTargetIds, String previousDefaultVersionId,
PolicyVersion createdVersionForRollback,
List prunedVersionsForRollback) {
- List rollbackRoles = new ArrayList<>(attachedRoleNames);
- Collections.reverse(rollbackRoles);
boolean cleanupSucceeded = true;
- for (String roleName : rollbackRoles) {
- String cleanupDescription = "detach policy " + policyArn + " from role " + roleName;
- if (!CfnRollback.attemptIamCleanup(failure, cleanupDescription,
- () -> iamService.detachRolePolicy(roleName, policyArn))) {
- cleanupSucceeded = false;
- }
- }
+ cleanupSucceeded &= attemptPrincipalCleanup(failure, policyArn, "group", changes.attachedGroups,
+ name -> iamService.detachGroupPolicy(name, policyArn), "detach");
+ cleanupSucceeded &= attemptPrincipalCleanup(failure, policyArn, "user", changes.attachedUsers,
+ name -> iamService.detachUserPolicy(name, policyArn), "detach");
+ cleanupSucceeded &= attemptPrincipalCleanup(failure, policyArn, "role", changes.attachedRoles,
+ name -> iamService.detachRolePolicy(name, policyArn), "detach");
if (createdPolicy
&& !CfnRollback.attemptIamCleanup(failure, "delete policy " + policyArn,
() -> iamService.deletePolicy(policyArn))) {
cleanupSucceeded = false;
}
- // An adopted update that fails here already replaced the default version and/or detached
- // now-obsolete roles before this attach loop ran; undo both so the failed update does not
- // leave the policy half-migrated under UPDATE_ROLLBACK_COMPLETE.
- List reattachRoles = new ArrayList<>(detachedObsoleteRoles);
- Collections.reverse(reattachRoles);
- for (String roleName : reattachRoles) {
- String cleanupDescription = "reattach policy " + policyArn + " to role " + roleName;
- if (!CfnRollback.attemptIamCleanup(failure, cleanupDescription,
- () -> iamService.attachRolePolicy(roleName, policyArn))) {
- cleanupSucceeded = false;
- }
- }
+ // An adopted update may already have detached targets and replaced the default version.
+ cleanupSucceeded &= attemptPrincipalCleanup(failure, policyArn, "group", changes.detachedGroups,
+ name -> iamService.attachGroupPolicy(name, policyArn), "reattach");
+ cleanupSucceeded &= attemptPrincipalCleanup(failure, policyArn, "user", changes.detachedUsers,
+ name -> iamService.attachUserPolicy(name, policyArn), "reattach");
+ cleanupSucceeded &= attemptPrincipalCleanup(failure, policyArn, "role", changes.detachedRoles,
+ name -> iamService.attachRolePolicy(name, policyArn), "reattach");
if (previousDefaultVersionId != null) {
String restoredVersionId = previousDefaultVersionId;
String restoreDescription = "restore default policy version " + restoredVersionId + " on " + policyArn;
@@ -235,6 +290,16 @@ public class IamManagedPolicyCfnProvisioner implements CfnResourceProvisioner {
}
if (cleanupSucceeded && createdPolicy) {
r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
+ } else if (cleanupSucceeded) {
+ restoreTargetAttribute(r, "ManagedPolicyRoleTargets", previousRoleTargets);
+ restoreTargetAttribute(r, "ManagedPolicyUserTargets", previousUserTargets);
+ restoreTargetAttribute(r, "ManagedPolicyGroupTargets", previousGroupTargets);
+ restoreTargetAttribute(r, "ManagedPolicyRoleTargetIds", previousRoleTargetIds);
+ restoreTargetAttribute(r, "ManagedPolicyUserTargetIds", previousUserTargetIds);
+ restoreTargetAttribute(r, "ManagedPolicyGroupTargetIds", previousGroupTargetIds);
+ if (previousDefaultVersionId != null) {
+ r.getAttributes().put("DefaultVersionId", previousDefaultVersionId);
+ }
}
if (!cleanupSucceeded) {
// A compensating call above failed (added as a suppressed exception on failure): the
@@ -247,8 +312,61 @@ public class IamManagedPolicyCfnProvisioner implements CfnResourceProvisioner {
}
}
+ private static void restoreTargetAttribute(StackResource resource, String key, String previousValue) {
+ if (previousValue == null) {
+ resource.getAttributes().remove(key);
+ } else {
+ resource.getAttributes().put(key, previousValue);
+ }
+ }
+
+ private static String targetIds(List entities, Function idGetter) {
+ if (entities.isEmpty()
+ || entities.stream().anyMatch(entity -> entity == null || idGetter.apply(entity) == null)) {
+ return null;
+ }
+ return entities.stream().map(idGetter).collect(Collectors.joining("\n"));
+ }
+
+ private static void putTargetIds(StackResource resource, String key, String ids) {
+ if (ids == null) {
+ resource.getAttributes().remove(key);
+ } else {
+ resource.getAttributes().put(key, ids);
+ }
+ }
+
+ private static boolean attemptPrincipalCleanup(RuntimeException failure, String policyArn, String type,
+ Collection names, Consumer action,
+ String operation) {
+ boolean succeeded = true;
+ List reversed = new ArrayList<>(names);
+ Collections.reverse(reversed);
+ for (String name : reversed) {
+ String preposition = "reattach".equals(operation) ? " to " : " from ";
+ String description = operation + " policy " + policyArn + preposition + type + " " + name;
+ if (!CfnRollback.attemptIamCleanup(failure, description, () -> action.accept(name))) {
+ succeeded = false;
+ }
+ }
+ return succeeded;
+ }
+
+ private static final class AttachmentChanges {
+ private final Set attachedRoles = new LinkedHashSet<>();
+ private final Set attachedUsers = new LinkedHashSet<>();
+ private final Set attachedGroups = new LinkedHashSet<>();
+ private final List detachedRoles = new ArrayList<>();
+ private final List detachedUsers = new ArrayList<>();
+ private final List detachedGroups = new ArrayList<>();
+ }
+
+ private record PrincipalDetachAction(List previousNames, List desiredNames,
+ BiConsumer detach, List detachedNames) {
+ }
+
@Override
public void delete(StackResource resource, String region) {
- IamManagedPolicyDeletes.detachRolesAndDeletePolicy(iamService, resource);
+ IamManagedPolicyDeletes.detachAndDeletePolicy(iamService, resource);
}
}
diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamManagedPolicyDeletes.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamManagedPolicyDeletes.java
index 113865c796..1805023ea6 100644
--- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamManagedPolicyDeletes.java
+++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamManagedPolicyDeletes.java
@@ -3,17 +3,24 @@ package io.floci.aws.services.cloudformation.provisioners;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.iam.IamService;
+import io.floci.aws.services.iam.model.IamGroup;
import io.floci.aws.services.iam.model.IamRole;
+import io.floci.aws.services.iam.model.IamUser;
import org.jboss.logging.Logger;
+import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* Delete helpers shared by the two IAM policy provisioners: {@code IamManagedPolicyCfnProvisioner}
* (a customer-managed policy) and {@code IamPolicyCfnProvisioner}'s legacy path (an inline policy
- * once persisted as a managed one). Both detach a stack-owned managed policy from its roles before
- * deleting it, and both resolve those roles the same way.
+ * once persisted as a managed one). Both detach a stack-owned managed policy from its principals
+ * before deleting it, and both resolve those principals the same way.
*/
final class IamManagedPolicyDeletes {
@@ -23,44 +30,112 @@ final class IamManagedPolicyDeletes {
}
/**
- * The roles a stack-owned managed policy is attached to: the targets recorded at provision time,
- * or, for a resource persisted before that metadata existed, the roles that currently reference
- * the policy ARN.
+ * The roles a stack-owned managed policy is attached to: the targets recorded at provision
+ * time, or, for a resource persisted before that metadata existed, the roles that currently
+ * reference the policy ARN.
*/
static List roleTargets(IamService iamService, StackResource resource) {
String policyArn = resource.getPhysicalId();
String targets = resource.getAttributes().get("ManagedPolicyRoleTargets");
- if (targets == null) {
- // Stacks persisted before target metadata was introduced still need to be deletable.
- // The policy is stack-owned, so discover only roles that currently reference this ARN.
- targets = iamService.listRoles("/").stream()
- .filter(role -> role.getAttachedPolicyArns().contains(policyArn))
- .map(IamRole::getRoleName)
- .collect(Collectors.joining("\n"));
+ String ids = resource.getAttributes().get("ManagedPolicyRoleTargetIds");
+ if (targets != null) {
+ List recordedNames = splitTargets(targets);
+ if (recordedNames.isEmpty() || ids == null || ids.isBlank()) {
+ return recordedNames;
+ }
+ return recordedTargets(targets, ids,
+ iamService.listRoles("/"), IamRole::getRoleId, IamRole::getRoleName);
}
- if (targets == null || targets.isBlank()) {
+ // Stacks persisted before target metadata was introduced still need to be deletable.
+ // The policy is stack-owned, so discover only roles that currently reference this ARN.
+ List attachedRoles = iamService.listRoles("/");
+ targets = attachedRoles.stream()
+ .filter(role -> role.getAttachedPolicyArns().contains(policyArn))
+ .map(IamRole::getRoleName)
+ .collect(Collectors.joining("\n"));
+ if (targets.isBlank()) {
return List.of();
}
- return targets.lines().filter(roleName -> !roleName.isBlank()).toList();
+ return recordedTargets(targets, ids, attachedRoles,
+ IamRole::getRoleId, IamRole::getRoleName);
+ }
+
+ static List userTargets(IamService iamService, StackResource resource) {
+ return principalTargets(resource, "ManagedPolicyUserTargets", "ManagedPolicyUserTargetIds",
+ () -> iamService.listUsers("/"), IamUser::getUserId, IamUser::getUserName);
+ }
+
+ static List groupTargets(IamService iamService, StackResource resource) {
+ return principalTargets(resource, "ManagedPolicyGroupTargets", "ManagedPolicyGroupTargetIds",
+ () -> iamService.listGroups("/"), IamGroup::getGroupId, IamGroup::getGroupName);
+ }
+
+ private static List principalTargets(StackResource resource, String namesKey, String idsKey,
+ Supplier> listPrincipals,
+ Function idGetter,
+ Function nameGetter) {
+ String names = resource.getAttributes().get(namesKey);
+ String ids = resource.getAttributes().get(idsKey);
+ if (splitTargets(names).isEmpty()) {
+ return List.of();
+ }
+ return recordedTargets(names, ids, ids == null || ids.isBlank() ? List.of() : listPrincipals.get(),
+ idGetter, nameGetter);
}
/**
- * Detaches the policy from every role it targets, then deletes it. Deletion is idempotent: a
- * role, attachment or the policy itself already being gone (NoSuchEntity) is tolerated, while a
+ * Detaches the policy from every target, then deletes it. Deletion is idempotent: a principal,
+ * attachment or the policy itself already being gone (NoSuchEntity) is tolerated, while a
* permission or service failure propagates so the stack stays DELETE_FAILED.
*/
- static void detachRolesAndDeletePolicy(IamService iamService, StackResource resource) {
+ static void detachAndDeletePolicy(IamService iamService, StackResource resource) {
String policyArn = resource.getPhysicalId();
- for (String roleName : roleTargets(iamService, resource)) {
+ detachTargets(policyArn, roleTargets(iamService, resource), iamService::detachRolePolicy);
+ detachTargets(policyArn, userTargets(iamService, resource), iamService::detachUserPolicy);
+ detachTargets(policyArn, groupTargets(iamService, resource), iamService::detachGroupPolicy);
+ deletePolicyTolerating(iamService, policyArn);
+ }
+
+ static List recordedTargets(String targets, String ids, List attached,
+ Function idGetter,
+ Function nameGetter) {
+ List targetNames = splitTargets(targets);
+ if (targetNames.isEmpty()) {
+ return List.of();
+ }
+ if (ids == null || ids.isBlank()) {
+ return targetNames;
+ }
+ Map currentNames = attached.stream().collect(Collectors.toMap(
+ idGetter, nameGetter, (first, ignored) -> first));
+ List targetIds = splitTargets(ids);
+ List resolved = new ArrayList<>();
+ for (int i = 0; i < targetNames.size(); i++) {
+ String id = i < targetIds.size() ? targetIds.get(i) : null;
+ if (id == null || id.isBlank()) {
+ resolved.add(targetNames.get(i));
+ } else if (currentNames.containsKey(id)) {
+ resolved.add(currentNames.get(id));
+ }
+ }
+ return resolved;
+ }
+
+ private static List splitTargets(String targets) {
+ return targets == null ? List.of() : targets.lines().filter(target -> !target.isBlank()).toList();
+ }
+
+ private static void detachTargets(String policyArn, List names,
+ BiConsumer detach) {
+ for (String name : names) {
try {
- iamService.detachRolePolicy(roleName, policyArn);
+ detach.accept(name, policyArn);
} catch (AwsException e) {
if (!"NoSuchEntity".equals(e.getErrorCode())) {
throw e;
}
}
}
- deletePolicyTolerating(iamService, policyArn);
}
/** Deletes the policy, tolerating one already gone. */
diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamPolicyCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamPolicyCfnProvisioner.java
index 9dcc07d5e4..880307a2a9 100644
--- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamPolicyCfnProvisioner.java
+++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamPolicyCfnProvisioner.java
@@ -378,6 +378,6 @@ public class IamPolicyCfnProvisioner implements CfnResourceProvisioner {
}
private void deleteLegacyManagedPolicy(StackResource resource) {
- IamManagedPolicyDeletes.detachRolesAndDeletePolicy(iamService, resource);
+ IamManagedPolicyDeletes.detachAndDeletePolicy(iamService, resource);
}
}
diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationIamInlinePolicyIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationIamInlinePolicyIntegrationTest.java
index 0145a39dbc..69acc844d8 100644
--- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationIamInlinePolicyIntegrationTest.java
+++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationIamInlinePolicyIntegrationTest.java
@@ -1,11 +1,18 @@
package io.floci.aws.services.cloudformation;
+import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.iam.IamClient;
+
+import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
+import static org.junit.jupiter.api.Assertions.assertAll;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -326,6 +333,98 @@ class CloudFormationIamInlinePolicyIntegrationTest {
.body(containsString(":policy/" + managedName));
}
+ @Test
+ void managedPolicyAttachesUsersAndGroups() throws InterruptedException {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String userName = "managed-policy-user-" + suffix;
+ String groupName = "managed-policy-group-" + suffix;
+ String policyName = "managed-principal-policy-" + suffix;
+ String policyArn = "arn:aws:iam::000000000000:policy/" + policyName;
+ String stackName = "cfn-managed-principals-" + suffix;
+
+ String template = """
+ {
+ "Resources": {
+ "ManagedPolicy": {
+ "Type": "AWS::IAM::ManagedPolicy",
+ "Properties": {
+ "ManagedPolicyName": "%s",
+ "PolicyDocument": {
+ "Version": "2012-10-17",
+ "Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]
+ },
+ "Users": ["%s"],
+ "Groups": ["%s"]
+ }
+ }
+ }
+ }
+ """.formatted(policyName, userName, groupName);
+ try (IamClient iam = AwsTestClients.create(IamClient.builder(), "test", Region.US_EAST_1)) {
+ iam.createUser(request -> request.userName(userName));
+ iam.createGroup(request -> request.groupName(groupName));
+
+ createStack(stackName, template);
+ assertStackComplete(stackName);
+
+ assertAll(
+ () -> assertEquals(List.of(policyArn), iam.listAttachedUserPolicies(request ->
+ request.userName(userName)).attachedPolicies().stream()
+ .map(policy -> policy.policyArn()).toList()),
+ () -> assertEquals(List.of(policyArn), iam.listAttachedGroupPolicies(request ->
+ request.groupName(groupName)).attachedPolicies().stream()
+ .map(policy -> policy.policyArn()).toList()));
+
+ CfnStackWaits.deleteStack(stackName, CFN_AUTH);
+
+ assertAll(
+ () -> assertTrue(iam.listAttachedUserPolicies(request ->
+ request.userName(userName)).attachedPolicies().isEmpty()),
+ () -> assertTrue(iam.listAttachedGroupPolicies(request ->
+ request.groupName(groupName)).attachedPolicies().isEmpty()));
+ }
+ }
+
+ @Test
+ void managedPolicyAttachesSameStackUserRefAndDeletesBeforeUser() throws InterruptedException {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String userName = "managed-ref-user-" + suffix;
+ String policyName = "managed-ref-policy-" + suffix;
+ String policyArn = "arn:aws:iam::000000000000:policy/" + policyName;
+ String stackName = "cfn-managed-user-ref-" + suffix;
+ String template = """
+ {
+ "Resources": {
+ "User": {
+ "Type": "AWS::IAM::User",
+ "Properties": {"UserName": "%s"}
+ },
+ "ManagedPolicy": {
+ "Type": "AWS::IAM::ManagedPolicy",
+ "Properties": {
+ "ManagedPolicyName": "%s",
+ "PolicyDocument": {
+ "Version": "2012-10-17",
+ "Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]
+ },
+ "Users": [{"Ref": "User"}]
+ }
+ }
+ }
+ }
+ """.formatted(userName, policyName);
+
+ try (IamClient iam = AwsTestClients.create(IamClient.builder(), "test", Region.US_EAST_1)) {
+ createStack(stackName, template);
+ assertStackComplete(stackName);
+ assertEquals(List.of(policyArn), iam.listAttachedUserPolicies(request ->
+ request.userName(userName)).attachedPolicies().stream()
+ .map(policy -> policy.policyArn()).toList());
+
+ CfnStackWaits.deleteStack(stackName, CFN_AUTH);
+ }
+ }
+
@Test
void deletingManagedPolicyDetachesItFromSurvivingRole() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
@@ -364,14 +463,7 @@ class CloudFormationIamInlinePolicyIntegrationTest {
createStack(stackName, template);
assertStackComplete(stackName);
- given()
- .contentType("application/x-www-form-urlencoded")
- .header("Authorization", CFN_AUTH)
- .formParam("Action", "DeleteStack")
- .formParam("StackName", stackName)
- .when().post("/").then().statusCode(200);
-
- awaitManagedPolicyGone(policyArn);
+ CfnStackWaits.deleteStack(stackName, CFN_AUTH);
given()
.contentType("application/x-www-form-urlencoded")
@@ -753,22 +845,6 @@ class CloudFormationIamInlinePolicyIntegrationTest {
+ " to be detached from role " + roleName);
}
- private static void awaitManagedPolicyGone(String policyArn) throws InterruptedException {
- for (int i = 0; i < 100; i++) {
- int status = given()
- .contentType("application/x-www-form-urlencoded")
- .header("Authorization", IAM_AUTH)
- .formParam("Action", "GetPolicy")
- .formParam("PolicyArn", policyArn)
- .when().post("/").then().extract().statusCode();
- if (status == 404) {
- return;
- }
- Thread.sleep(50);
- }
- throw new AssertionError("Timed out waiting for managed policy " + policyArn + " to be deleted");
- }
-
private static void assertFailedResource(String stackName, String logicalId,
String expectedSubject, String expectedReason) {
CfnStackWaits.awaitStatus(stackName, "ROLLBACK_COMPLETE", CFN_AUTH);
diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationManagedPolicyUpdateIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationManagedPolicyUpdateIntegrationTest.java
index 57321689a0..1bda02ae79 100644
--- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationManagedPolicyUpdateIntegrationTest.java
+++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationManagedPolicyUpdateIntegrationTest.java
@@ -3,6 +3,7 @@ package io.floci.aws.services.cloudformation;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.services.cloudformation.model.Stack;
+import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.iam.model.IamRole;
import io.floci.aws.testing.CfnStackWaits;
@@ -20,6 +21,8 @@ import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
@@ -59,7 +62,7 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
}
@SuppressWarnings("unchecked")
- private void forgetPolicyId(String stackName, String logicalId) throws ReflectiveOperationException {
+ private StackResource stackResource(String stackName, String logicalId) throws ReflectiveOperationException {
Object target = cloudFormationService instanceof ClientProxy proxy
? proxy.arc_contextualInstance()
: cloudFormationService;
@@ -70,7 +73,11 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
.filter(s -> stackName.equals(s.getStackName()))
.findFirst()
.orElseThrow(() -> new IllegalStateException("Stack not found: " + stackName));
- stack.getResources().get(logicalId).getAttributes().remove("PolicyId");
+ return stack.getResources().get(logicalId);
+ }
+
+ private void forgetPolicyId(String stackName, String logicalId) throws ReflectiveOperationException {
+ stackResource(stackName, logicalId).getAttributes().remove("PolicyId");
}
@SuppressWarnings("unchecked")
@@ -303,6 +310,136 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
.body(containsString(policyArn(policyName)));
}
+ @Test
+ void updateRetargetingUsersAndGroupsDetachesRemovedTargets() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-mp-principal-update-" + suffix;
+ String policyName = "mp-principal-update-" + suffix;
+ String oldUser = "mp-old-user-" + suffix;
+ String newUser = "mp-new-user-" + suffix;
+ String oldGroup = "mp-old-group-" + suffix;
+ String newGroup = "mp-new-group-" + suffix;
+ String arn = policyArn(policyName);
+
+ for (String userName : new String[] {oldUser, newUser}) {
+ iam("CreateUser", "UserName", userName);
+ }
+ for (String groupName : new String[] {oldGroup, newGroup}) {
+ iam("CreateGroup", "GroupName", groupName);
+ }
+
+ createStack(stackName, literalPrincipalManagedPolicyTemplate(
+ policyName, "s3:GetObject", oldUser, oldGroup));
+ assertStackStatus(stackName, "CREATE_COMPLETE");
+ updateStack(stackName, literalPrincipalManagedPolicyTemplate(
+ policyName, "s3:PutObject", newUser, newGroup));
+ assertStackStatus(stackName, "UPDATE_COMPLETE");
+
+ assertFalse(iam("ListAttachedUserPolicies", "UserName", oldUser).contains(arn));
+ assertFalse(iam("ListAttachedGroupPolicies", "GroupName", oldGroup).contains(arn));
+ assertTrue(iam("ListAttachedUserPolicies", "UserName", newUser).contains(arn));
+ assertTrue(iam("ListAttachedGroupPolicies", "GroupName", newGroup).contains(arn));
+ }
+
+ @Test
+ void updateDetachesRenamedUsersAndGroupsByIdentity() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-mp-renamed-update-" + suffix;
+ String policyName = "mp-renamed-update-" + suffix;
+ String oldUser = "mp-user-before-" + suffix;
+ String newUser = "mp-user-after-" + suffix;
+ String oldGroup = "mp-group-before-" + suffix;
+ String newGroup = "mp-group-after-" + suffix;
+ String arn = policyArn(policyName);
+
+ iam("CreateUser", "UserName", oldUser);
+ iam("CreateGroup", "GroupName", oldGroup);
+ createStack(stackName, literalPrincipalManagedPolicyTemplate(
+ policyName, "s3:GetObject", oldUser, oldGroup));
+ assertStackStatus(stackName, "CREATE_COMPLETE");
+
+ iam("UpdateUser", "UserName", oldUser, "NewUserName", newUser);
+ iam("UpdateGroup", "GroupName", oldGroup, "NewGroupName", newGroup);
+ updateStack(stackName, literalRoleManagedPolicyTemplate(policyName, "s3:PutObject"));
+ assertStackStatus(stackName, "UPDATE_COMPLETE");
+
+ assertFalse(iam("ListAttachedUserPolicies", "UserName", newUser).contains(arn));
+ assertFalse(iam("ListAttachedGroupPolicies", "GroupName", newGroup).contains(arn));
+ }
+
+ @Test
+ void failedGroupAttachOnUpdateRestoresPriorUserAndGroupAttachments()
+ throws ReflectiveOperationException {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-mp-principal-rollback-" + suffix;
+ String policyName = "mp-principal-rollback-" + suffix;
+ String oldUser = "mp-old-user-" + suffix;
+ String newUser = "mp-new-user-" + suffix;
+ String oldGroup = "mp-old-group-" + suffix;
+ String newGroup = "mp-new-group-" + suffix;
+ String arn = policyArn(policyName);
+
+ for (String userName : new String[] {oldUser, newUser}) {
+ iam("CreateUser", "UserName", userName);
+ }
+ for (String groupName : new String[] {oldGroup, newGroup}) {
+ iam("CreateGroup", "GroupName", groupName);
+ }
+
+ createStack(stackName, literalPrincipalManagedPolicyTemplate(
+ policyName, "s3:GetObject", oldUser, oldGroup));
+ assertStackStatus(stackName, "CREATE_COMPLETE");
+
+ doThrow(new AwsException("ServiceFailure", "simulated group attach failure", 500))
+ .when(iamService).attachGroupPolicy(eq(newGroup), eq(arn));
+ updateStack(stackName, literalPrincipalManagedPolicyTemplate(
+ policyName, "s3:PutObject", newUser, newGroup));
+ assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
+
+ assertTrue(iam("ListAttachedUserPolicies", "UserName", oldUser).contains(arn));
+ assertTrue(iam("ListAttachedGroupPolicies", "GroupName", oldGroup).contains(arn));
+ assertFalse(iam("ListAttachedUserPolicies", "UserName", newUser).contains(arn));
+ assertFalse(iam("ListAttachedGroupPolicies", "GroupName", newGroup).contains(arn));
+ assertTrue(iam("GetPolicy", "PolicyArn", arn).contains("v1"));
+ assertEquals("v1", stackResource(stackName, "SessionPolicy")
+ .getAttributes().get("DefaultVersionId"));
+ }
+
+ @Test
+ void failedGroupDetachOnUpdateRestoresEarlierUserDetach() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-mp-principal-detach-" + suffix;
+ String policyName = "mp-principal-detach-" + suffix;
+ String oldUser = "mp-old-user-" + suffix;
+ String newUser = "mp-new-user-" + suffix;
+ String oldGroup = "mp-old-group-" + suffix;
+ String newGroup = "mp-new-group-" + suffix;
+ String arn = policyArn(policyName);
+
+ for (String userName : new String[] {oldUser, newUser}) {
+ iam("CreateUser", "UserName", userName);
+ }
+ for (String groupName : new String[] {oldGroup, newGroup}) {
+ iam("CreateGroup", "GroupName", groupName);
+ }
+
+ createStack(stackName, literalPrincipalManagedPolicyTemplate(
+ policyName, "s3:GetObject", oldUser, oldGroup));
+ assertStackStatus(stackName, "CREATE_COMPLETE");
+
+ doThrow(new AwsException("ServiceFailure", "simulated group detach failure", 500))
+ .when(iamService).detachGroupPolicy(eq(oldGroup), eq(arn));
+ updateStack(stackName, literalPrincipalManagedPolicyTemplate(
+ policyName, "s3:PutObject", newUser, newGroup));
+ assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
+
+ assertTrue(iam("ListAttachedUserPolicies", "UserName", oldUser).contains(arn));
+ assertTrue(iam("ListAttachedGroupPolicies", "GroupName", oldGroup).contains(arn));
+ assertFalse(iam("ListAttachedUserPolicies", "UserName", newUser).contains(arn));
+ assertFalse(iam("ListAttachedGroupPolicies", "GroupName", newGroup).contains(arn));
+ assertTrue(iam("GetPolicy", "PolicyArn", arn).contains("v1"));
+ }
+
@Test
void updateRefusesToAdoptAPolicyRecreatedUnderTheStackOwnedName() throws ReflectiveOperationException {
String suffix = Long.toString(System.nanoTime(), 36);
@@ -387,13 +524,35 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
""".formatted(policyName, action, roleList);
}
+ private static String literalPrincipalManagedPolicyTemplate(
+ String policyName, String action, String userName, String groupName) {
+ return """
+ {
+ "Resources": {
+ "SessionPolicy": {
+ "Type": "AWS::IAM::ManagedPolicy",
+ "Properties": {
+ "ManagedPolicyName": "%s",
+ "PolicyDocument": {
+ "Version": "2012-10-17",
+ "Statement": [{"Effect": "Allow", "Action": "%s", "Resource": "*"}]
+ },
+ "Users": ["%s"],
+ "Groups": ["%s"]
+ }
+ }
+ }
+ }
+ """.formatted(policyName, action, userName, groupName);
+ }
+
@Test
void failedRoleAttachOnUpdateRestoresThePriorVersionAndDetachedRoles() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-mp-partial-" + suffix;
String policyName = "mp-partial-" + suffix;
String oldRole = "mp-partial-old-" + suffix;
- String badRole = "mp-partial-missing-" + suffix;
+ String badRole = "mp-partial-failing-" + suffix;
// Roles are plain IAM entities outside the stack (referenced by literal name, not Ref) so
// this stack's only resource is the managed policy — isolating the assertion from the
@@ -401,12 +560,16 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
iam("CreateRole", "RoleName", oldRole, "AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}");
+ iam("CreateRole", "RoleName", badRole, "AssumeRolePolicyDocument",
+ "{\"Version\":\"2012-10-17\",\"Statement\":[]}");
createStack(stackName, literalRoleManagedPolicyTemplate(policyName, "s3:GetObject", oldRole));
assertStackStatus(stackName, "CREATE_COMPLETE");
- // Retarget to a role that does not exist: AttachRolePolicy fails after the update path
- // has already replaced the default version and detached the old (now-obsolete) role.
+ // The target exists at validation time; a late attach failure exercises compensation
+ // after the update replaced the default version and detached the old role.
+ doThrow(new AwsException("ServiceFailure", "simulated attach failure", 500))
+ .when(iamService).attachRolePolicy(eq(badRole), eq(policyArn(policyName)));
updateStack(stackName, literalRoleManagedPolicyTemplate(policyName, "s3:PutObject", badRole));
assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
@@ -482,19 +645,23 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
String stackName = "cfn-mp-restorefail-" + suffix;
String policyName = "mp-restorefail-" + suffix;
String oldRole = "mp-restorefail-old-" + suffix;
- String badRole = "mp-restorefail-missing-" + suffix;
+ String badRole = "mp-restorefail-failing-" + suffix;
iam("CreateRole", "RoleName", oldRole, "AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}");
+ iam("CreateRole", "RoleName", badRole, "AssumeRolePolicyDocument",
+ "{\"Version\":\"2012-10-17\",\"Statement\":[]}");
createStack(stackName, literalRoleManagedPolicyTemplate(policyName, "s3:GetObject", oldRole));
assertStackStatus(stackName, "CREATE_COMPLETE");
- // Retargeting to a role that does not exist fails the attach loop after the obsolete-role
- // detach loop has already detached oldRole. The compensating reattach that restore()
- // performs for oldRole is made to fail here too, so cleanup itself does not complete —
+ // A late attach failure occurs after the obsolete-role detach loop. The compensating
+ // reattach that restore() performs for oldRole is made to fail here too, so cleanup itself
+ // does not complete:
// the stack must report UPDATE_ROLLBACK_FAILED, not silently claim UPDATE_ROLLBACK_COMPLETE.
+ doThrow(new AwsException("ServiceFailure", "simulated attach failure", 500))
+ .when(iamService).attachRolePolicy(eq(badRole), eq(policyArn(policyName)));
doThrow(new AwsException("ServiceFailure", "simulated reattach failure", 500))
.when(iamService).attachRolePolicy(eq(oldRole), eq(policyArn(policyName)));
@@ -508,11 +675,13 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
String stackName = "cfn-mp-prunefail-" + suffix;
String policyName = "mp-prunefail-" + suffix;
String oldRole = "mp-prunefail-old-" + suffix;
- String badRole = "mp-prunefail-missing-" + suffix;
+ String badRole = "mp-prunefail-failing-" + suffix;
iam("CreateRole", "RoleName", oldRole, "AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}");
+ iam("CreateRole", "RoleName", badRole, "AssumeRolePolicyDocument",
+ "{\"Version\":\"2012-10-17\",\"Statement\":[]}");
createStack(stackName, literalRoleManagedPolicyTemplate(policyName, "s3:GetObject", oldRole));
assertStackStatus(stackName, "CREATE_COMPLETE");
@@ -526,8 +695,9 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
assertStackStatus(stackName, "UPDATE_COMPLETE");
}
- // Retargeting to a role that does not exist fails the attach loop AFTER the update path
- // has already pruned v1 (to stay under the cap) and published v6 as the new default.
+ // The late attach failure happens AFTER pruning v1 and publishing v6.
+ doThrow(new AwsException("ServiceFailure", "simulated attach failure", 500))
+ .when(iamService).attachRolePolicy(eq(badRole), eq(policyArn(policyName)));
updateStack(stackName,
literalRoleManagedPolicyTemplate(policyName, "s3:AbortMultipartUpload", badRole));
assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/IamManagedPolicyCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/IamManagedPolicyCfnProvisionerTest.java
index 88fe6f7763..d76b0f9c83 100644
--- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/IamManagedPolicyCfnProvisionerTest.java
+++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/IamManagedPolicyCfnProvisionerTest.java
@@ -6,7 +6,9 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.iam.IamService;
+import io.floci.aws.services.iam.model.IamGroup;
import io.floci.aws.services.iam.model.IamPolicy;
+import io.floci.aws.services.iam.model.IamUser;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
@@ -23,6 +25,7 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -64,6 +67,98 @@ class IamManagedPolicyCfnProvisionerTest {
verify(iam).attachRolePolicy("web-role", ARN);
}
+ @Test
+ void missingGroupFailsBeforeCreatingThePolicy() throws Exception {
+ when(iam.getGroup("missing-group"))
+ .thenThrow(new AwsException("NoSuchEntity", "missing group", 404));
+
+ AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(resource(), props("""
+ {"ManagedPolicyName": "app-policy",
+ "PolicyDocument": {"Version": "2012-10-17", "Statement": []},
+ "Users": ["app-user"], "Groups": ["missing-group"]}
+ """), ctx(null)));
+
+ assertEquals("NoSuchEntity", failure.getErrorCode());
+ verify(iam, never()).createPolicy(eq("app-policy"), eq("/"), eq(null), any(), eq(Map.of()));
+ }
+
+ @Test
+ void failedAttachmentSnapshotDoesNotMutateAnExistingPolicy() throws Exception {
+ IamPolicy policy = mock(IamPolicy.class);
+ when(policy.getPolicyId()).thenReturn("AID1");
+ when(iam.createPolicy(eq("app-policy"), eq("/"), eq(null), any(), eq(Map.of())))
+ .thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409));
+ when(iam.getPolicy(ARN)).thenReturn(policy);
+ when(iam.listEntitiesForPolicy(ARN))
+ .thenThrow(new AwsException("ServiceFailure", "snapshot failed", 500));
+ StackResource r = resource();
+ r.setPhysicalId(ARN);
+ r.getAttributes().put("PolicyId", "AID1");
+
+ assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
+ {"ManagedPolicyName": "app-policy",
+ "PolicyDocument": {"Version": "2012-10-17", "Statement": []},
+ "Users": ["app-user"]}
+ """), ctx(ARN)));
+
+ verify(iam, never()).createPolicyVersion(eq(ARN), any(), eq(true));
+ verify(iam, never()).detachUserPolicy("app-user", ARN);
+ }
+
+ @Test
+ void updateDetachesExplicitLegacyUserAndGroupTargets() throws Exception {
+ IamPolicy policy = mock(IamPolicy.class);
+ when(policy.getArn()).thenReturn(ARN);
+ when(policy.getPolicyId()).thenReturn("AID1");
+ when(policy.getDefaultVersionId()).thenReturn("v1");
+ when(iam.createPolicy(eq("app-policy"), eq("/"), eq(null), any(), eq(Map.of())))
+ .thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409));
+ when(iam.getPolicy(ARN)).thenReturn(policy);
+ when(iam.listEntitiesForPolicy(ARN))
+ .thenReturn(new IamService.PolicyEntities(List.of(), List.of(), List.of()));
+ when(iam.listPolicyVersions(ARN)).thenReturn(List.of());
+ StackResource r = resource();
+ r.setPhysicalId(ARN);
+ r.getAttributes().put("PolicyId", "AID1");
+ r.getAttributes().put("ManagedPolicyUserTargets", "legacy-user");
+ r.getAttributes().put("ManagedPolicyGroupTargets", "legacy-group");
+
+ provisioner.provision(r, props("""
+ {"ManagedPolicyName": "app-policy",
+ "PolicyDocument": {"Version": "2012-10-17", "Statement": []}}
+ """), ctx(ARN));
+
+ verify(iam).detachUserPolicy("legacy-user", ARN);
+ verify(iam).detachGroupPolicy("legacy-group", ARN);
+ verify(iam, never()).listUsers("/");
+ verify(iam, never()).listGroups("/");
+ assertEquals("", r.getAttributes().get("ManagedPolicyUserTargets"));
+ assertEquals("", r.getAttributes().get("ManagedPolicyGroupTargets"));
+ }
+
+ @Test
+ void failedGroupAttachUndoesNewRoleAndUserAttachments() throws Exception {
+ IamPolicy policy = mock(IamPolicy.class);
+ when(policy.getArn()).thenReturn(ARN);
+ when(iam.createPolicy(eq("app-policy"), eq("/"), eq(null), any(), eq(Map.of()))).thenReturn(policy);
+ doThrow(new AwsException("ServiceFailure", "group attach failed", 500))
+ .when(iam).attachGroupPolicy("app-group", ARN);
+
+ assertThrows(AwsException.class, () -> provisioner.provision(resource(), props("""
+ {"ManagedPolicyName": "app-policy",
+ "PolicyDocument": {"Version": "2012-10-17", "Statement": []},
+ "Roles": ["app-role"], "Users": ["app-user"], "Groups": ["app-group"]}
+ """), ctx(null)));
+
+ InOrder order = inOrder(iam);
+ order.verify(iam).attachRolePolicy("app-role", ARN);
+ order.verify(iam).attachUserPolicy("app-user", ARN);
+ order.verify(iam).attachGroupPolicy("app-group", ARN);
+ order.verify(iam).detachUserPolicy("app-user", ARN);
+ order.verify(iam).detachRolePolicy("app-role", ARN);
+ order.verify(iam).deletePolicy(ARN);
+ }
+
@Test
void deleteDetachesRolesThenRemovesThePolicy() {
StackResource r = resource();
@@ -77,6 +172,92 @@ class IamManagedPolicyCfnProvisionerTest {
order.verify(iam).deletePolicy(ARN);
}
+ @Test
+ void deleteDetachesEveryStoredPrincipalBeforeRemovingThePolicy() {
+ StackResource r = resource();
+ r.setPhysicalId(ARN);
+ r.getAttributes().put("ManagedPolicyRoleTargets", "app-role");
+ r.getAttributes().put("ManagedPolicyUserTargets", "app-user");
+ r.getAttributes().put("ManagedPolicyGroupTargets", "app-group");
+ r.getAttributes().put("ManagedPolicyUserTargetIds", "AIDAUSER");
+ r.getAttributes().put("ManagedPolicyGroupTargetIds", "AGROUP");
+ IamUser user = mock(IamUser.class);
+ when(user.getUserId()).thenReturn("AIDAUSER");
+ when(user.getUserName()).thenReturn("app-user");
+ when(iam.listUsers("/")).thenReturn(List.of(user));
+ IamGroup group = mock(IamGroup.class);
+ when(group.getGroupId()).thenReturn("AGROUP");
+ when(group.getGroupName()).thenReturn("app-group");
+ when(iam.listGroups("/")).thenReturn(List.of(group));
+
+ provisioner.delete(r, "us-east-1");
+
+ InOrder order = inOrder(iam);
+ order.verify(iam).detachRolePolicy("app-role", ARN);
+ order.verify(iam).detachUserPolicy("app-user", ARN);
+ order.verify(iam).detachGroupPolicy("app-group", ARN);
+ order.verify(iam).deletePolicy(ARN);
+ }
+
+ @Test
+ void deleteUsesExplicitLegacyUserAndGroupTargetsWithoutScanning() {
+ StackResource r = resource();
+ r.setPhysicalId(ARN);
+ r.getAttributes().put("ManagedPolicyUserTargets", "legacy-user");
+ r.getAttributes().put("ManagedPolicyGroupTargets", "legacy-group");
+
+ provisioner.delete(r, "us-east-1");
+
+ verify(iam).detachUserPolicy("legacy-user", ARN);
+ verify(iam).detachGroupPolicy("legacy-group", ARN);
+ verify(iam, never()).listUsers("/");
+ verify(iam, never()).listGroups("/");
+ verify(iam).deletePolicy(ARN);
+ }
+
+ @Test
+ void legacyPolicyDeletePreservesUnrecordedUserAndGroupAttachments() {
+ StackResource r = resource();
+ r.setPhysicalId(ARN);
+ when(iam.listRoles("/")).thenReturn(List.of());
+ IamUser outsideUser = mock(IamUser.class);
+ when(outsideUser.getAttachedPolicyArns()).thenReturn(new ArrayList<>(List.of(ARN)));
+ when(outsideUser.getUserName()).thenReturn("outside-user");
+ when(iam.listUsers("/")).thenReturn(List.of(outsideUser));
+ IamGroup outsideGroup = mock(IamGroup.class);
+ when(outsideGroup.getAttachedPolicyArns()).thenReturn(new ArrayList<>(List.of(ARN)));
+ when(outsideGroup.getGroupName()).thenReturn("outside-group");
+ when(iam.listGroups("/")).thenReturn(List.of(outsideGroup));
+ doThrow(new AwsException("DeleteConflict", "policy still attached", 409))
+ .when(iam).deletePolicy(ARN);
+
+ AwsException failure = assertThrows(AwsException.class, () -> provisioner.delete(r, "us-east-1"));
+
+ assertEquals("DeleteConflict", failure.getErrorCode());
+ verify(iam, never()).detachUserPolicy("outside-user", ARN);
+ verify(iam, never()).detachGroupPolicy("outside-group", ARN);
+ verify(iam, never()).listUsers("/");
+ verify(iam, never()).listGroups("/");
+ }
+
+ @Test
+ void emptyRecordedPrincipalTargetsDoNotScanOrDetach() {
+ StackResource r = resource();
+ r.setPhysicalId(ARN);
+ r.getAttributes().put("ManagedPolicyUserTargets", "\n");
+ r.getAttributes().put("ManagedPolicyGroupTargets", "\n");
+ r.getAttributes().put("ManagedPolicyUserTargetIds", "AIDAUSER");
+ r.getAttributes().put("ManagedPolicyGroupTargetIds", "AGROUP");
+
+ provisioner.delete(r, "us-east-1");
+
+ verify(iam, never()).listUsers("/");
+ verify(iam, never()).listGroups("/");
+ verify(iam, never()).detachUserPolicy(any(), eq(ARN));
+ verify(iam, never()).detachGroupPolicy(any(), eq(ARN));
+ verify(iam).deletePolicy(ARN);
+ }
+
@Test
void deleteToleratesAnAlreadyDetachedRole() {
StackResource r = resource();
diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv
index a35ea1acce..d08841c9f9 100644
--- a/src/test/resources/cloudformation/writable-property-gaps.tsv
+++ b/src/test/resources/cloudformation/writable-property-gaps.tsv
@@ -369,10 +369,8 @@ AWS::Events::EventBus DeadLetterConfig rejected with a ValidationError, not supp
AWS::Events::EventBus KmsKeyIdentifier rejected with a ValidationError, not supported by Floci
AWS::Events::EventBus LogConfig rejected with a ValidationError, not supported by Floci
AWS::IAM::ManagedPolicy Description accepted and ignored
-AWS::IAM::ManagedPolicy Groups accepted and ignored
AWS::IAM::ManagedPolicy Path accepted and ignored
AWS::IAM::ManagedPolicy PolicyDocument accepted and ignored
-AWS::IAM::ManagedPolicy Users accepted and ignored
AWS::IAM::Policy PolicyDocument accepted and ignored
AWS::IAM::Role Tags accepted and ignored
AWS::IAM::User LoginProfile documented as ignored (docs/services/cloudformation.md, IAM)