fix(cloudformation): attach managed policies to users and groups (#8708)

This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-11-17 09:47:02 -04:00
1 parent 2fdcbecdf0
commit 76413ce74a
7 files changed
+736 -118

No files matched your search

@@ -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.
*
* <p>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<String> roleNames = ctx.resolveStringList(props, "Roles");
List<String> userNames = ctx.resolveStringList(props, "Users");
List<String> groupNames = ctx.resolveStringList(props, "Groups");
String existingArn = r.getPhysicalId();
// Check every declared target before creating a policy or publishing a new version.
List<IamRole> declaredRoles = roleNames.stream().map(iamService::getRole).toList();
List<IamUser> declaredUsers = userNames.stream().map(iamService::getUser).toList();
List<IamGroup> 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<PolicyVersion> prunedVersionsForRollback = new ArrayList<>();
List<String> 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<PrincipalDetachAction> 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<String> previouslyAttached = createdPolicy
? Set.of()
: iamService.listEntitiesForPolicy(policyArn).roles().stream()
.map(role -> role.getRoleName())
Set<String> previouslyAttachedRoles = priorEntities == null
? Set.of() : priorEntities.roles().stream()
.map(IamRole::getRoleName)
.collect(Collectors.toSet());
Set<String> previouslyAttachedUsers = priorEntities == null
? Set.of() : priorEntities.users().stream()
.map(IamUser::getUserName)
.collect(Collectors.toSet());
Set<String> previouslyAttachedGroups = priorEntities == null
? Set.of() : priorEntities.groups().stream()
.map(IamGroup::getGroupName)
.collect(Collectors.toSet());
LinkedHashSet<String> 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<String> attachedRoleNames,
List<String> detachedObsoleteRoles, String previousDefaultVersionId,
boolean createdPolicy, AttachmentChanges changes,
String previousRoleTargets, String previousUserTargets,
String previousGroupTargets,
String previousRoleTargetIds, String previousUserTargetIds,
String previousGroupTargetIds, String previousDefaultVersionId,
PolicyVersion createdVersionForRollback,
List<PolicyVersion> prunedVersionsForRollback) {
List<String> 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<String> 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 <T> String targetIds(List<T> entities, Function<T, String> 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<String> names, Consumer<String> action,
String operation) {
boolean succeeded = true;
List<String> 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<String> attachedRoles = new LinkedHashSet<>();
private final Set<String> attachedUsers = new LinkedHashSet<>();
private final Set<String> attachedGroups = new LinkedHashSet<>();
private final List<String> detachedRoles = new ArrayList<>();
private final List<String> detachedUsers = new ArrayList<>();
private final List<String> detachedGroups = new ArrayList<>();
}
private record PrincipalDetachAction(List<String> previousNames, List<String> desiredNames,
BiConsumer<String, String> detach, List<String> detachedNames) {
}
@Override
public void delete(StackResource resource, String region) {
IamManagedPolicyDeletes.detachRolesAndDeletePolicy(iamService, resource);
IamManagedPolicyDeletes.detachAndDeletePolicy(iamService, resource);
}
}
@@ -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<String> 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<String> 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<IamRole> 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<String> userTargets(IamService iamService, StackResource resource) {
return principalTargets(resource, "ManagedPolicyUserTargets", "ManagedPolicyUserTargetIds",
() -> iamService.listUsers("/"), IamUser::getUserId, IamUser::getUserName);
}
static List<String> groupTargets(IamService iamService, StackResource resource) {
return principalTargets(resource, "ManagedPolicyGroupTargets", "ManagedPolicyGroupTargetIds",
() -> iamService.listGroups("/"), IamGroup::getGroupId, IamGroup::getGroupName);
}
private static <T> List<String> principalTargets(StackResource resource, String namesKey, String idsKey,
Supplier<List<T>> listPrincipals,
Function<T, String> idGetter,
Function<T, String> 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 <T> List<String> recordedTargets(String targets, String ids, List<T> attached,
Function<T, String> idGetter,
Function<T, String> nameGetter) {
List<String> targetNames = splitTargets(targets);
if (targetNames.isEmpty()) {
return List.of();
}
if (ids == null || ids.isBlank()) {
return targetNames;
}
Map<String, String> currentNames = attached.stream().collect(Collectors.toMap(
idGetter, nameGetter, (first, ignored) -> first));
List<String> targetIds = splitTargets(ids);
List<String> 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<String> splitTargets(String targets) {
return targets == null ? List.of() : targets.lines().filter(target -> !target.isBlank()).toList();
}
private static void detachTargets(String policyArn, List<String> names,
BiConsumer<String, String> 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. */
@@ -378,6 +378,6 @@ public class IamPolicyCfnProvisioner implements CfnResourceProvisioner {
}
private void deleteLegacyManagedPolicy(StackResource resource) {
IamManagedPolicyDeletes.detachRolesAndDeletePolicy(iamService, resource);
IamManagedPolicyDeletes.detachAndDeletePolicy(iamService, resource);
}
}