diff --git a/CHANGELOG.md b/CHANGELOG.md index 22afde83e0..69f035fca7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **iam:** seeded `AWSCloudTrail_FullAccess` and `AWSCloudTrail_ReadOnlyAccess` AWS managed policies. - **iam:** distinguish `s3:GetObjectAcl` / `s3:PutObjectAcl` / `s3:Get|Put|DeleteObjectTagging` from base S3 ops via `?acl` / `?tagging` query parameters when resolving an action for IAM enforcement. +### Fixed + +- **cloudformation:** report failed rollback cleanup as `ROLLBACK_FAILED`, detach removed IAM inline-policy targets on stack updates, and migrate the legacy managed-policy representation during update or deletion ([#1800](https://github.com/floci-io/floci/pull/1800)) + ## [1.5.33] - 2026-07-15 ### Added diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java index 4ab510a719..75b34a830b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java @@ -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 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 originalPolicyArns = new HashSet<>(role.getAttachedPolicyArns()); + LinkedHashSet attachedByThisAttempt = new LinkedHashSet<>(); + try { + for (String policyArn : managedPolicyArns) { + iamService.attachRolePolicy(resolvedRoleName, policyArn); + if (!originalPolicyArns.contains(policyArn)) { + attachedByThisAttempt.add(policyArn); } } + } catch (RuntimeException failure) { + List 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 inline policy embedded in the + * named roles/users/groups (equivalent to PutRolePolicy/PutUserPolicy/PutGroupPolicy) — not + * 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 roleTargets = new ArrayList<>(); + List userTargets = new ArrayList<>(); + List 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 successfulTargets, + java.util.function.Consumer 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 roleTargets, + List userTargets, + List 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 appliedRoleTargets, + List appliedUserTargets, + List appliedGroupTargets) { + List pendingRoles = rollbackAppliedInlinePolicies( + failure, previousRoleTargets, appliedRoleTargets, previousPolicyName, currentPolicyName, + principal -> iamService.deleteRolePolicy(principal, currentPolicyName)); + List pendingUsers = rollbackAppliedInlinePolicies( + failure, previousUserTargets, appliedUserTargets, previousPolicyName, currentPolicyName, + principal -> iamService.deleteUserPolicy(principal, currentPolicyName)); + List 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 rollbackAppliedInlinePolicies( + RuntimeException failure, + String previousTargets, + List appliedTargets, + String previousPolicyName, + String currentPolicyName, + java.util.function.Consumer cleanup) { + Set previous = inlineTargetSet(previousTargets); + List rollbackTargets = new ArrayList<>(); + for (String target : new LinkedHashSet<>(appliedTargets)) { + if (!previousPolicyName.equals(currentPolicyName) || !previous.contains(target)) { + rollbackTargets.add(target); + } + } + Collections.reverse(rollbackTargets); + + List 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 roleTargets, + List userTargets, + List 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 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 attachedRoleNames = new LinkedHashSet<>(); + try { + for (String roleName : roleNames) { + iamService.attachRolePolicy(roleName, policy.getArn()); + attachedRoleNames.add(roleName); + } + } catch (RuntimeException failure) { + List 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 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 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 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 currentTargets, + String previousPolicyName, String currentPolicyName, + java.util.function.Consumer op) { + if (previousPolicyName == null) { + return; + } + Set retainedTargets = new HashSet<>(currentTargets); + detachInline(previousTargets, name -> { + if (!previousPolicyName.equals(currentPolicyName) || !retainedTargets.contains(name)) { + op.accept(name); + } + }); + } + + private Set 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); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java index ac724f8cd9..3455d6e485 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java @@ -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 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 rollbackCreatedResources(Stack stack, String region) { List resources = new ArrayList<>(stack.getResources().values()); Collections.reverse(resources); + List 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) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java new file mode 100644 index 0000000000..a7ab054b94 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java @@ -0,0 +1,650 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry; +import io.github.hectorvent.floci.services.iam.IamService; +import io.github.hectorvent.floci.services.iam.model.IamPolicy; +import io.github.hectorvent.floci.services.iam.model.IamRole; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class CloudFormationIamAttachmentProvisionerTest { + + private static final String ACCOUNT_ID = "000000000000"; + private static final String EXISTING_POLICY = "arn:aws:iam::aws:policy/ReadOnlyAccess"; + private static final String NEW_POLICY = "arn:aws:iam::aws:policy/SecurityAudit"; + private static final String MISSING_POLICY = "arn:aws:iam::aws:policy/Missing"; + + private final ObjectMapper mapper = new ObjectMapper(); + private IamService iamService; + private CloudFormationResourceProvisioner provisioner; + + @BeforeEach + void setUp() { + iamService = mock(IamService.class); + provisioner = new CloudFormationResourceProvisioner( + null, null, null, null, null, iamService, null, null, null, null, + null, null, null, null, null, null, + mapper, + null, null, null, null, null, null, null, + null, null, null, null, null, null, null, + new CloudFormationResourceRegistry(List.of())); + } + + @Test + void newRoleAttachmentFailureDetachesPolicyThenDeletesRole() { + IamRole role = role("new-role"); + when(iamService.createRole("new-role", "/", emptyTrustPolicy(), null, 3600, Map.of())) + .thenReturn(role); + doThrow(new AwsException("NoSuchEntity", "missing policy", 404)) + .when(iamService).attachRolePolicy("new-role", MISSING_POLICY); + + StackResource result = provisionRole("new-role", List.of(NEW_POLICY, MISSING_POLICY)); + + assertEquals("CREATE_FAILED", result.getStatus()); + assertEquals("missing policy", result.getStatusReason()); + InOrder cleanup = inOrder(iamService); + cleanup.verify(iamService).detachRolePolicy("new-role", NEW_POLICY); + cleanup.verify(iamService).deleteRole("new-role"); + } + + @Test + void sameStackRoleRetryPreservesOriginalPoliciesAndRole() { + IamRole role = role("existing-role"); + role.getAttachedPolicyArns().add(EXISTING_POLICY); + when(iamService.createRole("existing-role", "/", emptyTrustPolicy(), null, 3600, Map.of())) + .thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409)); + when(iamService.getRole("existing-role")).thenReturn(role); + doThrow(new AwsException("NoSuchEntity", "missing policy", 404)) + .when(iamService).attachRolePolicy("existing-role", MISSING_POLICY); + + StackResource result = provisionRole( + "existing-role", List.of(EXISTING_POLICY, NEW_POLICY, MISSING_POLICY), + "existing-role", Map.of("RoleId", role.getRoleId())); + + assertEquals("CREATE_FAILED", result.getStatus()); + verify(iamService).detachRolePolicy("existing-role", NEW_POLICY); + verify(iamService, never()).detachRolePolicy("existing-role", EXISTING_POLICY); + verify(iamService, never()).deleteRole("existing-role"); + } + + @Test + void freshRoleCollisionDoesNotAdoptUserOwnedRole() { + when(iamService.createRole("external-role", "/", emptyTrustPolicy(), null, 3600, Map.of())) + .thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409)); + + StackResource result = provisionRole("external-role", List.of(NEW_POLICY)); + + assertEquals("CREATE_FAILED", result.getStatus()); + assertNull(result.getPhysicalId()); + verify(iamService, never()).getRole("external-role"); + verify(iamService, never()).attachRolePolicy("external-role", NEW_POLICY); + verify(iamService, never()).deleteRole("external-role"); + } + + @Test + void generatedRoleNameRemainsStableOnUpdate() { + IamRole role = role("generated-role"); + when(iamService.createRole("generated-role", "/", emptyTrustPolicy(), null, 3600, Map.of())) + .thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409)); + when(iamService.getRole("generated-role")).thenReturn(role); + + StackResource result = provision( + "Role", "AWS::IAM::Role", "{}", "generated-role", + Map.of("RoleId", role.getRoleId())); + + assertEquals("CREATE_COMPLETE", result.getStatus()); + assertEquals("generated-role", result.getPhysicalId()); + } + + @Test + void sameNameRoleWithDifferentIdIsNotAdopted() { + IamRole replacement = role("same-name"); + when(iamService.createRole("same-name", "/", emptyTrustPolicy(), null, 3600, Map.of())) + .thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409)); + when(iamService.getRole("same-name")).thenReturn(replacement); + + StackResource result = provision( + "Role", "AWS::IAM::Role", """ + {"RoleName":"same-name","ManagedPolicyArns":["%s"]} + """.formatted(NEW_POLICY), "same-name", + Map.of("RoleId", "AROAOLD", CloudFormationResourceProvisioner.ROLLBACK_OWNED_ATTR, "true")); + + assertEquals("CREATE_FAILED", result.getStatus()); + assertEquals("already exists", result.getStatusReason()); + assertNull(result.getAttributes().get(CloudFormationResourceProvisioner.ROLLBACK_OWNED_ATTR)); + verify(iamService, never()).attachRolePolicy("same-name", NEW_POLICY); + verify(iamService, never()).deleteRole("same-name"); + } + + @Test + void roleNameChangeFailsBeforeCreatingReplacement() { + StackResource result = provision( + "Role", "AWS::IAM::Role", "{\"RoleName\":\"new-role\"}", + "old-role", Map.of()); + + assertEquals("CREATE_FAILED", result.getStatus()); + assertEquals("Updating RoleName requires resource replacement, which is not supported.", + result.getStatusReason()); + verify(iamService, never()).createRole( + "new-role", "/", emptyTrustPolicy(), null, 3600, Map.of()); + } + + @Test + void unexpectedRoleCreationFailureIsNotTreatedAsAnExistingRole() { + when(iamService.createRole("denied-role", "/", emptyTrustPolicy(), null, 3600, Map.of())) + .thenThrow(new AwsException("AccessDenied", "denied", 403)); + + StackResource result = provisionRole("denied-role", List.of()); + + assertEquals("CREATE_FAILED", result.getStatus()); + assertEquals("denied", result.getStatusReason()); + verify(iamService, never()).getRole("denied-role"); + } + + @Test + void managedPolicyAttachmentFailureDetachesRolesThenDeletesPolicy() { + String policyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/test-policy"; + IamPolicy policy = new IamPolicy( + "ANPATEST", "test-policy", "/", policyArn, null, "{}"); + when(iamService.createPolicy("test-policy", "/", null, policyDocument(), Map.of())) + .thenReturn(policy); + doThrow(new AwsException("NoSuchEntity", "missing role", 404)) + .when(iamService).attachRolePolicy("missing-role", policyArn); + + StackResource result = provision("ManagedPolicy", "AWS::IAM::ManagedPolicy", """ + { + "ManagedPolicyName": "test-policy", + "PolicyDocument": {"Version": "2012-10-17", "Statement": []}, + "Roles": ["existing-role", "missing-role"] + } + """); + + assertEquals("CREATE_FAILED", result.getStatus()); + InOrder cleanup = inOrder(iamService); + cleanup.verify(iamService).detachRolePolicy("existing-role", policyArn); + cleanup.verify(iamService).deletePolicy(policyArn); + verify(iamService, never()).deleteRole("existing-role"); + } + + @Test + void cleanupFailureDoesNotMaskPrimaryFailureOrSkipDeletion() { + IamRole role = role("cleanup-role"); + when(iamService.createRole("cleanup-role", "/", emptyTrustPolicy(), null, 3600, Map.of())) + .thenReturn(role); + doThrow(new AwsException("NoSuchEntity", "primary failure", 404)) + .when(iamService).attachRolePolicy("cleanup-role", MISSING_POLICY); + doThrow(new AwsException("ServiceFailure", "cleanup failure", 500)) + .when(iamService).detachRolePolicy("cleanup-role", NEW_POLICY); + + StackResource result = provisionRole("cleanup-role", List.of(NEW_POLICY, MISSING_POLICY)); + + assertEquals("CREATE_FAILED", result.getStatus()); + assertEquals("primary failure", result.getStatusReason()); + verify(iamService).detachRolePolicy("cleanup-role", NEW_POLICY); + verify(iamService).deleteRole("cleanup-role"); + } + + @Test + void inlinePolicyAttachmentFailurePreservesSuccessfulTargetsForRollback() { + String policyName = "test-inline-policy"; + doThrow(new AwsException("NoSuchEntity", "missing role", 404)) + .when(iamService).putRolePolicy("missing-role", policyName, policyDocument()); + + StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """ + { + "PolicyName": "%s", + "PolicyDocument": {"Version": "2012-10-17", "Statement": []}, + "Roles": ["existing-role", "missing-role"] + } + """.formatted(policyName)); + + assertEquals("CREATE_FAILED", result.getStatus()); + assertEquals("existing-role", result.getAttributes().get("InlineRoleTargets")); + assertEquals("true", result.getAttributes().get( + CloudFormationResourceProvisioner.ROLLBACK_OWNED_ATTR)); + + provisioner.delete(result, "us-east-1"); + + verify(iamService).deleteRolePolicy("existing-role", policyName); + verify(iamService, never()).deleteRolePolicy("missing-role", policyName); + } + + @Test + void inlinePolicyUpdateDetachesRemovedTargetsAcrossPrincipalTypes() { + String policyName = "test-inline-policy"; + + StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """ + { + "PolicyName": "%s", + "PolicyDocument": {"Version": "2012-10-17", "Statement": []}, + "Roles": ["retained-role", "added-role"], + "Users": ["added-user"], + "Groups": ["retained-group"] + } + """.formatted(policyName), policyName, Map.of( + "InlineRoleTargets", "removed-role\nretained-role", + "InlineUserTargets", "removed-user", + "InlineGroupTargets", "removed-group\nretained-group")); + + assertEquals("CREATE_COMPLETE", result.getStatus()); + assertEquals("retained-role\nadded-role", result.getAttributes().get("InlineRoleTargets")); + assertEquals("added-user", result.getAttributes().get("InlineUserTargets")); + assertEquals("retained-group", result.getAttributes().get("InlineGroupTargets")); + verify(iamService).deleteRolePolicy("removed-role", policyName); + verify(iamService, never()).deleteRolePolicy("retained-role", policyName); + verify(iamService).deleteUserPolicy("removed-user", policyName); + verify(iamService).deleteGroupPolicy("removed-group", policyName); + verify(iamService, never()).deleteGroupPolicy("retained-group", policyName); + } + + @Test + void inlinePolicyNameChangeDeletesOldPolicyFromRetainedTargets() { + String previousPolicyName = "previous-inline-policy"; + String currentPolicyName = "current-inline-policy"; + + StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """ + { + "PolicyName": "%s", + "PolicyDocument": {"Version": "2012-10-17", "Statement": []}, + "Roles": ["retained-role"], + "Users": ["retained-user"], + "Groups": ["retained-group"] + } + """.formatted(currentPolicyName), previousPolicyName, Map.of( + "InlineRoleTargets", "retained-role", + "InlineUserTargets", "retained-user", + "InlineGroupTargets", "retained-group")); + + assertEquals("CREATE_COMPLETE", result.getStatus()); + assertEquals(currentPolicyName, result.getPhysicalId()); + verify(iamService).deleteRolePolicy("retained-role", previousPolicyName); + verify(iamService).deleteUserPolicy("retained-user", previousPolicyName); + verify(iamService).deleteGroupPolicy("retained-group", previousPolicyName); + } + + @Test + void inlinePolicyUpdateFailurePreservesPreviousTargetsAndRemovesNewAttachments() { + String policyName = "test-inline-policy"; + doThrow(new AwsException("NoSuchEntity", "missing user", 404)) + .when(iamService).putUserPolicy("missing-user", policyName, policyDocument()); + + StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """ + { + "PolicyName": "%s", + "PolicyDocument": {"Version": "2012-10-17", "Statement": []}, + "Roles": ["new-role"], + "Users": ["missing-user"] + } + """.formatted(policyName), policyName, Map.of( + "InlineRoleTargets", "old-role", + "InlineUserTargets", "old-user", + "InlineGroupTargets", "old-group")); + + assertEquals("CREATE_FAILED", result.getStatus()); + assertEquals(policyName, result.getPhysicalId()); + assertEquals("old-role", result.getAttributes().get("InlineRoleTargets")); + assertEquals("old-user", result.getAttributes().get("InlineUserTargets")); + assertEquals("old-group", result.getAttributes().get("InlineGroupTargets")); + assertEquals("true", result.getAttributes().get( + CloudFormationResourceProvisioner.UPDATE_ROLLBACK_RESTORED_ATTR)); + verify(iamService).deleteRolePolicy("new-role", policyName); + verify(iamService, never()).deleteRolePolicy("old-role", policyName); + } + + @Test + void inlinePolicyNameChangeFailureRemovesNewNameAndPreservesOldMetadata() { + String previousPolicyName = "previous-inline-policy"; + String currentPolicyName = "current-inline-policy"; + doThrow(new AwsException("NoSuchEntity", "missing user", 404)) + .when(iamService).putUserPolicy("missing-user", currentPolicyName, policyDocument()); + + StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """ + { + "PolicyName": "%s", + "PolicyDocument": {"Version": "2012-10-17", "Statement": []}, + "Roles": ["retained-role"], + "Users": ["missing-user"] + } + """.formatted(currentPolicyName), previousPolicyName, Map.of( + "InlineRoleTargets", "retained-role", + "InlineUserTargets", "", + "InlineGroupTargets", "")); + + assertEquals("CREATE_FAILED", result.getStatus()); + assertEquals(previousPolicyName, result.getPhysicalId()); + assertEquals("retained-role", result.getAttributes().get("InlineRoleTargets")); + verify(iamService).deleteRolePolicy("retained-role", currentPolicyName); + verify(iamService, never()).deleteRolePolicy("retained-role", previousPolicyName); + } + + @Test + void generatedInlinePolicyNameRemainsStableOnUpdate() { + String policyName = "generated-inline-policy"; + + StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """ + { + "PolicyDocument": {"Version": "2012-10-17", "Statement": []}, + "Roles": ["retained-role"] + } + """, policyName, Map.of("InlineRoleTargets", "retained-role")); + + assertEquals("CREATE_COMPLETE", result.getStatus()); + assertEquals(policyName, result.getPhysicalId()); + verify(iamService).putRolePolicy("retained-role", policyName, policyDocument()); + } + + @Test + void legacyManagedInlinePolicyMigratesDuringUpdate() { + String legacyPolicyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/legacy-policy"; + IamRole oldRole = role("old-role"); + oldRole.getAttachedPolicyArns().add(legacyPolicyArn); + when(iamService.listRoles("/")).thenReturn(List.of(oldRole)); + + StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """ + { + "PolicyDocument": {"Version": "2012-10-17", "Statement": []}, + "Roles": ["new-role"] + } + """, legacyPolicyArn, Map.of("Arn", legacyPolicyArn)); + + assertEquals("CREATE_COMPLETE", result.getStatus()); + assertFalse(result.getPhysicalId().startsWith("arn:")); + assertNull(result.getAttributes().get("Arn")); + InOrder migration = inOrder(iamService); + migration.verify(iamService).putRolePolicy("new-role", result.getPhysicalId(), policyDocument()); + migration.verify(iamService).detachRolePolicy("old-role", legacyPolicyArn); + migration.verify(iamService).deletePolicy(legacyPolicyArn); + } + + @Test + void failedLegacyMigrationPreservesManagedPolicyForRetry() { + String legacyPolicyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/legacy-policy"; + doThrow(new AwsException("NoSuchEntity", "missing user", 404)) + .when(iamService).putUserPolicy(eq("missing-user"), anyString(), eq(policyDocument())); + + StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """ + { + "PolicyDocument": {"Version": "2012-10-17", "Statement": []}, + "Users": ["missing-user"] + } + """, legacyPolicyArn, Map.of("Arn", legacyPolicyArn)); + + assertEquals("CREATE_FAILED", result.getStatus()); + assertEquals(legacyPolicyArn, result.getPhysicalId()); + assertEquals(legacyPolicyArn, result.getAttributes().get("Arn")); + verify(iamService, never()).deletePolicy(legacyPolicyArn); + } + + @Test + void legacyMigrationRestoresDetachedRoleWhenPolicyDeletionFails() { + String legacyPolicyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/legacy-policy"; + IamRole oldRole = role("old-role"); + oldRole.getAttachedPolicyArns().add(legacyPolicyArn); + when(iamService.listRoles("/")).thenReturn(List.of(oldRole)); + doThrow(new AwsException("ServiceFailure", "delete failed", 500)) + .when(iamService).deletePolicy(legacyPolicyArn); + + StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """ + { + "PolicyDocument": {"Version": "2012-10-17", "Statement": []}, + "Roles": ["new-role"] + } + """, legacyPolicyArn, Map.of("Arn", legacyPolicyArn)); + + assertEquals("CREATE_FAILED", result.getStatus()); + assertEquals(legacyPolicyArn, result.getPhysicalId()); + assertEquals(legacyPolicyArn, result.getAttributes().get("Arn")); + InOrder rollback = inOrder(iamService); + rollback.verify(iamService).putRolePolicy(eq("new-role"), anyString(), eq(policyDocument())); + rollback.verify(iamService).detachRolePolicy("old-role", legacyPolicyArn); + rollback.verify(iamService).deletePolicy(legacyPolicyArn); + rollback.verify(iamService).attachRolePolicy("old-role", legacyPolicyArn); + rollback.verify(iamService).deleteRolePolicy(eq("new-role"), anyString()); + } + + @Test + void inlinePolicyUpdateTracksFailedCleanupForStackDeletion() { + String policyName = "test-inline-policy"; + doThrow(new AwsException("NoSuchEntity", "missing user", 404)) + .when(iamService).putUserPolicy("missing-user", policyName, policyDocument()); + doThrow(new AwsException("AccessDenied", "cleanup denied", 403)) + .doNothing() + .when(iamService).deleteRolePolicy("new-role", policyName); + + StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """ + { + "PolicyName": "%s", + "PolicyDocument": {"Version": "2012-10-17", "Statement": []}, + "Roles": ["new-role"], + "Users": ["missing-user"] + } + """.formatted(policyName), policyName, + Map.of("InlineRoleTargets", "old-role")); + + assertEquals("CREATE_FAILED", result.getStatus()); + assertEquals("old-role", result.getAttributes().get("InlineRoleTargets")); + + provisioner.delete(result, "us-east-1"); + + verify(iamService, times(2)).deleteRolePolicy("new-role", policyName); + verify(iamService).deleteRolePolicy("old-role", policyName); + } + + @Test + void inlinePolicyRemovalFailureDoesNotCommitTheNewTargetLedger() { + String policyName = "test-inline-policy"; + doThrow(new AwsException("AccessDenied", "cannot remove old role", 403)) + .when(iamService).deleteRolePolicy("old-role", policyName); + + StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """ + { + "PolicyName": "%s", + "PolicyDocument": {"Version": "2012-10-17", "Statement": []}, + "Roles": ["new-role"] + } + """.formatted(policyName), policyName, + Map.of("InlineRoleTargets", "old-role")); + + assertEquals("CREATE_FAILED", result.getStatus()); + assertEquals("old-role", result.getAttributes().get("InlineRoleTargets")); + verify(iamService).deleteRolePolicy("old-role", policyName); + verify(iamService).deleteRolePolicy("new-role", policyName); + } + + @Test + void inlinePolicyDeletionIgnoresAlreadyMissingPrincipal() { + String policyName = "test-inline-policy"; + StackResource resource = new StackResource(); + resource.setResourceType("AWS::IAM::Policy"); + resource.setPhysicalId(policyName); + resource.setAttributes(Map.of("InlineRoleTargets", "missing-role")); + doThrow(new AwsException("NoSuchEntity", "already gone", 404)) + .when(iamService).deleteRolePolicy("missing-role", policyName); + + provisioner.delete(resource, "us-east-1"); + + verify(iamService).deleteRolePolicy("missing-role", policyName); + } + + @Test + void inlinePolicyDeletionPropagatesUnexpectedFailure() { + String policyName = "test-inline-policy"; + StackResource resource = new StackResource(); + resource.setResourceType("AWS::IAM::Policy"); + resource.setPhysicalId(policyName); + resource.setAttributes(Map.of("InlineRoleTargets", "role-a")); + doThrow(new AwsException("AccessDenied", "denied", 403)) + .when(iamService).deleteRolePolicy("role-a", policyName); + + AwsException failure = assertThrows(AwsException.class, + () -> provisioner.delete(resource, "us-east-1")); + + assertEquals("AccessDenied", failure.getErrorCode()); + } + + @Test + void legacyManagedInlinePolicyIsDetachedAndDeleted() { + String policyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/legacy-policy"; + IamRole role = role("legacy-role"); + role.getAttachedPolicyArns().add(policyArn); + when(iamService.listRoles("/")).thenReturn(List.of(role)); + StackResource resource = new StackResource(); + resource.setResourceType("AWS::IAM::Policy"); + resource.setPhysicalId(policyArn); + resource.setAttributes(Map.of("Arn", policyArn)); + + provisioner.delete(resource, "us-east-1"); + + InOrder deletion = inOrder(iamService); + deletion.verify(iamService).detachRolePolicy("legacy-role", policyArn); + deletion.verify(iamService).deletePolicy(policyArn); + } + + @Test + void managedPolicyDeletionDetachesStoredRolesBeforeDeletingPolicy() { + String policyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/test-policy"; + StackResource resource = new StackResource(); + resource.setResourceType("AWS::IAM::ManagedPolicy"); + resource.setPhysicalId(policyArn); + resource.setAttributes(Map.of("ManagedPolicyRoleTargets", "role-a\nrole-b")); + + provisioner.delete(resource, "us-east-1"); + + InOrder deletion = inOrder(iamService); + deletion.verify(iamService).detachRolePolicy("role-a", policyArn); + deletion.verify(iamService).detachRolePolicy("role-b", policyArn); + deletion.verify(iamService).deletePolicy(policyArn); + } + + @Test + void managedPolicyDeletionIgnoresAlreadyMissingAttachments() { + String policyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/test-policy"; + StackResource resource = new StackResource(); + resource.setResourceType("AWS::IAM::ManagedPolicy"); + resource.setPhysicalId(policyArn); + resource.setAttributes(Map.of("ManagedPolicyRoleTargets", "missing-role")); + doThrow(new AwsException("NoSuchEntity", "already gone", 404)) + .when(iamService).detachRolePolicy("missing-role", policyArn); + + provisioner.delete(resource, "us-east-1"); + + verify(iamService).deletePolicy(policyArn); + } + + @Test + void managedPolicyDeletionDiscoversTargetsForOlderPersistedStacks() { + String policyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/test-policy"; + IamRole role = role("legacy-role"); + role.getAttachedPolicyArns().add(policyArn); + when(iamService.listRoles("/")).thenReturn(List.of(role)); + StackResource resource = new StackResource(); + resource.setResourceType("AWS::IAM::ManagedPolicy"); + resource.setPhysicalId(policyArn); + resource.setAttributes(Map.of()); + + provisioner.delete(resource, "us-east-1"); + + InOrder deletion = inOrder(iamService); + deletion.verify(iamService).detachRolePolicy("legacy-role", policyArn); + deletion.verify(iamService).deletePolicy(policyArn); + } + + @Test + void managedPolicyDeletionPropagatesUnexpectedDetachFailure() { + String policyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/test-policy"; + StackResource resource = new StackResource(); + resource.setResourceType("AWS::IAM::ManagedPolicy"); + resource.setPhysicalId(policyArn); + resource.setAttributes(Map.of("ManagedPolicyRoleTargets", "role-a")); + doThrow(new AwsException("AccessDenied", "denied", 403)) + .when(iamService).detachRolePolicy("role-a", policyArn); + + AwsException failure = assertThrows(AwsException.class, + () -> provisioner.delete(resource, "us-east-1")); + + assertEquals("AccessDenied", failure.getErrorCode()); + verify(iamService, never()).deletePolicy(policyArn); + } + + private StackResource provisionRole(String roleName, List policyArns) { + return provisionRole(roleName, policyArns, null); + } + + private StackResource provisionRole(String roleName, List policyArns, + String existingPhysicalId) { + return provisionRole(roleName, policyArns, existingPhysicalId, Map.of()); + } + + private StackResource provisionRole(String roleName, List policyArns, + String existingPhysicalId, + Map existingAttributes) { + String policies = policyArns.stream() + .map(value -> "\"" + value + "\"") + .reduce((left, right) -> left + "," + right) + .orElse(""); + return provision("Role", "AWS::IAM::Role", """ + {"RoleName":"%s","ManagedPolicyArns":[%s]} + """.formatted(roleName, policies), existingPhysicalId, existingAttributes); + } + + private StackResource provision(String logicalId, String type, String json) { + return provision(logicalId, type, json, null, Map.of()); + } + + private StackResource provision(String logicalId, String type, String json, + String existingPhysicalId, Map existingAttributes) { + return provisioner.provision(logicalId, type, props(json), engine(), + "us-east-1", ACCOUNT_ID, "test-stack", existingPhysicalId, existingAttributes); + } + + private CloudFormationTemplateEngine engine() { + return new CloudFormationTemplateEngine( + ACCOUNT_ID, "us-east-1", "test-stack", "stack/id", + Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), mapper, + (Function) name -> null); + } + + private JsonNode props(String json) { + try { + return mapper.readTree(json); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private static IamRole role(String name) { + return new IamRole("AROA" + name, name, "/", + "arn:aws:iam::" + ACCOUNT_ID + ":role/" + name, emptyTrustPolicy()); + } + + private static String emptyTrustPolicy() { + return "{\"Version\":\"2012-10-17\",\"Statement\":[]}"; + } + + private static String policyDocument() { + return "{\"Version\":\"2012-10-17\",\"Statement\":[]}"; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamInlinePolicyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamInlinePolicyIntegrationTest.java new file mode 100644 index 0000000000..07b80f83e8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamInlinePolicyIntegrationTest.java @@ -0,0 +1,798 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Regression for GH-1531: two CloudFormation stacks in the same account each declare an + * {@code AWS::IAM::Policy} with the same auto-generated {@code PolicyName} (as CDK emits when two + * stacks reuse a construct sub-tree — e.g. {@code IamTaskRoleDefaultPolicy}) but attach it to + * different roles. {@code AWS::IAM::Policy} is an inline policy, scoped to its owning + * principal, so both stacks must deploy. Previously Floci modelled it as a standalone (account-global) + * managed policy, so the second stack failed with "Policy ... already exists" and rolled back. + * + *

