fix(cloudformation): model AWS::IAM::Policy as an inline policy (Fixes #1531) (#1800)

* fix(cloudformation): model AWS::IAM::Policy as an inline policy (Fixes #1531)

AWS::IAM::Policy is an inline policy embedded in the roles/users/groups it
names (PutRolePolicy/PutUserPolicy/PutGroupPolicy), not a standalone
managed policy. Floci provisioned it via iamService.createPolicy, giving
it an account-global name. When two stacks reused the same construct
sub-tree — as CDK does, emitting the same auto-generated PolicyName
(IamTaskRoleDefaultPolicy<hash>) on different roles — the second stack
failed with "Policy ... already exists" and rolled back, even though real
AWS scopes an inline policy's name to its owning principal.

Provision AWS::IAM::Policy as an inline policy attached to each named
principal, and remember the targets so a resource/stack delete detaches it
cleanly (an inline policy has no ARN and is removed with its principal).
AWS::IAM::ManagedPolicy keeps its standalone managed-policy behaviour and
now honours ManagedPolicyName. Two stacks reusing the same inline policy
name on different roles both deploy.

* fix(cloudformation): address review — log inline-detach failures, safe delimiter, test delete

Review feedback on the AWS::IAM::Policy inline-policy handling:

- detachInline no longer swallows exceptions silently (AGENTS.md forbids
  empty catch blocks); it logs at debug like the sibling *Safe helpers.
- Inline-policy target principals are joined/split on a newline instead of
  a comma. IAM friendly names permit commas ([\w+=,.@-]+) but never
  newlines, so a role/user/group name containing a comma no longer
  corrupts the target list and orphans the inline policy on delete.
- Added a test that deletes the stack and asserts the inline policy is
  detached (GetRolePolicy -> NoSuchEntity) from a role created outside the
  stack, so the detach path (deleteInlinePolicySafe/detachInline) is
  exercised rather than a cascade role delete.

* fix(cloudformation): surface IAM attachment failures

* fix(cloudformation): roll back IAM resources safely

* fix(cloudformation): roll back partial inline policies

* fix(cloudformation): detach removed IAM targets

* fix(cloudformation): verify IAM policy target updates

* fix(cloudformation): preserve inline policy update state

* fix(cloudformation): migrate legacy IAM policies

* fix(cloudformation): roll back legacy policy migration

---------

Co-authored-by: Alexy Grabov <Alexy.Grabov@cyberark.com>
This commit is contained in:
Alex BannaandAlexy Grabov authored and GitHub committed 2026-07-27 22:24:46 -05:00
1 parent 468e943c83
commit 264b909e87
5 files changed
+1961 -53

No files matched your search

@@ -56,6 +56,7 @@ import io.github.hectorvent.floci.services.elbv2.model.Rule;
import io.github.hectorvent.floci.services.elbv2.model.RuleCondition;
import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.kms.KmsService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.LambdaLayerService;
@@ -109,6 +110,12 @@ public class CloudFormationResourceProvisioner {
private static final String LAMBDA_CODE_IDENTITY_ATTR = "FlociLambdaCodeIdentity";
private static final String LAMBDA_NAME_MODE_ATTR = "FlociLambdaFunctionNameMode";
private static final String LAMBDA_PACKAGE_TYPE_ATTR = "FlociLambdaPackageType";
static final String ROLLBACK_OWNED_ATTR = "__FlociRollbackOwned";
static final String UPDATE_ROLLBACK_RESTORED_ATTR = "__FlociUpdateRollbackRestored";
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 LAMBDA_NAME_MODE_EXPLICIT = "explicit";
private static final String LAMBDA_NAME_MODE_GENERATED = "generated";
private static final int LAMBDA_DEFAULT_TIMEOUT_SECONDS = 3;
@@ -272,8 +279,9 @@ public class CloudFormationResourceProvisioner {
case "AWS::IAM::Role" -> provisionIamRole(resource, properties, engine, accountId, stackName);
case "AWS::IAM::User" -> provisionIamUser(resource, properties, engine, stackName);
case "AWS::IAM::AccessKey" -> provisionIamAccessKey(resource, properties, engine);
case "AWS::IAM::Policy", "AWS::IAM::ManagedPolicy" ->
provisionIamPolicy(resource, properties, engine, accountId, stackName);
case "AWS::IAM::Policy" -> provisionIamInlinePolicy(resource, properties, engine, stackName);
case "AWS::IAM::ManagedPolicy" ->
provisionIamManagedPolicy(resource, properties, engine, accountId, stackName);
case "AWS::IAM::InstanceProfile" -> provisionInstanceProfile(resource, properties, engine, accountId, stackName);
case "AWS::SSM::Parameter" -> provisionSsmParameter(resource, properties, engine, region, stackName);
case "AWS::KMS::Key" -> provisionKmsKey(resource, properties, engine, region, accountId);
@@ -403,6 +411,18 @@ 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)) {
deleteManagedPolicy(resource);
return;
}
delete(resourceType, resource.getPhysicalId(), region);
}
@@ -427,7 +447,11 @@ public class CloudFormationResourceProvisioner {
case "AWS::DynamoDB::Table" -> dynamoDbService.deleteTable(physicalId, region);
case "AWS::Lambda::Function" -> lambdaService.deleteFunction(region, physicalId);
case "AWS::IAM::Role" -> deleteRoleSafe(physicalId);
case "AWS::IAM::Policy", "AWS::IAM::ManagedPolicy" -> deletePolicySafe(physicalId);
// AWS::IAM::Policy is inline: it is removed together with its owning principal (see
// deleteRoleSafe), 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);
case "AWS::IAM::InstanceProfile" -> iamService.deleteInstanceProfile(physicalId);
case "AWS::SSM::Parameter" -> ssmService.deleteParameter(physicalId, region);
case "AWS::KMS::Key" -> {
@@ -1854,9 +1878,17 @@ public class CloudFormationResourceProvisioner {
private void provisionIamRole(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String accountId, String stackName) {
String existingRoleName = r.getPhysicalId();
String roleName = resolveOptional(props, "RoleName", engine);
if (roleName == null || roleName.isBlank()) {
roleName = generatePhysicalName(stackName, r.getLogicalId(), 64, false);
roleName = existingRoleName != null && !existingRoleName.isBlank()
? existingRoleName
: generatePhysicalName(stackName, r.getLogicalId(), 64, false);
}
final String resolvedRoleName = roleName;
if (existingRoleName != null && !existingRoleName.equals(resolvedRoleName)) {
throw new AwsException("ValidationError",
"Updating RoleName requires resource replacement, which is not supported.", 400);
}
String assumeDoc = props != null && props.has("AssumeRolePolicyDocument")
? props.get("AssumeRolePolicyDocument").toString()
@@ -1866,61 +1898,300 @@ public class CloudFormationResourceProvisioner {
path = "/";
}
String description = resolveOptional(props, "Description", engine);
List<String> managedPolicyArns = resolveStringList(props, "ManagedPolicyArns", engine);
IamRole role;
boolean createdRole = false;
try {
var role = iamService.createRole(roleName, path, assumeDoc, description, 3600, Map.of());
r.setPhysicalId(roleName);
r.getAttributes().put("Arn", role.getArn());
r.getAttributes().put("RoleId", role.getRoleId());
} catch (Exception e) {
// Role might already exist (e.g., re-deploy) — look it up
var role = iamService.getRole(roleName);
r.setPhysicalId(roleName);
r.getAttributes().put("Arn", role.getArn());
r.getAttributes().put("RoleId", role.getRoleId());
role = iamService.createRole(resolvedRoleName, path, assumeDoc, description, 3600, Map.of());
createdRole = true;
r.getAttributes().put(ROLLBACK_OWNED_ATTR, "true");
} catch (AwsException e) {
boolean stackAlreadyOwnsRole = existingRoleName != null
&& existingRoleName.equals(resolvedRoleName);
if (!stackAlreadyOwnsRole || !"EntityAlreadyExists".equals(e.getErrorCode())) {
throw e;
}
// Same-stack update/retry: both the physical name and immutable role ID must match.
// A role deleted out of band and recreated under the same name belongs to its new owner.
role = iamService.getRole(resolvedRoleName);
String existingRoleId = r.getAttributes().get("RoleId");
if (existingRoleId == null || existingRoleId.isBlank()
|| !existingRoleId.equals(role.getRoleId())) {
r.getAttributes().remove(ROLLBACK_OWNED_ATTR);
throw e;
}
}
// Attach managed policies if specified
if (props != null && props.has("ManagedPolicyArns")) {
for (JsonNode policyArn : props.get("ManagedPolicyArns")) {
try {
iamService.attachRolePolicy(roleName, engine.resolve(policyArn));
} catch (Exception ignored) {
r.setPhysicalId(resolvedRoleName);
r.getAttributes().put("Arn", role.getArn());
r.getAttributes().put("RoleId", role.getRoleId());
Set<String> originalPolicyArns = new HashSet<>(role.getAttachedPolicyArns());
LinkedHashSet<String> attachedByThisAttempt = new LinkedHashSet<>();
try {
for (String policyArn : managedPolicyArns) {
iamService.attachRolePolicy(resolvedRoleName, policyArn);
if (!originalPolicyArns.contains(policyArn)) {
attachedByThisAttempt.add(policyArn);
}
}
} catch (RuntimeException failure) {
List<String> rollbackArns = new ArrayList<>(attachedByThisAttempt);
Collections.reverse(rollbackArns);
boolean cleanupSucceeded = true;
for (String policyArn : rollbackArns) {
String cleanupDescription = "detach policy " + policyArn + " from role " + resolvedRoleName;
if (!attemptIamCleanup(failure, cleanupDescription,
() -> iamService.detachRolePolicy(resolvedRoleName, policyArn))) {
cleanupSucceeded = false;
}
}
if (createdRole) {
if (!attemptIamCleanup(failure, "delete role " + resolvedRoleName,
() -> iamService.deleteRole(resolvedRoleName))) {
cleanupSucceeded = false;
}
if (cleanupSucceeded) {
r.getAttributes().remove(ROLLBACK_OWNED_ATTR);
}
}
throw failure;
}
}
// ── IAM Policy ────────────────────────────────────────────────────────────
private void provisionIamPolicy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String accountId, String stackName) {
/**
* 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 = props != null && props.has("PolicyDocument")
? props.get("PolicyDocument").toString()
: "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
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(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 (!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
* a managed policy name is account-global, so its physical name is honoured verbatim from
* {@code ManagedPolicyName} when set, matching AWS.
*/
private void provisionIamManagedPolicy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String accountId, String stackName) {
String policyName = resolveOptional(props, "ManagedPolicyName", engine);
if (policyName == null || policyName.isBlank()) {
policyName = generatePhysicalName(stackName, r.getLogicalId(), 128, false);
}
String document = props != null && props.has("PolicyDocument")
? props.get("PolicyDocument").toString()
: "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
List<String> roleNames = resolveStringList(props, "Roles", engine);
var policy = iamService.createPolicy(policyName, "/", null, document, Map.of());
r.getAttributes().put(ROLLBACK_OWNED_ATTR, "true");
r.setPhysicalId(policy.getArn());
r.getAttributes().put("Arn", policy.getArn());
r.getAttributes().put("ManagedPolicyRoleTargets", String.join("\n", roleNames));
// Attach to roles if specified
if (props != null && props.has("Roles")) {
for (JsonNode role : props.get("Roles")) {
try {
iamService.attachRolePolicy(engine.resolve(role), policy.getArn());
} catch (Exception ignored) {
LinkedHashSet<String> attachedRoleNames = new LinkedHashSet<>();
try {
for (String roleName : roleNames) {
iamService.attachRolePolicy(roleName, policy.getArn());
attachedRoleNames.add(roleName);
}
} catch (RuntimeException failure) {
List<String> rollbackRoles = new ArrayList<>(attachedRoleNames);
Collections.reverse(rollbackRoles);
boolean cleanupSucceeded = true;
for (String roleName : rollbackRoles) {
String cleanupDescription = "detach policy " + policy.getArn() + " from role " + roleName;
if (!attemptIamCleanup(failure, cleanupDescription,
() -> iamService.detachRolePolicy(roleName, policy.getArn()))) {
cleanupSucceeded = false;
}
}
if (!attemptIamCleanup(failure, "delete policy " + policy.getArn(),
() -> iamService.deletePolicy(policy.getArn()))) {
cleanupSucceeded = false;
}
if (cleanupSucceeded) {
r.getAttributes().remove(ROLLBACK_OWNED_ATTR);
}
throw failure;
}
}
private void provisionIamManagedPolicy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String accountId, String stackName) {
provisionIamPolicy(r, props, engine, accountId, stackName);
private boolean attemptIamCleanup(RuntimeException primaryFailure, String description, Runnable cleanup) {
try {
cleanup.run();
return true;
} catch (RuntimeException cleanupFailure) {
primaryFailure.addSuppressed(cleanupFailure);
LOG.warnv("IAM rollback cleanup failed while attempting to {0}: {1}",
description, cleanupFailure.getMessage());
return false;
}
}
// ── IAM Instance Profile ──────────────────────────────────────────────────
@@ -3813,28 +4084,180 @@ public class CloudFormationResourceProvisioner {
}
private void deleteRoleSafe(String roleName) {
IamRole role;
try {
var role = iamService.getRole(roleName);
for (String policyArn : new ArrayList<>(role.getAttachedPolicyArns())) {
iamService.detachRolePolicy(roleName, policyArn);
role = iamService.getRole(roleName);
} catch (AwsException e) {
if (!"NoSuchEntity".equals(e.getErrorCode())) {
throw e;
}
for (String policyName : new ArrayList<>(role.getInlinePolicies().keySet())) {
iamService.deleteRolePolicy(roleName, policyName);
}
iamService.deleteRole(roleName);
} catch (Exception e) {
LOG.debugv("Could not delete role {0}: {1}", roleName, e.getMessage());
LOG.debugv("IAM role already gone, treating as deleted: {0}", roleName);
return;
}
for (String policyArn : new ArrayList<>(role.getAttachedPolicyArns())) {
iamService.detachRolePolicy(roleName, policyArn);
}
for (String policyName : new ArrayList<>(role.getInlinePolicies().keySet())) {
iamService.deleteRolePolicy(roleName, policyName);
}
iamService.deleteRole(roleName);
}
private void deletePolicySafe(String policyArn) {
try {
iamService.deletePolicy(policyArn);
} catch (Exception e) {
LOG.debugv("Could not delete policy {0}: {1}", policyArn, e.getMessage());
} catch (AwsException e) {
if (!"NoSuchEntity".equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("IAM policy already gone, treating as deleted: {0}", policyArn);
}
}
private void deleteManagedPolicy(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;
}
}
}
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) {
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");
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(java.util.stream.Collectors.joining("\n"));
}
if (targets == null || targets.isBlank()) {
return List.of();
}
return Arrays.stream(targets.split("\n"))
.filter(roleName -> !roleName.isBlank())
.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);
}
private void deleteSecretSafe(String secretId, String region) {
try {
secretsManagerService.deleteSecret(secretId, null, true, region);
@@ -588,13 +588,28 @@ public class CloudFormationService {
stack.setStatus("ROLLBACK_IN_PROGRESS");
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "ROLLBACK_IN_PROGRESS", failedResource.getStatusReason());
rollbackCreatedResources(stack, region);
stack.setStatus("ROLLBACK_COMPLETE");
List<String> rollbackFailures = rollbackCreatedResources(stack, region);
stack.setLastUpdatedTime(now());
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "ROLLBACK_COMPLETE", null);
LOG.infov("Stack {0} rolled back to a clean slate (ROLLBACK_COMPLETE)", stack.getStackName());
if (rollbackFailures.isEmpty()) {
stack.setStatus("ROLLBACK_COMPLETE");
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "ROLLBACK_COMPLETE", null);
LOG.infov("Stack {0} rolled back to a clean slate (ROLLBACK_COMPLETE)", stack.getStackName());
} else {
String reason = "The following resource(s) failed to roll back: ["
+ String.join(", ", rollbackFailures) + "].";
stack.setStatus("ROLLBACK_FAILED");
stack.setStatusReason(reason);
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "ROLLBACK_FAILED", reason);
LOG.errorv("Stack {0} rollback failed: {1}", stack.getStackName(), reason);
}
} else {
if ("true".equals(failedResource.getAttributes().remove(
CloudFormationResourceProvisioner.UPDATE_ROLLBACK_RESTORED_ATTR))) {
failedResource.setStatus("CREATE_COMPLETE");
failedResource.setStatusReason(null);
}
stack.setStatus("UPDATE_ROLLBACK_COMPLETE");
stack.setLastUpdatedTime(now());
addEvent(stack, stack.getStackName(), stack.getStackId(),
@@ -604,20 +619,38 @@ public class CloudFormationService {
persistStack(stack);
}
/** Deletes every resource successfully created in this execution, in reverse order. */
private void rollbackCreatedResources(Stack stack, String region) {
/** Deletes every resource created in this execution, in reverse order. */
private List<String> rollbackCreatedResources(Stack stack, String region) {
List<StackResource> resources = new ArrayList<>(stack.getResources().values());
Collections.reverse(resources);
List<String> failedResources = new ArrayList<>();
for (StackResource resource : resources) {
if (resource.getPhysicalId() != null && "CREATE_COMPLETE".equals(resource.getStatus())) {
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "DELETE_IN_PROGRESS", null);
provisioner.delete(resource.getResourceType(), resource.getPhysicalId(), region);
boolean completed = "CREATE_COMPLETE".equals(resource.getStatus());
boolean ownedFailedResource = "CREATE_FAILED".equals(resource.getStatus())
&& "true".equals(resource.getAttributes().get(
CloudFormationResourceProvisioner.ROLLBACK_OWNED_ATTR));
if (resource.getPhysicalId() == null || (!completed && !ownedFailedResource)) {
continue;
}
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "DELETE_IN_PROGRESS", null);
try {
provisioner.delete(resource, region);
resource.setStatus("DELETE_COMPLETE");
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "DELETE_COMPLETE", null);
} catch (Exception e) {
failedResources.add(resource.getLogicalId());
resource.setStatus("DELETE_FAILED");
resource.setStatusReason(e.getMessage());
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "DELETE_FAILED", e.getMessage());
LOG.warnv("Failed to roll back {0} ({1}) in stack {2}: {3}",
resource.getResourceType(), resource.getPhysicalId(),
stack.getStackName(), e.getMessage());
}
}
return failedResources;
}
private void deleteStackResources(Stack stack, String region) {