From e648b6b9347fce3d1c0abfb6f5e87232ee5865fe Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sun, 20 Sep 2026 12:04:15 -0500 Subject: [PATCH] refactor(cloudformation): move IAM ManagedPolicy into IamManagedPolicyCfnProvisioner (#3972) Move AWS::IAM::ManagedPolicy, the last IAM type in the monolith, into a new IamManagedPolicyCfnProvisioner over IamService. Ref and Fn::GetAtt PolicyArn return the policy ARN. On UpdateStack with an unchanged name PolicyDocument is applied as a new default version in place, pruning the oldest versions under IAM's five-version cap and detaching roles no longer listed, and a mid-update failure restores the version and attachment state this pass changed. Delete detaches the roles before DeletePolicy, tolerating an already-gone attachment. Stacked on #3971 (inline Policy); merge that first. The move resolves PolicyArn and DefaultVersionId as Fn::GetAtt keys and records the five other read-only attributes (AttachmentCount, CreateDate, UpdateDate, IsAttachable, PermissionsBoundaryUsageCount) as gaps, since leaving LEGACY_SWITCH subjects the type to CfnSchemaCoverageTest. The small managed-policy delete helpers are duplicated with IamPolicyCfnProvisioner's legacy path for now, to be collapsed into a shared helper once both land. --- .../CloudFormationResourceProvisioner.java | 295 +----------------- .../IamManagedPolicyCfnProvisioner.java | 289 +++++++++++++++++ .../cloudformation/CfnProvisionerFixture.java | 2 + ...FormationIamAttachmentProvisionerTest.java | 4 +- .../IamManagedPolicyCfnProvisionerTest.java | 136 ++++++++ .../cloudformation/getatt-attribute-gaps.tsv | 5 + .../supported-resource-types.tsv | 2 +- 7 files changed, 437 insertions(+), 296 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamManagedPolicyCfnProvisioner.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamManagedPolicyCfnProvisionerTest.java 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 18ecf9586a..cb49bad44a 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 @@ -85,8 +85,7 @@ public class CloudFormationResourceProvisioner { */ static final Set DELETE_NEEDS_STACK_RESOURCE = Set.of( "AWS::ApiGatewayV2::Authorizer", - "AWS::CloudFormation::CustomResource", - "AWS::IAM::ManagedPolicy"); + "AWS::CloudFormation::CustomResource"); /** * Every resource type the switch in {@link #provision} still serves. Load-bearing: the @@ -103,7 +102,6 @@ public class CloudFormationResourceProvisioner { "AWS::ApiGatewayV2::Route", "AWS::ApiGatewayV2::Stage", "AWS::CloudFormation::CustomResource", - "AWS::IAM::ManagedPolicy", "AWS::Lambda::Function", "AWS::Lambda::LayerVersion"); @@ -209,8 +207,6 @@ public class CloudFormationResourceProvisioner { case "AWS::Lambda::Function" -> provisionLambda(resource, properties, engine, region, accountId, stackName); case "AWS::Lambda::LayerVersion" -> provisionLambdaLayerVersion(resource, properties, engine, region, stackName); - case "AWS::IAM::ManagedPolicy" -> - provisionIamManagedPolicy(resource, properties, engine, accountId, stackName); case "AWS::ApiGatewayV2::Api" -> provisionApiGatewayV2Api(resource, properties, engine, region, accountId, stackName); case "AWS::ApiGatewayV2::Authorizer" -> provisionApiGatewayV2Authorizer(resource, properties, engine, region); case "AWS::ApiGatewayV2::Route" -> provisionApiGatewayV2Route(resource, properties, engine, region); @@ -376,12 +372,6 @@ public class CloudFormationResourceProvisioner { } 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; - } throw new IllegalStateException("DELETE_NEEDS_STACK_RESOURCE lists " + resourceType + " but no branch here deletes it — deleting it by physical id alone would " + "silently no-op and leave the resource live."); @@ -403,7 +393,6 @@ public class CloudFormationResourceProvisioner { } switch (resourceType) { case "AWS::Lambda::Function" -> deleteLambdaFunctionSafe(physicalId, region); - case "AWS::IAM::ManagedPolicy" -> deletePolicySafe(physicalId); // No bus context on the type/physicalId path (e.g. CREATE-rollback); targets the default bus. case "AWS::ApiGatewayV2::Api" -> apiGatewayV2Service.deleteApi(region, physicalId); case "AWS::Lambda::LayerVersion" -> deleteLambdaLayerVersion(physicalId, region); @@ -465,15 +454,6 @@ public class CloudFormationResourceProvisioner { // ── Auto Scaling ──────────────────────────────────────────────────────────── - private List resolveStringList(JsonNode props, String field, CloudFormationTemplateEngine engine) { - if (props == null || !props.has(field)) { - return new ArrayList<>(); - } - // engine.resolveStringList accepts both a literal array and a list-valued intrinsic - // (Fn::Split / Fn::GetAZs / Fn::Cidr) and drops blank entries (issue #2937). - return new ArrayList<>(engine.resolveStringList(props.get(field))); - } - // ── EKS ───────────────────────────────────────────────────────────────────── // ── Lambda ──────────────────────────────────────────────────────────────── @@ -1114,233 +1094,6 @@ public class CloudFormationResourceProvisioner { } } - // ── IAM Policy ──────────────────────────────────────────────────────────── - - private static String resolvePolicyDocument(JsonNode props, CloudFormationTemplateEngine engine) { - JsonNode documentNode = props != null ? props.get("PolicyDocument") : null; - String resolved = documentNode != null ? engine.resolveJsonAttributeStrict(documentNode) : null; - return resolved != null ? resolved : "{\"Version\":\"2012-10-17\",\"Statement\":[]}"; - } - - /** - * 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 = resolvePolicyDocument(props, engine); - List roleNames = resolveStringList(props, "Roles", engine); - String existingArn = r.getPhysicalId(); - - io.github.hectorvent.floci.services.iam.model.IamPolicy policy; - boolean createdPolicy = false; - String previousDefaultVersionId = null; - io.github.hectorvent.floci.services.iam.model.PolicyVersion createdVersionForRollback = null; - List prunedVersionsForRollback = - new ArrayList<>(); - List detachedObsoleteRoles = new ArrayList<>(); - try { - policy = iamService.createPolicy(policyName, "/", null, document, Map.of()); - createdPolicy = true; - } catch (AwsException e) { - // Stack UPDATE with an unchanged policy name: the policy this stack provisioned on a - // previous pass already exists. PolicyDocument is a mutable property, so CloudFormation - // updates the policy in place (a new default version) rather than replacing it. Only - // adopt when the existing physical id is this exact policy — a collision with a policy - // some other stack owns must still fail like AWS does. - boolean stackAlreadyOwnsPolicy = existingArn != null - && existingArn.endsWith(":policy/" + policyName); - if (!stackAlreadyOwnsPolicy || !"EntityAlreadyExists".equals(e.getErrorCode())) { - throw e; - } - policy = iamService.getPolicy(existingArn); - String policyId = r.getAttributes().get("PolicyId"); - // A missing PolicyId means this resource predates PolicyId tracking (an upgrade from - // an older floci pass) — its identity can't be verified, and the ARN alone is not - // proof of ownership: a policy deleted and recreated under the same name reuses the - // same ARN with a different PolicyId. Fail closed rather than silently adopting - // (and mutating) a policy this stack no longer owns. - if (policyId == null || !policyId.equals(policy.getPolicyId())) { - throw e; - } - previousDefaultVersionId = policy.getDefaultVersionId(); - // IAM caps a managed policy at 5 versions; prune the oldest non-default ones the way - // CloudFormation does, so repeated stack updates never die on LimitExceeded. - var versions = iamService.listPolicyVersions(existingArn).stream() - .filter(v -> !v.isDefaultVersion()) - .sorted(java.util.Comparator.comparingInt( - v -> Integer.parseInt(v.getVersionId().substring(1)))) - .toList(); - for (int i = 0; i <= versions.size() - 4; i++) { - var pruned = versions.get(i); - // Captured before deletion so a later failure in this same update can recreate - // the content — the version id itself is gone for good (AWS never reissues one), - // but the document must survive a rollback that reports COMPLETE. - prunedVersionsForRollback.add(pruned); - iamService.deletePolicyVersion(existingArn, pruned.getVersionId()); - } - createdVersionForRollback = iamService.createPolicyVersion(existingArn, document, true); - // Roles this stack attached on the previous pass but no longer listed in the - // template are detached, matching CloudFormation's update semantics. - String previousTargets = r.getAttributes().get("ManagedPolicyRoleTargets"); - if (previousTargets != null && !previousTargets.isBlank()) { - for (String previousRole : previousTargets.split("\n")) { - if (!roleNames.contains(previousRole)) { - try { - iamService.detachRolePolicy(previousRole, existingArn); - detachedObsoleteRoles.add(previousRole); - } catch (AwsException detachFailure) { - // Update is idempotent like the delete path: the attachment can - // already be gone on a retry, but other failures must still surface — - // and must still restore the version/attachments this pass already - // changed, the same as a failure in the attach loop below (this loop - // runs first, so that loop's own catch never sees this failure). - if (!"NoSuchEntity".equals(detachFailure.getErrorCode())) { - restoreManagedPolicyOnUpdateFailure(detachFailure, r, existingArn, - false, Set.of(), detachedObsoleteRoles, - previousDefaultVersionId, createdVersionForRollback, - prunedVersionsForRollback); - throw detachFailure; - } - } - } - } - } - } - r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true"); - r.getAttributes().put("PolicyId", policy.getPolicyId()); - r.setPhysicalId(policy.getArn()); - // PolicyArn is the attribute CloudFormation documents for this type, and what a template - // written against AWS asks for. Without it Fn::GetAtt does not resolve and the unresolved - // literal reaches whatever consumed it — a role's ManagedPolicyArns, typically, which then - // fails with "policy does not exist" and rolls the stack back. "Arn" stays for callers - // already using it. - r.getAttributes().put("Arn", policy.getArn()); - r.getAttributes().put("PolicyArn", policy.getArn()); - r.getAttributes().put("ManagedPolicyRoleTargets", String.join("\n", roleNames)); - - String policyArn = policy.getArn(); - // On adopt, attachments from the previous pass are not this attempt's to undo. - Set previouslyAttached = createdPolicy - ? Set.of() - : iamService.listEntitiesForPolicy(policyArn).roles().stream() - .map(role -> role.getRoleName()) - .collect(java.util.stream.Collectors.toSet()); - LinkedHashSet attachedRoleNames = new LinkedHashSet<>(); - try { - for (String roleName : roleNames) { - iamService.attachRolePolicy(roleName, policyArn); - if (!previouslyAttached.contains(roleName)) { - attachedRoleNames.add(roleName); - } - } - } catch (RuntimeException failure) { - restoreManagedPolicyOnUpdateFailure(failure, r, policyArn, createdPolicy, attachedRoleNames, - detachedObsoleteRoles, previousDefaultVersionId, createdVersionForRollback, - prunedVersionsForRollback); - throw failure; - } - } - - /** - * Undoes whatever this update attempt already did to a managed policy before it failed — - * shared by the attach loop above and the obsolete-role detach loop earlier in - * {@link #provisionIamManagedPolicy}, since a detach failure (e.g. a role that became - * unmodifiable between passes) can escape before the attach loop even runs, and must still - * restore the version/attachment state already changed in this pass. - */ - private void restoreManagedPolicyOnUpdateFailure( - RuntimeException failure, - StackResource r, - String policyArn, - boolean createdPolicy, - Set attachedRoleNames, - List detachedObsoleteRoles, - String previousDefaultVersionId, - io.github.hectorvent.floci.services.iam.model.PolicyVersion createdVersionForRollback, - List prunedVersionsForRollback) { - List rollbackRoles = new ArrayList<>(attachedRoleNames); - Collections.reverse(rollbackRoles); - boolean cleanupSucceeded = true; - for (String roleName : rollbackRoles) { - String cleanupDescription = "detach policy " + policyArn + " from role " + roleName; - if (!CfnRollback.attemptIamCleanup(failure, cleanupDescription, - () -> iamService.detachRolePolicy(roleName, policyArn))) { - cleanupSucceeded = false; - } - } - if (createdPolicy - && !CfnRollback.attemptIamCleanup(failure, "delete policy " + policyArn, - () -> iamService.deletePolicy(policyArn))) { - cleanupSucceeded = false; - } - // An adopted update that fails here already replaced the default version and/or - // detached now-obsolete roles before this attach loop ran; undo both so the failed - // update doesn't leave the policy half-migrated under UPDATE_ROLLBACK_COMPLETE. - List reattachRoles = new ArrayList<>(detachedObsoleteRoles); - Collections.reverse(reattachRoles); - for (String roleName : reattachRoles) { - String cleanupDescription = "reattach policy " + policyArn + " to role " + roleName; - if (!CfnRollback.attemptIamCleanup(failure, cleanupDescription, - () -> iamService.attachRolePolicy(roleName, policyArn))) { - cleanupSucceeded = false; - } - } - if (previousDefaultVersionId != null) { - String restoredVersionId = previousDefaultVersionId; - String restoreDescription = - "restore default policy version " + restoredVersionId + " on " + policyArn; - if (!CfnRollback.attemptIamCleanup(failure, restoreDescription, - () -> iamService.setDefaultPolicyVersion(policyArn, restoredVersionId))) { - cleanupSucceeded = false; - } - if (createdVersionForRollback != null) { - String strayVersionId = createdVersionForRollback.getVersionId(); - String pruneDescription = "delete stray policy version " + strayVersionId + " on " + policyArn; - if (!CfnRollback.attemptIamCleanup(failure, pruneDescription, - () -> iamService.deletePolicyVersion(policyArn, strayVersionId))) { - cleanupSucceeded = false; - } - } - // Versions pruned to stay under IAM's 5-version cap before publishing this attempt's - // new default are gone for good under their original version id, but the document - // itself must not be — restoring only the default and deleting the stray version - // (above) frees exactly the slot(s) needed to recreate their content now, so a - // "successful" rollback doesn't quietly destroy policy history that predates this - // update. - for (var prunedVersion : prunedVersionsForRollback) { - String document = prunedVersion.getDocument(); - String restoreContentDescription = - "restore pruned policy version content on " + policyArn; - if (!CfnRollback.attemptIamCleanup(failure, restoreContentDescription, - () -> iamService.createPolicyVersion(policyArn, document, false))) { - cleanupSucceeded = false; - } - } - } - if (cleanupSucceeded && createdPolicy) { - r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR); - } - if (!cleanupSucceeded) { - // A compensating call above failed (added as a suppressed exception on `failure`) — - // the policy's version/attachments were only partially restored. Surface that so the - // stack reports UPDATE_ROLLBACK_FAILED instead of the caller assuming this resource is - // fully restored just because UPDATE_ROLLBACK_FAILURE_ATTR was never set. - String reason = failure.getMessage() != null - ? failure.getMessage() - : failure.getClass().getSimpleName(); - r.getAttributes().put(UPDATE_ROLLBACK_FAILURE_ATTR, reason); - } - } - - // ── IAM Instance Profile ────────────────────────────────────────────────── - // ── Pipes ────────────────────────────────────────────────────────────────── /** @@ -2463,17 +2216,6 @@ public class CloudFormationResourceProvisioner { return (value != null && !value.isBlank()) ? value : defaultValue; } - private void deletePolicySafe(String policyArn) { - try { - iamService.deletePolicy(policyArn); - } catch (AwsException e) { - if (!"NoSuchEntity".equals(e.getErrorCode())) { - throw e; - } - LOG.debugv("IAM policy already gone, treating as deleted: {0}", policyArn); - } - } - private void deleteLambdaFunctionSafe(String functionName, String region) { try { lambdaService.deleteFunction(region, functionName); @@ -2485,41 +2227,6 @@ public class CloudFormationResourceProvisioner { } } - 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 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(); - } - /** * Generate an AWS-like physical name: {stackName}-{logicalId}-{randomSuffix}. * Mirrors the naming pattern AWS CloudFormation uses when no explicit name is provided. diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamManagedPolicyCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamManagedPolicyCfnProvisioner.java new file mode 100644 index 0000000000..0e68358261 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamManagedPolicyCfnProvisioner.java @@ -0,0 +1,289 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +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.PolicyVersion; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * CloudFormation provisioning for {@code AWS::IAM::ManagedPolicy}, a standalone customer-managed + * policy with an ARN that must be detached from its roles before deletion. {@code Ref} and + * {@code Fn::GetAtt PolicyArn} return the policy ARN. A managed policy name is account-global, so + * the physical name is honoured verbatim from {@code ManagedPolicyName} when set. + * + *

On {@code UpdateStack} with an unchanged name the policy this stack provisioned already + * exists, so {@code PolicyDocument} is applied as a new default version in place (pruning the + * oldest versions to stay under IAM's five-version cap) and roles no longer listed are detached, + * matching CloudFormation. A failure mid-update restores the version and attachment state this pass + * changed rather than leaving the policy half-migrated. + */ +@ApplicationScoped +public class IamManagedPolicyCfnProvisioner implements CfnResourceProvisioner { + + private static final String TYPE = "AWS::IAM::ManagedPolicy"; + + private final IamService iamService; + + @Inject + public IamManagedPolicyCfnProvisioner(IamService iamService) { + this.iamService = iamService; + } + + @Override + public Set resourceTypes() { + return Set.of(TYPE); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + String policyName = ctx.resolveOptional(props, "ManagedPolicyName"); + if (policyName == null || policyName.isBlank()) { + policyName = ctx.generatePhysicalName(r.getLogicalId(), 128, false); + } + String document = ctx.resolvePolicyDocument(props); + List roleNames = ctx.resolveStringList(props, "Roles"); + String existingArn = r.getPhysicalId(); + + IamPolicy policy; + boolean createdPolicy = false; + String previousDefaultVersionId = null; + PolicyVersion createdVersionForRollback = null; + List prunedVersionsForRollback = new ArrayList<>(); + List detachedObsoleteRoles = new ArrayList<>(); + try { + policy = iamService.createPolicy(policyName, "/", null, document, Map.of()); + createdPolicy = true; + } catch (AwsException e) { + // Stack UPDATE with an unchanged policy name: the policy this stack provisioned on a + // previous pass already exists. PolicyDocument is a mutable property, so CloudFormation + // updates the policy in place (a new default version) rather than replacing it. Only + // adopt when the existing physical id is this exact policy: a collision with a policy + // some other stack owns must still fail like AWS does. + boolean stackAlreadyOwnsPolicy = existingArn != null + && existingArn.endsWith(":policy/" + policyName); + if (!stackAlreadyOwnsPolicy || !"EntityAlreadyExists".equals(e.getErrorCode())) { + throw e; + } + policy = iamService.getPolicy(existingArn); + String policyId = r.getAttributes().get("PolicyId"); + // A missing PolicyId means this resource predates PolicyId tracking (an upgrade from an + // older floci pass): its identity cannot be verified, and the ARN alone is not proof of + // ownership, since a policy deleted and recreated under the same name reuses the same + // ARN with a different PolicyId. Fail closed rather than adopting a policy this stack no + // longer owns. + if (policyId == null || !policyId.equals(policy.getPolicyId())) { + throw e; + } + previousDefaultVersionId = policy.getDefaultVersionId(); + // IAM caps a managed policy at 5 versions; prune the oldest non-default ones the way + // CloudFormation does, so repeated stack updates never die on LimitExceeded. + List versions = iamService.listPolicyVersions(existingArn).stream() + .filter(v -> !v.isDefaultVersion()) + .sorted(Comparator.comparingInt(v -> Integer.parseInt(v.getVersionId().substring(1)))) + .toList(); + for (int i = 0; i <= versions.size() - 4; i++) { + PolicyVersion pruned = versions.get(i); + // Captured before deletion so a later failure in this same update can recreate the + // content: the version id itself is gone for good (AWS never reissues one), but the + // document must survive a rollback that reports COMPLETE. + prunedVersionsForRollback.add(pruned); + iamService.deletePolicyVersion(existingArn, pruned.getVersionId()); + } + createdVersionForRollback = iamService.createPolicyVersion(existingArn, document, true); + // Roles this stack attached on the previous pass but no longer listed in the template + // are detached, matching CloudFormation's update semantics. + String previousTargets = r.getAttributes().get("ManagedPolicyRoleTargets"); + if (previousTargets != null && !previousTargets.isBlank()) { + for (String previousRole : previousTargets.split("\n")) { + if (!roleNames.contains(previousRole)) { + try { + iamService.detachRolePolicy(previousRole, existingArn); + detachedObsoleteRoles.add(previousRole); + } catch (AwsException detachFailure) { + // Update is idempotent like the delete path: the attachment can already + // be gone on a retry, but other failures must surface and still restore + // the version/attachments this pass changed, the same as a failure in + // the attach loop below (this loop runs first, so that loop's own catch + // never sees this failure). + if (!"NoSuchEntity".equals(detachFailure.getErrorCode())) { + restoreOnUpdateFailure(detachFailure, r, existingArn, + false, Set.of(), detachedObsoleteRoles, + previousDefaultVersionId, createdVersionForRollback, + prunedVersionsForRollback); + throw detachFailure; + } + } + } + } + } + } + r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true"); + r.getAttributes().put("PolicyId", policy.getPolicyId()); + r.setPhysicalId(policy.getArn()); + // PolicyArn is the attribute CloudFormation documents for this type, and what a template + // written against AWS asks for. Without it Fn::GetAtt does not resolve and the unresolved + // literal reaches whatever consumed it, a role's ManagedPolicyArns typically, which then + // fails with "policy does not exist" and rolls the stack back. "Arn" stays for callers + // already using it. + r.getAttributes().put("Arn", policy.getArn()); + r.getAttributes().put("PolicyArn", policy.getArn()); + r.getAttributes().put("DefaultVersionId", policy.getDefaultVersionId()); + r.getAttributes().put("ManagedPolicyRoleTargets", String.join("\n", roleNames)); + + String policyArn = policy.getArn(); + // On adopt, attachments from the previous pass are not this attempt's to undo. + Set previouslyAttached = createdPolicy + ? Set.of() + : iamService.listEntitiesForPolicy(policyArn).roles().stream() + .map(role -> role.getRoleName()) + .collect(Collectors.toSet()); + LinkedHashSet attachedRoleNames = new LinkedHashSet<>(); + try { + for (String roleName : roleNames) { + iamService.attachRolePolicy(roleName, policyArn); + if (!previouslyAttached.contains(roleName)) { + attachedRoleNames.add(roleName); + } + } + } catch (RuntimeException failure) { + restoreOnUpdateFailure(failure, r, policyArn, createdPolicy, attachedRoleNames, + detachedObsoleteRoles, previousDefaultVersionId, createdVersionForRollback, + prunedVersionsForRollback); + throw failure; + } + } + + /** + * Undoes whatever this update attempt already did to the managed policy before it failed: + * shared by the attach loop and the obsolete-role detach loop, since a detach failure can + * escape before the attach loop even runs and must still restore the version and attachment + * state already changed in this pass. + */ + private void restoreOnUpdateFailure(RuntimeException failure, StackResource r, String policyArn, + boolean createdPolicy, Set attachedRoleNames, + List detachedObsoleteRoles, String previousDefaultVersionId, + PolicyVersion createdVersionForRollback, + List prunedVersionsForRollback) { + List rollbackRoles = new ArrayList<>(attachedRoleNames); + Collections.reverse(rollbackRoles); + boolean cleanupSucceeded = true; + for (String roleName : rollbackRoles) { + String cleanupDescription = "detach policy " + policyArn + " from role " + roleName; + if (!CfnRollback.attemptIamCleanup(failure, cleanupDescription, + () -> iamService.detachRolePolicy(roleName, policyArn))) { + cleanupSucceeded = false; + } + } + if (createdPolicy + && !CfnRollback.attemptIamCleanup(failure, "delete policy " + policyArn, + () -> iamService.deletePolicy(policyArn))) { + cleanupSucceeded = false; + } + // An adopted update that fails here already replaced the default version and/or detached + // now-obsolete roles before this attach loop ran; undo both so the failed update does not + // leave the policy half-migrated under UPDATE_ROLLBACK_COMPLETE. + List reattachRoles = new ArrayList<>(detachedObsoleteRoles); + Collections.reverse(reattachRoles); + for (String roleName : reattachRoles) { + String cleanupDescription = "reattach policy " + policyArn + " to role " + roleName; + if (!CfnRollback.attemptIamCleanup(failure, cleanupDescription, + () -> iamService.attachRolePolicy(roleName, policyArn))) { + cleanupSucceeded = false; + } + } + if (previousDefaultVersionId != null) { + String restoredVersionId = previousDefaultVersionId; + String restoreDescription = "restore default policy version " + restoredVersionId + " on " + policyArn; + if (!CfnRollback.attemptIamCleanup(failure, restoreDescription, + () -> iamService.setDefaultPolicyVersion(policyArn, restoredVersionId))) { + cleanupSucceeded = false; + } + if (createdVersionForRollback != null) { + String strayVersionId = createdVersionForRollback.getVersionId(); + String pruneDescription = "delete stray policy version " + strayVersionId + " on " + policyArn; + if (!CfnRollback.attemptIamCleanup(failure, pruneDescription, + () -> iamService.deletePolicyVersion(policyArn, strayVersionId))) { + cleanupSucceeded = false; + } + } + // Versions pruned to stay under IAM's 5-version cap before publishing this attempt's new + // default are gone for good under their original version id, but the document itself + // must not be: restoring only the default and deleting the stray version above frees + // exactly the slot(s) needed to recreate their content now, so a "successful" rollback + // does not quietly destroy policy history that predates this update. + for (PolicyVersion prunedVersion : prunedVersionsForRollback) { + String document = prunedVersion.getDocument(); + String restoreContentDescription = "restore pruned policy version content on " + policyArn; + if (!CfnRollback.attemptIamCleanup(failure, restoreContentDescription, + () -> iamService.createPolicyVersion(policyArn, document, false))) { + cleanupSucceeded = false; + } + } + } + if (cleanupSucceeded && createdPolicy) { + r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR); + } + if (!cleanupSucceeded) { + // A compensating call above failed (added as a suppressed exception on failure): the + // policy's version/attachments were only partially restored. Surface that so the stack + // reports UPDATE_ROLLBACK_FAILED instead of assuming this resource is fully restored. + String reason = failure.getMessage() != null + ? failure.getMessage() + : failure.getClass().getSimpleName(); + r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, reason); + } + } + + @Override + public void delete(StackResource resource, String region) { + String policyArn = resource.getPhysicalId(); + for (String roleName : managedPolicyRoleTargets(resource)) { + try { + iamService.detachRolePolicy(roleName, policyArn); + } catch (AwsException e) { + // Deletion is idempotent: the role or attachment can already be absent on a retry, + // but permission/service failures must keep the stack in DELETE_FAILED. + if (!"NoSuchEntity".equals(e.getErrorCode())) { + throw e; + } + } + } + try { + iamService.deletePolicy(policyArn); + } catch (AwsException e) { + if (!"NoSuchEntity".equals(e.getErrorCode())) { + throw e; + } + } + } + + private List managedPolicyRoleTargets(StackResource resource) { + String policyArn = resource.getPhysicalId(); + String targets = resource.getAttributes().get("ManagedPolicyRoleTargets"); + if (targets == null) { + // Stacks persisted before target metadata was introduced still need to be deletable. + // The policy is stack-owned, so discover only roles that currently reference this ARN. + targets = iamService.listRoles("/").stream() + .filter(role -> role.getAttachedPolicyArns().contains(policyArn)) + .map(role -> role.getRoleName()) + .collect(Collectors.joining("\n")); + } + if (targets == null || targets.isBlank()) { + return List.of(); + } + return targets.lines().filter(roleName -> !roleName.isBlank()).toList(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index b8eed188a4..21c1311390 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -63,6 +63,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ElbV2CfnP import io.github.hectorvent.floci.services.cloudformation.provisioners.FirehoseCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.IamAccessKeyCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.IamInstanceProfileCfnProvisioner; +import io.github.hectorvent.floci.services.cloudformation.provisioners.IamManagedPolicyCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.IamPolicyCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.IamRoleCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.IamUserCfnProvisioner; @@ -299,6 +300,7 @@ final class CfnProvisionerFixture { discovered.add(new IamAccessKeyCfnProvisioner(iamService)); discovered.add(new IamInstanceProfileCfnProvisioner(iamService)); discovered.add(new IamPolicyCfnProvisioner(iamService)); + discovered.add(new IamManagedPolicyCfnProvisioner(iamService)); } if (eksService != null) { discovered.add(new EksCfnProvisioner(eksService)); 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 index 92cfe537cb..9dfac042af 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java @@ -5,6 +5,7 @@ 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.CfnRollback; +import io.github.hectorvent.floci.services.cloudformation.provisioners.IamManagedPolicyCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.IamPolicyCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.IamRoleCfnProvisioner; import io.github.hectorvent.floci.services.iam.IamService; @@ -50,7 +51,8 @@ class CloudFormationIamAttachmentProvisionerTest { provisioner = CfnProvisionerFixture.builder() .iam(iamService) .objectMapper(mapper) - .provisioners(new IamRoleCfnProvisioner(iamService), new IamPolicyCfnProvisioner(iamService)) + .provisioners(new IamRoleCfnProvisioner(iamService), new IamPolicyCfnProvisioner(iamService), + new IamManagedPolicyCfnProvisioner(iamService)) .build(); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamManagedPolicyCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamManagedPolicyCfnProvisionerTest.java new file mode 100644 index 0000000000..0df734d396 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamManagedPolicyCfnProvisionerTest.java @@ -0,0 +1,136 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +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.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.iam.IamService; +import io.github.hectorvent.floci.services.iam.model.IamPolicy; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +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.verify; +import static org.mockito.Mockito.when; + +/** + * {@code AWS::IAM::ManagedPolicy} in isolation: a create publishes the ARN for Ref and Fn::GetAtt + * PolicyArn, attaches the declared roles, and a delete detaches the roles before removing the + * policy, tolerating an already-gone attachment while propagating real failures. The deep + * adopt-on-update, version-pruning and rollback paths are exercised through the dispatcher by + * {@code CloudFormationIamAttachmentProvisionerTest} and the managed-policy integration test. + */ +class IamManagedPolicyCfnProvisionerTest { + + private static final String TYPE = "AWS::IAM::ManagedPolicy"; + private static final String ARN = "arn:aws:iam::000000000000:policy/app-policy"; + + private final IamService iam = mock(IamService.class); + private final IamManagedPolicyCfnProvisioner provisioner = new IamManagedPolicyCfnProvisioner(iam); + private final ObjectMapper mapper = new ObjectMapper(); + + @Test + void createPublishesTheArnAndAttachesRoles() throws Exception { + IamPolicy policy = mock(IamPolicy.class); + when(policy.getArn()).thenReturn(ARN); + when(policy.getPolicyId()).thenReturn("AID1"); + when(policy.getDefaultVersionId()).thenReturn("v1"); + when(iam.createPolicy(eq("app-policy"), eq("/"), eq(null), any(), eq(Map.of()))).thenReturn(policy); + + StackResource r = resource(); + provisioner.provision(r, props(""" + {"ManagedPolicyName": "app-policy", + "PolicyDocument": {"Version": "2012-10-17", "Statement": []}, + "Roles": ["web-role"]} + """), ctx(null)); + + assertEquals(ARN, r.getPhysicalId()); + assertEquals(ARN, r.getAttributes().get("PolicyArn")); + assertEquals(ARN, r.getAttributes().get("Arn")); + assertEquals("v1", r.getAttributes().get("DefaultVersionId")); + verify(iam).attachRolePolicy("web-role", ARN); + } + + @Test + void deleteDetachesRolesThenRemovesThePolicy() { + StackResource r = resource(); + r.setPhysicalId(ARN); + r.getAttributes().put("ManagedPolicyRoleTargets", "web-role"); + + provisioner.delete(r, "us-east-1"); + + InOrder order = inOrder(iam); + order.verify(iam).detachRolePolicy("web-role", ARN); + order.verify(iam).deletePolicy(ARN); + } + + @Test + void deleteToleratesAnAlreadyDetachedRole() { + StackResource r = resource(); + r.setPhysicalId(ARN); + r.getAttributes().put("ManagedPolicyRoleTargets", "web-role"); + doThrow(new AwsException("NoSuchEntity", "gone", 404)) + .when(iam).detachRolePolicy("web-role", ARN); + + assertDoesNotThrow(() -> provisioner.delete(r, "us-east-1")); + verify(iam).deletePolicy(ARN); + } + + @Test + void deletePropagatesANonNotFoundDetachFailure() { + StackResource r = resource(); + r.setPhysicalId(ARN); + r.getAttributes().put("ManagedPolicyRoleTargets", "web-role"); + doThrow(new AwsException("AccessDenied", "nope", 403)) + .when(iam).detachRolePolicy("web-role", ARN); + + AwsException failure = assertThrows(AwsException.class, () -> provisioner.delete(r, "us-east-1")); + assertEquals("AccessDenied", failure.getErrorCode()); + } + + private ProvisionContext ctx(String priorPhysicalId) { + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return node == null ? null : node.asText(); + }); + when(engine.resolveJsonAttributeStrict(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return node == null ? null : node.toString(); + }); + when(engine.resolveStringList(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + List out = new ArrayList<>(); + if (node != null && node.isArray()) { + node.forEach(element -> out.add(element.asText())); + } + return out; + }); + return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId); + } + + private JsonNode props(String json) throws Exception { + return mapper.readTree(json); + } + + private static StackResource resource() { + StackResource r = new StackResource(); + r.setLogicalId("Policy"); + r.setResourceType(TYPE); + r.setAttributes(new HashMap<>()); + return r; + } +} diff --git a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv index 953c709f19..e02a26f015 100644 --- a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv +++ b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv @@ -55,3 +55,8 @@ AWS::EKS::Cluster EncryptionConfigKeyArn not modeled: Floci does not apply envel AWS::EKS::Cluster Id not modeled: Floci identifies a cluster by its Name (the primary identifier and Ref), not a separate Id AWS::EKS::Nodegroup Id not published: Floci identifies a nodegroup by its name within the cluster, which is the Ref, not the composite Id AWS::IAM::Policy Id not published: Floci uses the policy name for Ref, AWS returns an opaque generated identifier that Floci does not model +AWS::IAM::ManagedPolicy AttachmentCount not published: the attachment count is dynamic and Floci does not expose it as a stable Fn::GetAtt value +AWS::IAM::ManagedPolicy CreateDate not published: Floci does not surface the policy create date as an Fn::GetAtt value +AWS::IAM::ManagedPolicy IsAttachable not modeled: Floci does not track policy attachability +AWS::IAM::ManagedPolicy PermissionsBoundaryUsageCount not modeled: Floci does not track permissions-boundary usage +AWS::IAM::ManagedPolicy UpdateDate not published: Floci does not surface the policy update date as an Fn::GetAtt value diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 060ae557f6..d5b42d7e2d 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -89,7 +89,7 @@ AWS::Events::EventBusPolicy EventsCfnProvisioner AWS::Events::Rule EventsCfnProvisioner AWS::IAM::AccessKey IamAccessKeyCfnProvisioner AWS::IAM::InstanceProfile IamInstanceProfileCfnProvisioner -AWS::IAM::ManagedPolicy LEGACY_SWITCH +AWS::IAM::ManagedPolicy IamManagedPolicyCfnProvisioner AWS::IAM::Policy IamPolicyCfnProvisioner AWS::IAM::Role IamRoleCfnProvisioner AWS::IAM::User IamUserCfnProvisioner