Also asserts that {@code AWS::IAM::ManagedPolicy} remains a standalone managed policy with an ARN. + * IAM is the Query API (form-encoded request, XML response); no containers involved, so Docker-free. + */ +@QuarkusTest +class CloudFormationIamInlinePolicyIntegrationTest { + + private static final String CFN_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request"; + private static final String IAM_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/iam/aws4_request"; + + private static String stackWithInlinePolicy(String roleName, String policyName) { + return """ + { + "Resources": { + "Role": { + "Type": "AWS::IAM::Role", + "Properties": { + "RoleName": "%s", + "AssumeRolePolicyDocument": { + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Allow", + "Principal": {"Service": "ecs-tasks.amazonaws.com"}, + "Action": "sts:AssumeRole" + }] + } + } + }, + "DefaultPolicy": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyName": "%s", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Allow", + "Action": "s3:GetObject", + "Resource": "*" + }] + }, + "Roles": [{"Ref": "Role"}] + } + } + } + } + """.formatted(roleName, policyName); + } + + private static String inlinePolicyForExistingRole(String policyName, String roleName, String action) { + return """ + { + "Resources": { + "DefaultPolicy": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyName": "%s", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "%s", "Resource": "*"}] + }, + "Roles": ["%s"] + } + } + } + } + """.formatted(policyName, action, roleName); + } + + private static String inlinePolicyForExistingRoleAndUser( + String policyName, String roleName, String userName, String action) { + return """ + { + "Resources": { + "DefaultPolicy": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyName": "%s", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "%s", "Resource": "*"}] + }, + "Roles": ["%s"], + "Users": ["%s"] + } + } + } + } + """.formatted(policyName, action, roleName, userName); + } + + private static void createStack(String stackName, String template) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + } + + private static void updateStack(String stackName, String template) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "UpdateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + } + + private static void assertStackComplete(String stackName) { + assertStackStatus(stackName, "CREATE_COMPLETE"); + } + + private static void assertStackStatus(String stackName, String status) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("" + status + "")); + } + + @Test + void twoStacksReusingSameInlinePolicyNameBothDeploy() { + String suffix = Long.toString(System.nanoTime(), 36); + // Same auto-generated policy name in both stacks — the exact GH-1531 collision. + String sharedPolicyName = "IamTaskRoleDefaultPolicy" + suffix; + String roleA = "role-a-" + suffix; + String roleB = "role-b-" + suffix; + + createStack("cfn-iam-inline-a-" + suffix, stackWithInlinePolicy(roleA, sharedPolicyName)); + assertStackComplete("cfn-iam-inline-a-" + suffix); + + // Before the fix this second stack rolled back ("Policy ... already exists"). + createStack("cfn-iam-inline-b-" + suffix, stackWithInlinePolicy(roleB, sharedPolicyName)); + assertStackComplete("cfn-iam-inline-b-" + suffix); + + // Each role really carries the inline policy, scoped to that role. + for (String roleName : new String[] {roleA, roleB}) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetRolePolicy") + .formParam("RoleName", roleName) + .formParam("PolicyName", sharedPolicyName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString(sharedPolicyName)) + .body(containsString("s3:GetObject")); + } + } + + @Test + void updateRemovingRoleDetachesInlinePolicy() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-iam-inline-update-" + suffix; + String policyName = "inline-update-policy-" + suffix; + String oldRole = "inline-update-old-" + suffix; + String newRole = "inline-update-new-" + suffix; + + for (String roleName : new String[] {oldRole, newRole}) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "CreateRole") + .formParam("RoleName", roleName) + .formParam("AssumeRolePolicyDocument", + "{\"Version\":\"2012-10-17\",\"Statement\":[]}") + .when().post("/").then().statusCode(200); + } + + createStack(stackName, inlinePolicyForExistingRole(policyName, oldRole, "s3:GetObject")); + assertStackComplete(stackName); + + updateStack(stackName, inlinePolicyForExistingRole(policyName, newRole, "s3:PutObject")); + assertStackStatus(stackName, "UPDATE_COMPLETE"); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetRolePolicy") + .formParam("RoleName", oldRole) + .formParam("PolicyName", policyName) + .when().post("/").then().statusCode(404).body(containsString("NoSuchEntity")); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetRolePolicy") + .formParam("RoleName", newRole) + .formParam("PolicyName", policyName) + .when().post("/").then().statusCode(200).body(containsString("s3:PutObject")); + } + + @Test + void failedUpdatePreservesPriorInlinePolicyForStackDeletion() throws InterruptedException { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-iam-inline-failed-update-" + suffix; + String policyName = "inline-failed-update-policy-" + suffix; + String oldRole = "inline-failed-update-old-" + suffix; + String newRole = "inline-failed-update-new-" + suffix; + String missingUser = "inline-failed-update-missing-" + suffix; + + for (String roleName : new String[] {oldRole, newRole}) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "CreateRole") + .formParam("RoleName", roleName) + .formParam("AssumeRolePolicyDocument", + "{\"Version\":\"2012-10-17\",\"Statement\":[]}") + .when().post("/").then().statusCode(200); + } + + createStack(stackName, inlinePolicyForExistingRole(policyName, oldRole, "s3:GetObject")); + assertStackComplete(stackName); + + updateStack(stackName, inlinePolicyForExistingRoleAndUser( + policyName, newRole, missingUser, "s3:PutObject")); + assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE"); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetRolePolicy") + .formParam("RoleName", oldRole) + .formParam("PolicyName", policyName) + .when().post("/").then().statusCode(200).body(containsString("s3:GetObject")); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetRolePolicy") + .formParam("RoleName", newRole) + .formParam("PolicyName", policyName) + .when().post("/").then().statusCode(404).body(containsString("NoSuchEntity")); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DeleteStack") + .formParam("StackName", stackName) + .when().post("/").then().statusCode(200); + + awaitInlinePolicyGone(oldRole, policyName); + } + + @Test + void managedPolicyRemainsStandaloneWithArn() { + String suffix = Long.toString(System.nanoTime(), 36); + String managedName = "managed-policy-" + suffix; + String stackName = "cfn-iam-managed-" + suffix; + + String template = """ + { + "Resources": { + "ManagedPolicy": { + "Type": "AWS::IAM::ManagedPolicy", + "Properties": { + "ManagedPolicyName": "%s", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Allow", + "Action": "s3:ListBucket", + "Resource": "*" + }] + } + } + } + }, + "Outputs": { + "PolicyArn": {"Value": {"Ref": "ManagedPolicy"}} + } + } + """.formatted(managedName); + + createStack(stackName, template); + + // Managed policy has an ARN (unlike inline), surfaced through Ref. + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("CREATE_COMPLETE")) + .body(containsString(":policy/" + managedName)); + } + + @Test + void deletingManagedPolicyDetachesItFromSurvivingRole() throws InterruptedException { + String suffix = Long.toString(System.nanoTime(), 36); + String roleName = "managed-policy-role-" + suffix; + String policyName = "attached-managed-policy-" + suffix; + String policyArn = "arn:aws:iam::000000000000:policy/" + policyName; + String stackName = "cfn-iam-managed-del-" + suffix; + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "CreateRole") + .formParam("RoleName", roleName) + .formParam("AssumeRolePolicyDocument", + "{\"Version\":\"2012-10-17\",\"Statement\":[]}") + .when().post("/").then().statusCode(200); + + String template = """ + { + "Resources": { + "ManagedPolicy": { + "Type": "AWS::IAM::ManagedPolicy", + "Properties": { + "ManagedPolicyName": "%s", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}] + }, + "Roles": ["%s"] + } + } + } + } + """.formatted(policyName, roleName); + + createStack(stackName, template); + assertStackComplete(stackName); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DeleteStack") + .formParam("StackName", stackName) + .when().post("/").then().statusCode(200); + + awaitManagedPolicyGone(policyArn); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetRole") + .formParam("RoleName", roleName) + .when().post("/").then().statusCode(200).body(containsString(roleName)); + + String attachments = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "ListAttachedRolePolicies") + .formParam("RoleName", roleName) + .when().post("/").then().statusCode(200).extract().asString(); + assertFalse(attachments.contains(policyName), "deleted policy must be detached: " + attachments); + } + + @Test + void roleWithMissingManagedPolicyFailsAndRollsBack() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-iam-role-missing-policy-" + suffix; + String roleName = "missing-policy-role-" + suffix; + String validArn = "arn:aws:iam::aws:policy/ReadOnlyAccess"; + String missingArn = "arn:aws:iam::aws:policy/DefinitelyMissing-" + suffix; + String template = """ + { + "Resources": { + "Role": { + "Type": "AWS::IAM::Role", + "Properties": { + "RoleName": "missing-policy-role-%s", + "ManagedPolicyArns": ["%s", "%s"] + } + } + } + } + """.formatted(suffix, validArn, missingArn); + + createStack(stackName, template); + + assertFailedResource(stackName, "Role", missingArn, "does not exist"); + + // The first attachment succeeded before the second failed. Rollback must detach it and + // delete the role created by this failed resource instead of leaking a partial IAM entity. + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetRole") + .formParam("RoleName", roleName) + .when().post("/").then().statusCode(404).body(containsString("NoSuchEntity")); + } + + @Test + void freshStackDoesNotAdoptExistingRole() { + String suffix = Long.toString(System.nanoTime(), 36); + String roleName = "externally-owned-role-" + suffix; + String stackName = "cfn-iam-role-collision-" + suffix; + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "CreateRole") + .formParam("RoleName", roleName) + .formParam("AssumeRolePolicyDocument", + "{\"Version\":\"2012-10-17\",\"Statement\":[]}") + .when().post("/").then().statusCode(200); + + String template = """ + { + "Resources": { + "Role": { + "Type": "AWS::IAM::Role", + "Properties": {"RoleName": "%s"} + } + } + } + """.formatted(roleName); + + createStack(stackName, template); + + assertFailedResource(stackName, "Role", roleName, "already exists"); + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetRole") + .formParam("RoleName", roleName) + .when().post("/").then().statusCode(200).body(containsString(roleName)); + } + + @Test + void managedPolicyWithMissingRoleFailsAndRollsBack() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-iam-policy-missing-role-" + suffix; + String existingRole = "existing-role-" + suffix; + String missingRole = "missing-role-" + suffix; + String policyName = "missing-role-policy-" + suffix; + String policyArn = "arn:aws:iam::000000000000:policy/" + policyName; + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "CreateRole") + .formParam("RoleName", existingRole) + .formParam("AssumeRolePolicyDocument", + "{\"Version\":\"2012-10-17\",\"Statement\":[]}") + .when().post("/").then().statusCode(200); + + String template = """ + { + "Resources": { + "ManagedPolicy": { + "Type": "AWS::IAM::ManagedPolicy", + "Properties": { + "ManagedPolicyName": "missing-role-policy-%s", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}] + }, + "Roles": ["%s", "%s"] + } + } + } + } + """.formatted(suffix, existingRole, missingRole); + + createStack(stackName, template); + + assertFailedResource(stackName, "ManagedPolicy", missingRole, "cannot be found"); + + // Rollback removes the policy it created and only detaches the role supplied by the user. + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetPolicy") + .formParam("PolicyArn", policyArn) + .when().post("/").then().statusCode(404).body(containsString("NoSuchEntity")); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetRole") + .formParam("RoleName", existingRole) + .when().post("/").then().statusCode(200).body(containsString(existingRole)); + + String attachments = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "ListAttachedRolePolicies") + .formParam("RoleName", existingRole) + .when().post("/").then().statusCode(200).extract().asString(); + assertFalse(attachments.contains(policyName), "failed policy must be detached: " + attachments); + } + + @Test + void inlinePolicyWithMissingRoleRollsBackSuccessfulAttachment() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-iam-inline-missing-role-" + suffix; + String existingRole = "inline-existing-role-" + suffix; + String missingRole = "inline-missing-role-" + suffix; + String policyName = "inline-missing-role-policy-" + suffix; + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "CreateRole") + .formParam("RoleName", existingRole) + .formParam("AssumeRolePolicyDocument", + "{\"Version\":\"2012-10-17\",\"Statement\":[]}") + .when().post("/").then().statusCode(200); + + String template = """ + { + "Resources": { + "InlinePolicy": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyName": "%s", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}] + }, + "Roles": ["%s", "%s"] + } + } + } + } + """.formatted(policyName, existingRole, missingRole); + + createStack(stackName, template); + + String stack = describeStack(stackName, "DescribeStacks"); + assertTrue(stack.contains("ROLLBACK_COMPLETE"), + "stack should roll back after the inline attachment failure: " + stack); + + String resources = describeStack(stackName, "DescribeStackResources"); + assertTrue( + resources.contains("InlinePolicy") + && resources.contains("DELETE_COMPLETE"), + "partially attached inline policy should be rolled back: " + resources); + + String events = describeStack(stackName, "DescribeStackEvents"); + assertTrue(events.contains(missingRole) && events.contains("cannot be found"), + "failure reason should identify the missing role: " + events); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetRolePolicy") + .formParam("RoleName", existingRole) + .formParam("PolicyName", policyName) + .when().post("/").then().statusCode(404).body(containsString("NoSuchEntity")); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetRole") + .formParam("RoleName", existingRole) + .when().post("/").then().statusCode(200).body(containsString(existingRole)); + } + + @Test + void laterResourceFailureRollsBackCompletedManagedPolicyAttachments() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-iam-later-failure-" + suffix; + String existingRole = "rollback-target-role-" + suffix; + String policyName = "rollback-target-policy-" + suffix; + String policyArn = "arn:aws:iam::000000000000:policy/" + policyName; + String missingArn = "arn:aws:iam::aws:policy/RollbackMissing-" + suffix; + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "CreateRole") + .formParam("RoleName", existingRole) + .formParam("AssumeRolePolicyDocument", + "{\"Version\":\"2012-10-17\",\"Statement\":[]}") + .when().post("/").then().statusCode(200); + + String template = """ + { + "Resources": { + "ManagedPolicy": { + "Type": "AWS::IAM::ManagedPolicy", + "Properties": { + "ManagedPolicyName": "%s", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}] + }, + "Roles": ["%s"] + } + }, + "FailingRole": { + "Type": "AWS::IAM::Role", + "DependsOn": "ManagedPolicy", + "Properties": { + "RoleName": "later-failing-role-%s", + "ManagedPolicyArns": ["%s"] + } + } + } + } + """.formatted(policyName, existingRole, suffix, missingArn); + + createStack(stackName, template); + + assertFailedResource(stackName, "FailingRole", missingArn, "does not exist"); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetPolicy") + .formParam("PolicyArn", policyArn) + .when().post("/").then().statusCode(404).body(containsString("NoSuchEntity")); + + String attachments = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "ListAttachedRolePolicies") + .formParam("RoleName", existingRole) + .when().post("/").then().statusCode(200).extract().asString(); + assertFalse(attachments.contains(policyName), "rolled-back policy must be detached: " + attachments); + } + + @Test + void deletingStackDetachesInlinePolicyFromSurvivingRole() throws InterruptedException { + String suffix = Long.toString(System.nanoTime(), 36); + String roleName = "ext-role-" + suffix; + String policyName = "InlinePolicy" + suffix; + String stackName = "cfn-iam-inline-del-" + suffix; + + // Role owned OUTSIDE the stack, so it survives DeleteStack — this isolates the inline-policy + // detach (deleteInlinePolicySafe/detachInline) from a cascade role delete. + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "CreateRole") + .formParam("RoleName", roleName) + .formParam("AssumeRolePolicyDocument", + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":{\"Service\":\"ecs-tasks.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}") + .when().post("/").then().statusCode(200); + + String template = """ + { + "Resources": { + "DefaultPolicy": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyName": "%s", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}] + }, + "Roles": ["%s"] + } + } + } + } + """.formatted(policyName, roleName); + + createStack(stackName, template); + assertStackComplete(stackName); + + // The inline policy is embedded in the pre-existing role. + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetRolePolicy") + .formParam("RoleName", roleName) + .formParam("PolicyName", policyName) + .when().post("/").then().statusCode(200).body(containsString("s3:GetObject")); + + // Deleting the stack must detach the inline policy from the surviving role (async delete). + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DeleteStack") + .formParam("StackName", stackName) + .when().post("/").then().statusCode(200); + + awaitInlinePolicyGone(roleName, policyName); + + // The role still exists ... + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetRole") + .formParam("RoleName", roleName) + .when().post("/").then().statusCode(200).body(containsString(roleName)); + + // ... but its inline policy is gone (NoSuchEntity, HTTP 404). + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetRolePolicy") + .formParam("RoleName", roleName) + .formParam("PolicyName", policyName) + .when().post("/").then().statusCode(404).body(containsString("NoSuchEntity")); + } + + /** DeleteStack runs asynchronously; poll until the inline policy has been detached (404) or time out. */ + private static void awaitInlinePolicyGone(String roleName, String policyName) throws InterruptedException { + for (int i = 0; i < 100; i++) { + int sc = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetRolePolicy") + .formParam("RoleName", roleName) + .formParam("PolicyName", policyName) + .when().post("/").then().extract().statusCode(); + if (sc == 404) { + return; + } + Thread.sleep(50); + } + throw new AssertionError("Timed out waiting for inline policy " + policyName + + " to be detached from role " + roleName); + } + + private static void awaitManagedPolicyGone(String policyArn) throws InterruptedException { + for (int i = 0; i < 100; i++) { + int status = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetPolicy") + .formParam("PolicyArn", policyArn) + .when().post("/").then().extract().statusCode(); + if (status == 404) { + return; + } + Thread.sleep(50); + } + throw new AssertionError("Timed out waiting for managed policy " + policyArn + " to be deleted"); + } + + private static void assertFailedResource(String stackName, String logicalId, + String expectedSubject, String expectedReason) { + String stack = describeStack(stackName, "DescribeStacks"); + assertTrue( + stack.contains("ROLLBACK_COMPLETE"), + "stack should roll back after the attachment failure: " + stack); + assertFalse( + stack.contains("CREATE_COMPLETE"), + "stack must not report false success: " + stack); + + String resources = describeStack(stackName, "DescribeStackResources"); + assertTrue( + resources.contains("" + logicalId + "") + && resources.contains("CREATE_FAILED"), + "failed resource status should be visible: " + resources); + + String events = describeStack(stackName, "DescribeStackEvents"); + assertTrue( + events.contains(expectedSubject) && events.contains(expectedReason), + "failure reason should identify the missing attachment target: " + events); + } + + private static String describeStack(String stackName, String action) { + return given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", action) + .formParam("StackName", stackName) + .when().post("/").then().statusCode(200).extract().asString(); + } +}