refactor(cloudformation): share managed-policy delete helpers (#4052)

IamManagedPolicyCfnProvisioner and IamPolicyCfnProvisioner's legacy path each carried a near-identical managedPolicyRoleTargets resolver and detach-then-delete loop for a stack-owned managed policy. Extract them into IamManagedPolicyDeletes (roleTargets, detachRolesAndDeletePolicy, deletePolicyTolerating), mirroring CfnDeletes, and delegate from both. The legacy migration keeps its own rollback-tracking detach loop, reusing only the shared target resolution and tolerant delete.

Behavior-preserving: the copies were equivalent (recorded-targets-or-discover, then detach tolerating NoSuchEntity, then delete tolerating NoSuchEntity).

Refs #3972

Follow-up now unblocked because both IAM policy PRs (#3971, #3972) have merged.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-21 08:05:20 -04:00
1 parent e7fe03b69b
commit e4c75e4f17
3 files changed
+81 -83

No files matched your search

@@ -249,41 +249,6 @@ public class IamManagedPolicyCfnProvisioner implements CfnResourceProvisioner {
@Override
public void delete(StackResource resource, String region) {
String policyArn = resource.getPhysicalId();
for (String roleName : managedPolicyRoleTargets(resource)) {
try {
iamService.detachRolePolicy(roleName, policyArn);
} catch (AwsException e) {
// Deletion is idempotent: the role or attachment can already be absent on a retry,
// but permission/service failures must keep the stack in DELETE_FAILED.
if (!"NoSuchEntity".equals(e.getErrorCode())) {
throw e;
}
}
}
try {
iamService.deletePolicy(policyArn);
} catch (AwsException e) {
if (!"NoSuchEntity".equals(e.getErrorCode())) {
throw e;
}
}
}
private List<String> managedPolicyRoleTargets(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(role -> role.getRoleName())
.collect(Collectors.joining("\n"));
}
if (targets == null || targets.isBlank()) {
return List.of();
}
return targets.lines().filter(roleName -> !roleName.isBlank()).toList();
IamManagedPolicyDeletes.detachRolesAndDeletePolicy(iamService, resource);
}
}
@@ -0,0 +1,77 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
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.model.IamRole;
import org.jboss.logging.Logger;
import java.util.List;
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.
*/
final class IamManagedPolicyDeletes {
private static final Logger LOG = Logger.getLogger(IamManagedPolicyDeletes.class);
private 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.
*/
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"));
}
if (targets == null || targets.isBlank()) {
return List.of();
}
return targets.lines().filter(roleName -> !roleName.isBlank()).toList();
}
/**
* 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
* permission or service failure propagates so the stack stays DELETE_FAILED.
*/
static void detachRolesAndDeletePolicy(IamService iamService, StackResource resource) {
String policyArn = resource.getPhysicalId();
for (String roleName : roleTargets(iamService, resource)) {
try {
iamService.detachRolePolicy(roleName, policyArn);
} catch (AwsException e) {
if (!"NoSuchEntity".equals(e.getErrorCode())) {
throw e;
}
}
}
deletePolicyTolerating(iamService, policyArn);
}
/** Deletes the policy, tolerating one already gone. */
static void deletePolicyTolerating(IamService iamService, String policyArn) {
try {
iamService.deletePolicy(policyArn);
} catch (AwsException e) {
if (!"NoSuchEntity".equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("IAM policy already gone, treating as deleted: {0}", policyArn);
}
}
}
@@ -5,7 +5,6 @@ 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.model.IamRole;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -18,7 +17,6 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* CloudFormation provisioning for {@code AWS::IAM::Policy}, which in AWS is an <em>inline</em>
@@ -303,7 +301,7 @@ public class IamPolicyCfnProvisioner implements CfnResourceProvisioner {
String policyArn = resource.getPhysicalId();
List<String> detachedRoles = new ArrayList<>();
try {
for (String roleName : managedPolicyRoleTargets(resource)) {
for (String roleName : IamManagedPolicyDeletes.roleTargets(iamService, resource)) {
try {
iamService.detachRolePolicy(roleName, policyArn);
detachedRoles.add(roleName);
@@ -313,7 +311,7 @@ public class IamPolicyCfnProvisioner implements CfnResourceProvisioner {
}
}
}
deleteManagedPolicySafe(policyArn);
IamManagedPolicyDeletes.deletePolicyTolerating(iamService, policyArn);
} catch (RuntimeException failure) {
Collections.reverse(detachedRoles);
for (String roleName : detachedRoles) {
@@ -326,48 +324,6 @@ public class IamPolicyCfnProvisioner implements CfnResourceProvisioner {
}
private void deleteLegacyManagedPolicy(StackResource resource) {
String policyArn = resource.getPhysicalId();
for (String roleName : managedPolicyRoleTargets(resource)) {
try {
iamService.detachRolePolicy(roleName, policyArn);
} catch (AwsException e) {
// Deletion is idempotent: the role or attachment can already be absent on a retry,
// but permission/service failures must keep the stack in DELETE_FAILED.
if (!"NoSuchEntity".equals(e.getErrorCode())) {
throw e;
}
}
}
deleteManagedPolicySafe(policyArn);
}
private void deleteManagedPolicySafe(String policyArn) {
try {
iamService.deletePolicy(policyArn);
} catch (AwsException e) {
if (!"NoSuchEntity".equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("IAM policy already gone, treating as deleted: {0}", policyArn);
}
}
private List<String> managedPolicyRoleTargets(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"));
}
if (targets == null || targets.isBlank()) {
return List.of();
}
return Arrays.stream(targets.split("\n"))
.filter(roleName -> !roleName.isBlank())
.toList();
IamManagedPolicyDeletes.detachRolesAndDeletePolicy(iamService, resource);
}
}