refactor(cloudformation): move IAM inline Policy into IamPolicyCfnProvisioner (#3971)

Move AWS::IAM::Policy out of the CloudFormationResourceProvisioner monolith into a new IamPolicyCfnProvisioner over IamService. AWS::IAM::Policy is an inline policy embedded in the named roles, users and groups, so Ref is the policy name with no ARN, the name is stable across updates unless the template changes it, and a failed update rolls back the partially applied puts and records anything it could not undo for the next provision to drain. A physical id that is a managed policy ARN is the pre-inline upgrade path, migrated and deleted here as before.

The shared PolicyDocument resolver is hoisted onto ProvisionContext so the managed-policy provisioner can reuse it when it moves. Leaving LEGACY_SWITCH subjects the type to CfnSchemaCoverageTest: its only readOnly attribute, Id, is recorded as a gap row because Floci uses the policy name for Ref where AWS returns an opaque identifier it does not model. ManagedPolicy stays in the monolith for the following PR, so its delete and the legacy-managed helpers are duplicated between the two until then.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-19 22:52:06 -04:00
1 parent 0f76840ef4
commit ee74fd0a49
8 files changed
+505 -296

No files matched your search

@@ -58,10 +58,6 @@ public class CloudFormationResourceProvisioner {
private static final String LAMBDA_PACKAGE_TYPE_ATTR = "FlociLambdaPackageType";
static final String UPDATE_ROLLBACK_RESTORED_ATTR = CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR;
static final String UPDATE_ROLLBACK_FAILURE_ATTR = CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR;
private static final String INLINE_CLEANUP_POLICY_NAME_ATTR = "__FlociInlineCleanupPolicyName";
private static final String INLINE_CLEANUP_ROLE_TARGETS_ATTR = "__FlociInlineCleanupRoleTargets";
private static final String INLINE_CLEANUP_USER_TARGETS_ATTR = "__FlociInlineCleanupUserTargets";
private static final String INLINE_CLEANUP_GROUP_TARGETS_ATTR = "__FlociInlineCleanupGroupTargets";
private static final String NAME_MODE_EXPLICIT = "explicit";
private static final String NAME_MODE_GENERATED = "generated";
private static final int GENERATED_NAME_SUFFIX_LENGTH = 12;
@@ -90,8 +86,7 @@ public class CloudFormationResourceProvisioner {
static final Set<String> DELETE_NEEDS_STACK_RESOURCE = Set.of(
"AWS::ApiGatewayV2::Authorizer",
"AWS::CloudFormation::CustomResource",
"AWS::IAM::ManagedPolicy",
"AWS::IAM::Policy");
"AWS::IAM::ManagedPolicy");
/**
* Every resource type the switch in {@link #provision} still serves. Load-bearing: the
@@ -109,7 +104,6 @@ public class CloudFormationResourceProvisioner {
"AWS::ApiGatewayV2::Stage",
"AWS::CloudFormation::CustomResource",
"AWS::IAM::ManagedPolicy",
"AWS::IAM::Policy",
"AWS::Lambda::Function",
"AWS::Lambda::LayerVersion");
@@ -215,7 +209,6 @@ public class CloudFormationResourceProvisioner {
case "AWS::Lambda::Function" -> provisionLambda(resource, properties, engine, region, accountId, stackName);
case "AWS::Lambda::LayerVersion" ->
provisionLambdaLayerVersion(resource, properties, engine, region, stackName);
case "AWS::IAM::Policy" -> provisionIamInlinePolicy(resource, properties, engine, stackName);
case "AWS::IAM::ManagedPolicy" ->
provisionIamManagedPolicy(resource, properties, engine, accountId, stackName);
case "AWS::ApiGatewayV2::Api" -> provisionApiGatewayV2Api(resource, properties, engine, region, accountId, stackName);
@@ -383,12 +376,6 @@ public class CloudFormationResourceProvisioner {
}
return;
}
// AWS::IAM::Policy is an inline policy; detaching it needs the principals it was attached to,
// which the type/physicalId delete path can't provide (only the delete-stack path has them).
if ("AWS::IAM::Policy".equals(resourceType)) {
deleteInlinePolicySafe(resource);
return;
}
// Managed-policy deletion likewise needs the resolved role targets so it can detach the
// policy before IAM's DeletePolicy operation. The type/physicalId path lacks that state.
if ("AWS::IAM::ManagedPolicy".equals(resourceType)) {
@@ -416,10 +403,6 @@ public class CloudFormationResourceProvisioner {
}
switch (resourceType) {
case "AWS::Lambda::Function" -> deleteLambdaFunctionSafe(physicalId, region);
// AWS::IAM::Policy is inline: it is removed together with its owning principal (see
// IamRoleCfnProvisioner#delete), or precisely via the StackResource-aware delete path.
// Nothing to do here when only the physical id (policy name) is known, as on rollback.
case "AWS::IAM::Policy" -> { }
case "AWS::IAM::ManagedPolicy" -> deletePolicySafe(physicalId);
// No bus context on the type/physicalId path (e.g. CREATE-rollback); targets the default bus.
case "AWS::ApiGatewayV2::Api" -> apiGatewayV2Service.deleteApi(region, physicalId);
@@ -1139,173 +1122,6 @@ public class CloudFormationResourceProvisioner {
return resolved != null ? resolved : "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
}
/**
* Provisions {@code AWS::IAM::Policy}, which in AWS is an <em>inline</em> policy embedded in the
* named roles/users/groups (equivalent to PutRolePolicy/PutUserPolicy/PutGroupPolicy) — <em>not</em>
* a standalone managed policy. Because an inline policy name is scoped to the principal that owns
* it (not the account), two stacks that reuse the same construct sub-tree — and therefore emit the
* same auto-generated {@code PolicyName} on different roles — no longer collide. Floci currently
* uses the policy name for {@code Ref}; AWS returns an opaque generated resource identifier.
* The resource exposes no ARN attribute.
*/
private void provisionIamInlinePolicy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String stackName) {
String previousPolicyName = r.getPhysicalId();
String previousRoleTargets = r.getAttributes().get("InlineRoleTargets");
String previousUserTargets = r.getAttributes().get("InlineUserTargets");
String previousGroupTargets = r.getAttributes().get("InlineGroupTargets");
boolean legacyManagedPolicy = isIamManagedPolicyArn(previousPolicyName);
String policyName = resolveOptional(props, "PolicyName", engine);
if (policyName == null || policyName.isBlank()) {
policyName = previousPolicyName != null && !previousPolicyName.isBlank() && !legacyManagedPolicy
? previousPolicyName
: generatePhysicalName(stackName, r.getLogicalId(), 128, false);
}
String document = resolvePolicyDocument(props, engine);
final String name = policyName;
final String doc = document;
List<String> roleTargets = new ArrayList<>();
List<String> userTargets = new ArrayList<>();
List<String> groupTargets = new ArrayList<>();
try {
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) {
migrateLegacyManagedPolicy(r);
} else {
deleteRemovedInlinePolicies(previousRoleTargets, roleTargets,
previousPolicyName, policyName,
principal -> iamService.deleteRolePolicy(principal, previousPolicyName));
deleteRemovedInlinePolicies(previousUserTargets, userTargets,
previousPolicyName, policyName,
principal -> iamService.deleteUserPolicy(principal, previousPolicyName));
deleteRemovedInlinePolicies(previousGroupTargets, groupTargets,
previousPolicyName, policyName,
principal -> iamService.deleteGroupPolicy(principal, previousPolicyName));
}
} 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);
}
throw failure;
}
r.setPhysicalId(policyName);
r.getAttributes().remove("Arn");
recordInlinePolicyTargets(r, roleTargets, userTargets, groupTargets);
}
/**
* Applies {@code op} to each principal name listed under {@code propName}. Each successful target
* is appended immediately so the caller can either commit the complete target set or roll back a
* partially applied attempt.
*/
private void putInlinePolicy(JsonNode props, String propName, CloudFormationTemplateEngine engine,
List<String> successfulTargets,
java.util.function.Consumer<String> op) {
if (props == null || !props.has(propName)) {
return;
}
for (JsonNode entry : props.get(propName)) {
String name = engine.resolve(entry);
if (name != null && !name.isBlank()) {
op.accept(name);
successfulTargets.add(name);
}
}
}
private void recordInlinePolicyTargets(StackResource resource,
List<String> roleTargets,
List<String> userTargets,
List<String> groupTargets) {
// Newlines are unambiguous because IAM principal names allow commas but never newlines.
resource.getAttributes().put("InlineRoleTargets", String.join("\n", roleTargets));
resource.getAttributes().put("InlineUserTargets", String.join("\n", userTargets));
resource.getAttributes().put("InlineGroupTargets", String.join("\n", groupTargets));
if (!roleTargets.isEmpty() || !userTargets.isEmpty() || !groupTargets.isEmpty()) {
resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
}
}
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));
recordPendingInlineCleanup(resource, currentPolicyName, pendingRoles, pendingUsers, pendingGroups);
resource.getAttributes().put(UPDATE_ROLLBACK_RESTORED_ATTR, "true");
}
private List<String> rollbackAppliedInlinePolicies(
RuntimeException failure,
String previousTargets,
List<String> appliedTargets,
String previousPolicyName,
String currentPolicyName,
java.util.function.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);
}
}
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,
List<String> roleTargets,
List<String> userTargets,
List<String> groupTargets) {
if (roleTargets.isEmpty() && userTargets.isEmpty() && groupTargets.isEmpty()) {
return;
}
resource.getAttributes().put(INLINE_CLEANUP_POLICY_NAME_ATTR, policyName);
resource.getAttributes().put(INLINE_CLEANUP_ROLE_TARGETS_ATTR, String.join("\n", roleTargets));
resource.getAttributes().put(INLINE_CLEANUP_USER_TARGETS_ATTR, String.join("\n", userTargets));
resource.getAttributes().put(INLINE_CLEANUP_GROUP_TARGETS_ATTR, String.join("\n", groupTargets));
}
/**
* Provisions {@code AWS::IAM::ManagedPolicy} as a standalone customer-managed policy (has an ARN,
* must be detached before deletion), attaching it to any specified roles. Unlike an inline policy
@@ -2685,32 +2501,6 @@ public class CloudFormationResourceProvisioner {
deletePolicySafe(policyArn);
}
private void migrateLegacyManagedPolicy(StackResource resource) {
String policyArn = resource.getPhysicalId();
List<String> detachedRoles = new ArrayList<>();
try {
for (String roleName : managedPolicyRoleTargets(resource)) {
try {
iamService.detachRolePolicy(roleName, policyArn);
detachedRoles.add(roleName);
} catch (AwsException e) {
if (!"NoSuchEntity".equals(e.getErrorCode())) {
throw e;
}
}
}
deletePolicySafe(policyArn);
} catch (RuntimeException failure) {
Collections.reverse(detachedRoles);
for (String roleName : detachedRoles) {
CfnRollback.attemptIamCleanup(failure,
"reattach legacy policy " + policyArn + " to role " + roleName,
() -> iamService.attachRolePolicy(roleName, policyArn));
}
throw failure;
}
}
private List<String> managedPolicyRoleTargets(StackResource resource) {
String policyArn = resource.getPhysicalId();
String targets = resource.getAttributes().get("ManagedPolicyRoleTargets");
@@ -2730,89 +2520,6 @@ public class CloudFormationResourceProvisioner {
.toList();
}
/** Removes an {@code AWS::IAM::Policy} inline policy from each principal it was embedded in. */
private void deleteInlinePolicySafe(StackResource resource) {
cleanupPendingInlinePolicies(resource);
if (isIamManagedPolicyArn(resource.getPhysicalId())) {
// Before AWS::IAM::Policy was modelled as an inline policy, Floci persisted it as a
// customer-managed policy ARN. Delete that legacy representation during an upgrade.
deleteManagedPolicy(resource);
return;
}
String policyName = resource.getPhysicalId();
detachInline(resource.getAttributes().get("InlineRoleTargets"),
(name) -> iamService.deleteRolePolicy(name, policyName));
detachInline(resource.getAttributes().get("InlineUserTargets"),
(name) -> iamService.deleteUserPolicy(name, policyName));
detachInline(resource.getAttributes().get("InlineGroupTargets"),
(name) -> iamService.deleteGroupPolicy(name, policyName));
}
private boolean isIamManagedPolicyArn(String physicalId) {
return physicalId != null
&& physicalId.startsWith("arn:")
&& physicalId.contains(":iam::")
&& physicalId.contains(":policy/");
}
private void detachInline(String targets, java.util.function.Consumer<String> op) {
if (targets == null || targets.isBlank()) {
return;
}
for (String name : targets.split("\n")) {
if (!name.isBlank()) {
try {
op.accept(name);
} catch (AwsException e) {
// The principal may already be gone (deleted earlier in the same teardown),
// but permission and service failures must keep the stack in DELETE_FAILED.
if (!"NoSuchEntity".equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("Inline policy principal already gone, treating as detached: {0}", name);
}
}
}
}
private void deleteRemovedInlinePolicies(String previousTargets, List<String> currentTargets,
String previousPolicyName, String currentPolicyName,
java.util.function.Consumer<String> op) {
if (previousPolicyName == null) {
return;
}
Set<String> retainedTargets = new HashSet<>(currentTargets);
detachInline(previousTargets, name -> {
if (!previousPolicyName.equals(currentPolicyName) || !retainedTargets.contains(name)) {
op.accept(name);
}
});
}
private Set<String> inlineTargetSet(String targets) {
if (targets == null || targets.isBlank()) {
return Set.of();
}
return new HashSet<>(Arrays.asList(targets.split("\n")));
}
private void cleanupPendingInlinePolicies(StackResource resource) {
String policyName = resource.getAttributes().get(INLINE_CLEANUP_POLICY_NAME_ATTR);
if (policyName == null || policyName.isBlank()) {
return;
}
detachInline(resource.getAttributes().get(INLINE_CLEANUP_ROLE_TARGETS_ATTR),
principal -> iamService.deleteRolePolicy(principal, policyName));
detachInline(resource.getAttributes().get(INLINE_CLEANUP_USER_TARGETS_ATTR),
principal -> iamService.deleteUserPolicy(principal, policyName));
detachInline(resource.getAttributes().get(INLINE_CLEANUP_GROUP_TARGETS_ATTR),
principal -> iamService.deleteGroupPolicy(principal, policyName));
resource.getAttributes().remove(INLINE_CLEANUP_POLICY_NAME_ATTR);
resource.getAttributes().remove(INLINE_CLEANUP_ROLE_TARGETS_ATTR);
resource.getAttributes().remove(INLINE_CLEANUP_USER_TARGETS_ATTR);
resource.getAttributes().remove(INLINE_CLEANUP_GROUP_TARGETS_ATTR);
}
/**
* Generate an AWS-like physical name: {stackName}-{logicalId}-{randomSuffix}.
* Mirrors the naming pattern AWS CloudFormation uses when no explicit name is provided.
@@ -0,0 +1,352 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
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;
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.Consumer;
import java.util.stream.Collectors;
/**
* CloudFormation provisioning for {@code AWS::IAM::Policy}, which in AWS is an <em>inline</em>
* policy embedded in the named roles, users and groups (PutRolePolicy / PutUserPolicy /
* PutGroupPolicy), not a standalone managed policy. {@code Ref} returns the policy name and the
* resource exposes no ARN. Because an inline policy name is scoped to its owning principal, the
* name is stable across updates unless the template changes it, and a failed update rolls back the
* partially applied puts, recording anything it could not undo for the next provision to drain.
*
* <p>A physical id that is a managed policy ARN is a pre-inline upgrade: those stacks persisted the
* policy as a customer-managed policy, so the legacy representation is migrated (detached and
* deleted) here and removed on delete.
*/
@ApplicationScoped
public class IamPolicyCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(IamPolicyCfnProvisioner.class);
private static final String TYPE = "AWS::IAM::Policy";
private static final String INLINE_CLEANUP_POLICY_NAME_ATTR = "__FlociInlineCleanupPolicyName";
private static final String INLINE_CLEANUP_ROLE_TARGETS_ATTR = "__FlociInlineCleanupRoleTargets";
private static final String INLINE_CLEANUP_USER_TARGETS_ATTR = "__FlociInlineCleanupUserTargets";
private static final String INLINE_CLEANUP_GROUP_TARGETS_ATTR = "__FlociInlineCleanupGroupTargets";
private final IamService iamService;
@Inject
public IamPolicyCfnProvisioner(IamService iamService) {
this.iamService = iamService;
}
@Override
public Set<String> resourceTypes() {
return Set.of(TYPE);
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
CloudFormationTemplateEngine engine = ctx.engine();
String previousPolicyName = r.getPhysicalId();
String previousRoleTargets = r.getAttributes().get("InlineRoleTargets");
String previousUserTargets = r.getAttributes().get("InlineUserTargets");
String previousGroupTargets = r.getAttributes().get("InlineGroupTargets");
boolean legacyManagedPolicy = isIamManagedPolicyArn(previousPolicyName);
String policyName = ctx.resolveOptional(props, "PolicyName");
if (policyName == null || policyName.isBlank()) {
policyName = previousPolicyName != null && !previousPolicyName.isBlank() && !legacyManagedPolicy
? previousPolicyName
: ctx.generatePhysicalName(r.getLogicalId(), 128, false);
}
String document = ctx.resolvePolicyDocument(props);
final String name = policyName;
final String doc = document;
List<String> roleTargets = new ArrayList<>();
List<String> userTargets = new ArrayList<>();
List<String> groupTargets = new ArrayList<>();
try {
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) {
migrateLegacyManagedPolicy(r);
} else {
deleteRemovedInlinePolicies(previousRoleTargets, roleTargets,
previousPolicyName, policyName,
principal -> iamService.deleteRolePolicy(principal, previousPolicyName));
deleteRemovedInlinePolicies(previousUserTargets, userTargets,
previousPolicyName, policyName,
principal -> iamService.deleteUserPolicy(principal, previousPolicyName));
deleteRemovedInlinePolicies(previousGroupTargets, groupTargets,
previousPolicyName, policyName,
principal -> iamService.deleteGroupPolicy(principal, previousPolicyName));
}
} 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);
}
throw failure;
}
r.setPhysicalId(policyName);
r.getAttributes().remove("Arn");
recordInlinePolicyTargets(r, roleTargets, userTargets, groupTargets);
}
@Override
public void delete(StackResource resource, String region) {
cleanupPendingInlinePolicies(resource);
if (isIamManagedPolicyArn(resource.getPhysicalId())) {
// Legacy representation from before AWS::IAM::Policy was modelled as inline: delete the
// customer-managed policy it was persisted as.
deleteLegacyManagedPolicy(resource);
return;
}
String policyName = resource.getPhysicalId();
detachInline(resource.getAttributes().get("InlineRoleTargets"),
name -> iamService.deleteRolePolicy(name, policyName));
detachInline(resource.getAttributes().get("InlineUserTargets"),
name -> iamService.deleteUserPolicy(name, policyName));
detachInline(resource.getAttributes().get("InlineGroupTargets"),
name -> iamService.deleteGroupPolicy(name, policyName));
}
private void putInlinePolicy(JsonNode props, String propName, CloudFormationTemplateEngine engine,
List<String> successfulTargets, Consumer<String> op) {
if (props == null || !props.has(propName)) {
return;
}
for (JsonNode entry : props.get(propName)) {
String name = engine.resolve(entry);
if (name != null && !name.isBlank()) {
op.accept(name);
successfulTargets.add(name);
}
}
}
private void recordInlinePolicyTargets(StackResource resource, List<String> roleTargets,
List<String> userTargets, List<String> groupTargets) {
// Newlines are unambiguous because IAM principal names allow commas but never newlines.
resource.getAttributes().put("InlineRoleTargets", String.join("\n", roleTargets));
resource.getAttributes().put("InlineUserTargets", String.join("\n", userTargets));
resource.getAttributes().put("InlineGroupTargets", String.join("\n", groupTargets));
if (!roleTargets.isEmpty() || !userTargets.isEmpty() || !groupTargets.isEmpty()) {
resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
}
}
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));
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);
}
}
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,
List<String> roleTargets, List<String> userTargets,
List<String> groupTargets) {
if (roleTargets.isEmpty() && userTargets.isEmpty() && groupTargets.isEmpty()) {
return;
}
resource.getAttributes().put(INLINE_CLEANUP_POLICY_NAME_ATTR, policyName);
resource.getAttributes().put(INLINE_CLEANUP_ROLE_TARGETS_ATTR, String.join("\n", roleTargets));
resource.getAttributes().put(INLINE_CLEANUP_USER_TARGETS_ATTR, String.join("\n", userTargets));
resource.getAttributes().put(INLINE_CLEANUP_GROUP_TARGETS_ATTR, String.join("\n", groupTargets));
}
private void cleanupPendingInlinePolicies(StackResource resource) {
String policyName = resource.getAttributes().get(INLINE_CLEANUP_POLICY_NAME_ATTR);
if (policyName == null || policyName.isBlank()) {
return;
}
detachInline(resource.getAttributes().get(INLINE_CLEANUP_ROLE_TARGETS_ATTR),
principal -> iamService.deleteRolePolicy(principal, policyName));
detachInline(resource.getAttributes().get(INLINE_CLEANUP_USER_TARGETS_ATTR),
principal -> iamService.deleteUserPolicy(principal, policyName));
detachInline(resource.getAttributes().get(INLINE_CLEANUP_GROUP_TARGETS_ATTR),
principal -> iamService.deleteGroupPolicy(principal, policyName));
resource.getAttributes().remove(INLINE_CLEANUP_POLICY_NAME_ATTR);
resource.getAttributes().remove(INLINE_CLEANUP_ROLE_TARGETS_ATTR);
resource.getAttributes().remove(INLINE_CLEANUP_USER_TARGETS_ATTR);
resource.getAttributes().remove(INLINE_CLEANUP_GROUP_TARGETS_ATTR);
}
private void deleteRemovedInlinePolicies(String previousTargets, List<String> currentTargets,
String previousPolicyName, String currentPolicyName,
Consumer<String> op) {
if (previousPolicyName == null) {
return;
}
Set<String> retainedTargets = new HashSet<>(currentTargets);
detachInline(previousTargets, name -> {
if (!previousPolicyName.equals(currentPolicyName) || !retainedTargets.contains(name)) {
op.accept(name);
}
});
}
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) {
if (targets == null || targets.isBlank()) {
return;
}
for (String name : targets.split("\n")) {
if (!name.isBlank()) {
try {
op.accept(name);
} catch (AwsException e) {
// The principal may already be gone (deleted earlier in the same teardown),
// but permission and service failures must keep the stack in DELETE_FAILED.
if (!"NoSuchEntity".equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("Inline policy principal already gone, treating as detached: {0}", name);
}
}
}
}
private boolean isIamManagedPolicyArn(String physicalId) {
return physicalId != null
&& physicalId.startsWith("arn:")
&& physicalId.contains(":iam::")
&& physicalId.contains(":policy/");
}
// ── Legacy managed-policy representation (pre-inline upgrade path) ───────────
private void migrateLegacyManagedPolicy(StackResource resource) {
String policyArn = resource.getPhysicalId();
List<String> detachedRoles = new ArrayList<>();
try {
for (String roleName : managedPolicyRoleTargets(resource)) {
try {
iamService.detachRolePolicy(roleName, policyArn);
detachedRoles.add(roleName);
} catch (AwsException e) {
if (!"NoSuchEntity".equals(e.getErrorCode())) {
throw e;
}
}
}
deleteManagedPolicySafe(policyArn);
} catch (RuntimeException failure) {
Collections.reverse(detachedRoles);
for (String roleName : detachedRoles) {
CfnRollback.attemptIamCleanup(failure,
"reattach legacy policy " + policyArn + " to role " + roleName,
() -> iamService.attachRolePolicy(roleName, policyArn));
}
throw failure;
}
}
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();
}
}
@@ -113,6 +113,17 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio
return new ArrayList<>(engine.resolveStringList(props.get(name)));
}
/**
* The resolved {@code PolicyDocument} of an IAM policy resource as a JSON string, defaulting to
* an empty policy when the property is absent. Shared by the IAM policy provisioners so neither
* carries its own copy.
*/
public String resolvePolicyDocument(JsonNode props) {
JsonNode documentNode = props != null ? props.get("PolicyDocument") : null;
String resolved = documentNode != null ? engine.resolveJsonAttributeStrict(documentNode) : null;
return resolved != null ? resolved : "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
}
/**
* The physical name for a resource whose name is create-only: the template's name when it gives
* one, otherwise the name this resource already had, and only failing both a freshly generated