From ee74fd0a494f8206f0612c278ae723a92b7c058d Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 19 Sep 2026 21:52:06 -0500 Subject: [PATCH] refactor(cloudformation): move IAM inline Policy into IamPolicyCfnProvisioner (#3971) Move AWS::IAM::Policy out of the CloudFormationResourceProvisioner monolith into a new IamPolicyCfnProvisioner over IamService. AWS::IAM::Policy is an inline policy embedded in the named roles, users and groups, so Ref is the policy name with no ARN, the name is stable across updates unless the template changes it, and a failed update rolls back the partially applied puts and records anything it could not undo for the next provision to drain. A physical id that is a managed policy ARN is the pre-inline upgrade path, migrated and deleted here as before. The shared PolicyDocument resolver is hoisted onto ProvisionContext so the managed-policy provisioner can reuse it when it moves. Leaving LEGACY_SWITCH subjects the type to CfnSchemaCoverageTest: its only readOnly attribute, Id, is recorded as a gap row because Floci uses the policy name for Ref where AWS returns an opaque identifier it does not model. ManagedPolicy stays in the monolith for the following PR, so its delete and the legacy-managed helpers are duplicated between the two until then. --- .../CloudFormationResourceProvisioner.java | 295 +-------------- .../provisioners/IamPolicyCfnProvisioner.java | 352 ++++++++++++++++++ .../provisioners/ProvisionContext.java | 11 + .../cloudformation/CfnProvisionerFixture.java | 2 + ...FormationIamAttachmentProvisionerTest.java | 3 +- .../IamPolicyCfnProvisionerTest.java | 135 +++++++ .../cloudformation/getatt-attribute-gaps.tsv | 1 + .../supported-resource-types.tsv | 2 +- 8 files changed, 505 insertions(+), 296 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamPolicyCfnProvisioner.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamPolicyCfnProvisionerTest.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 f2afdfb95e..18ecf9586a 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 @@ -58,10 +58,6 @@ public class CloudFormationResourceProvisioner { private static final String LAMBDA_PACKAGE_TYPE_ATTR = "FlociLambdaPackageType"; static final String UPDATE_ROLLBACK_RESTORED_ATTR = CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR; static final String UPDATE_ROLLBACK_FAILURE_ATTR = CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR; - private static final String INLINE_CLEANUP_POLICY_NAME_ATTR = "__FlociInlineCleanupPolicyName"; - private static final String INLINE_CLEANUP_ROLE_TARGETS_ATTR = "__FlociInlineCleanupRoleTargets"; - private static final String INLINE_CLEANUP_USER_TARGETS_ATTR = "__FlociInlineCleanupUserTargets"; - private static final String INLINE_CLEANUP_GROUP_TARGETS_ATTR = "__FlociInlineCleanupGroupTargets"; private static final String NAME_MODE_EXPLICIT = "explicit"; private static final String NAME_MODE_GENERATED = "generated"; private static final int GENERATED_NAME_SUFFIX_LENGTH = 12; @@ -90,8 +86,7 @@ public class CloudFormationResourceProvisioner { static final Set DELETE_NEEDS_STACK_RESOURCE = Set.of( "AWS::ApiGatewayV2::Authorizer", "AWS::CloudFormation::CustomResource", - "AWS::IAM::ManagedPolicy", - "AWS::IAM::Policy"); + "AWS::IAM::ManagedPolicy"); /** * Every resource type the switch in {@link #provision} still serves. Load-bearing: the @@ -109,7 +104,6 @@ public class CloudFormationResourceProvisioner { "AWS::ApiGatewayV2::Stage", "AWS::CloudFormation::CustomResource", "AWS::IAM::ManagedPolicy", - "AWS::IAM::Policy", "AWS::Lambda::Function", "AWS::Lambda::LayerVersion"); @@ -215,7 +209,6 @@ public class CloudFormationResourceProvisioner { case "AWS::Lambda::Function" -> provisionLambda(resource, properties, engine, region, accountId, stackName); case "AWS::Lambda::LayerVersion" -> provisionLambdaLayerVersion(resource, properties, engine, region, stackName); - case "AWS::IAM::Policy" -> provisionIamInlinePolicy(resource, properties, engine, stackName); case "AWS::IAM::ManagedPolicy" -> provisionIamManagedPolicy(resource, properties, engine, accountId, stackName); case "AWS::ApiGatewayV2::Api" -> provisionApiGatewayV2Api(resource, properties, engine, region, accountId, stackName); @@ -383,12 +376,6 @@ public class CloudFormationResourceProvisioner { } return; } - // AWS::IAM::Policy is an inline policy; detaching it needs the principals it was attached to, - // which the type/physicalId delete path can't provide (only the delete-stack path has them). - if ("AWS::IAM::Policy".equals(resourceType)) { - deleteInlinePolicySafe(resource); - return; - } // Managed-policy deletion likewise needs the resolved role targets so it can detach the // policy before IAM's DeletePolicy operation. The type/physicalId path lacks that state. if ("AWS::IAM::ManagedPolicy".equals(resourceType)) { @@ -416,10 +403,6 @@ public class CloudFormationResourceProvisioner { } switch (resourceType) { case "AWS::Lambda::Function" -> deleteLambdaFunctionSafe(physicalId, region); - // AWS::IAM::Policy is inline: it is removed together with its owning principal (see - // IamRoleCfnProvisioner#delete), or precisely via the StackResource-aware delete path. - // Nothing to do here when only the physical id (policy name) is known, as on rollback. - case "AWS::IAM::Policy" -> { } case "AWS::IAM::ManagedPolicy" -> deletePolicySafe(physicalId); // No bus context on the type/physicalId path (e.g. CREATE-rollback); targets the default bus. case "AWS::ApiGatewayV2::Api" -> apiGatewayV2Service.deleteApi(region, physicalId); @@ -1139,173 +1122,6 @@ public class CloudFormationResourceProvisioner { return resolved != null ? resolved : "{\"Version\":\"2012-10-17\",\"Statement\":[]}"; } - /** - * Provisions {@code AWS::IAM::Policy}, which in AWS is an 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 = resolvePolicyDocument(props, engine); - - 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(CfnRollback.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 (!CfnRollback.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 @@ -2685,32 +2501,6 @@ public class CloudFormationResourceProvisioner { 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) { - CfnRollback.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"); @@ -2730,89 +2520,6 @@ public class CloudFormationResourceProvisioner { .toList(); } - /** Removes an {@code AWS::IAM::Policy} inline policy from each principal it was embedded in. */ - private void deleteInlinePolicySafe(StackResource resource) { - cleanupPendingInlinePolicies(resource); - if (isIamManagedPolicyArn(resource.getPhysicalId())) { - // Before AWS::IAM::Policy was modelled as an inline policy, Floci persisted it as a - // customer-managed policy ARN. Delete that legacy representation during an upgrade. - deleteManagedPolicy(resource); - return; - } - String policyName = resource.getPhysicalId(); - detachInline(resource.getAttributes().get("InlineRoleTargets"), - (name) -> iamService.deleteRolePolicy(name, policyName)); - detachInline(resource.getAttributes().get("InlineUserTargets"), - (name) -> iamService.deleteUserPolicy(name, policyName)); - detachInline(resource.getAttributes().get("InlineGroupTargets"), - (name) -> iamService.deleteGroupPolicy(name, policyName)); - } - - private boolean isIamManagedPolicyArn(String physicalId) { - return physicalId != null - && physicalId.startsWith("arn:") - && physicalId.contains(":iam::") - && physicalId.contains(":policy/"); - } - - private void detachInline(String targets, java.util.function.Consumer 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); - } - /** * 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/IamPolicyCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamPolicyCfnProvisioner.java new file mode 100644 index 0000000000..f373ce28cd --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamPolicyCfnProvisioner.java @@ -0,0 +1,352 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.iam.IamService; +import io.github.hectorvent.floci.services.iam.model.IamRole; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +/** + * CloudFormation provisioning for {@code AWS::IAM::Policy}, which in AWS is an inline + * policy embedded in the named roles, users and groups (PutRolePolicy / PutUserPolicy / + * PutGroupPolicy), not a standalone managed policy. {@code Ref} returns the policy name and the + * resource exposes no ARN. Because an inline policy name is scoped to its owning principal, the + * name is stable across updates unless the template changes it, and a failed update rolls back the + * partially applied puts, recording anything it could not undo for the next provision to drain. + * + *

A physical id that is a managed policy ARN is a pre-inline upgrade: those stacks persisted the + * policy as a customer-managed policy, so the legacy representation is migrated (detached and + * deleted) here and removed on delete. + */ +@ApplicationScoped +public class IamPolicyCfnProvisioner implements CfnResourceProvisioner { + + private static final Logger LOG = Logger.getLogger(IamPolicyCfnProvisioner.class); + + private static final String TYPE = "AWS::IAM::Policy"; + private static final String INLINE_CLEANUP_POLICY_NAME_ATTR = "__FlociInlineCleanupPolicyName"; + private static final String INLINE_CLEANUP_ROLE_TARGETS_ATTR = "__FlociInlineCleanupRoleTargets"; + private static final String INLINE_CLEANUP_USER_TARGETS_ATTR = "__FlociInlineCleanupUserTargets"; + private static final String INLINE_CLEANUP_GROUP_TARGETS_ATTR = "__FlociInlineCleanupGroupTargets"; + + private final IamService iamService; + + @Inject + public IamPolicyCfnProvisioner(IamService iamService) { + this.iamService = iamService; + } + + @Override + public Set resourceTypes() { + return Set.of(TYPE); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + CloudFormationTemplateEngine engine = ctx.engine(); + String previousPolicyName = r.getPhysicalId(); + String previousRoleTargets = r.getAttributes().get("InlineRoleTargets"); + String previousUserTargets = r.getAttributes().get("InlineUserTargets"); + String previousGroupTargets = r.getAttributes().get("InlineGroupTargets"); + boolean legacyManagedPolicy = isIamManagedPolicyArn(previousPolicyName); + String policyName = ctx.resolveOptional(props, "PolicyName"); + if (policyName == null || policyName.isBlank()) { + policyName = previousPolicyName != null && !previousPolicyName.isBlank() && !legacyManagedPolicy + ? previousPolicyName + : ctx.generatePhysicalName(r.getLogicalId(), 128, false); + } + String document = ctx.resolvePolicyDocument(props); + + final String name = policyName; + final String doc = document; + List 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); + } + + @Override + public void delete(StackResource resource, String region) { + cleanupPendingInlinePolicies(resource); + if (isIamManagedPolicyArn(resource.getPhysicalId())) { + // Legacy representation from before AWS::IAM::Policy was modelled as inline: delete the + // customer-managed policy it was persisted as. + deleteLegacyManagedPolicy(resource); + return; + } + String policyName = resource.getPhysicalId(); + detachInline(resource.getAttributes().get("InlineRoleTargets"), + name -> iamService.deleteRolePolicy(name, policyName)); + detachInline(resource.getAttributes().get("InlineUserTargets"), + name -> iamService.deleteUserPolicy(name, policyName)); + detachInline(resource.getAttributes().get("InlineGroupTargets"), + name -> iamService.deleteGroupPolicy(name, policyName)); + } + + private void putInlinePolicy(JsonNode props, String propName, CloudFormationTemplateEngine engine, + List successfulTargets, 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(CfnRollback.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(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true"); + } + + private List rollbackAppliedInlinePolicies(RuntimeException failure, String previousTargets, + List appliedTargets, String previousPolicyName, + String currentPolicyName, 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 (!CfnRollback.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)); + } + + private void cleanupPendingInlinePolicies(StackResource resource) { + String policyName = resource.getAttributes().get(INLINE_CLEANUP_POLICY_NAME_ATTR); + if (policyName == null || policyName.isBlank()) { + return; + } + detachInline(resource.getAttributes().get(INLINE_CLEANUP_ROLE_TARGETS_ATTR), + principal -> iamService.deleteRolePolicy(principal, policyName)); + detachInline(resource.getAttributes().get(INLINE_CLEANUP_USER_TARGETS_ATTR), + principal -> iamService.deleteUserPolicy(principal, policyName)); + detachInline(resource.getAttributes().get(INLINE_CLEANUP_GROUP_TARGETS_ATTR), + principal -> iamService.deleteGroupPolicy(principal, policyName)); + resource.getAttributes().remove(INLINE_CLEANUP_POLICY_NAME_ATTR); + resource.getAttributes().remove(INLINE_CLEANUP_ROLE_TARGETS_ATTR); + resource.getAttributes().remove(INLINE_CLEANUP_USER_TARGETS_ATTR); + resource.getAttributes().remove(INLINE_CLEANUP_GROUP_TARGETS_ATTR); + } + + private void deleteRemovedInlinePolicies(String previousTargets, List currentTargets, + String previousPolicyName, String currentPolicyName, + 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 detachInline(String targets, 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 boolean isIamManagedPolicyArn(String physicalId) { + return physicalId != null + && physicalId.startsWith("arn:") + && physicalId.contains(":iam::") + && physicalId.contains(":policy/"); + } + + // ── Legacy managed-policy representation (pre-inline upgrade path) ─────────── + + private void migrateLegacyManagedPolicy(StackResource resource) { + String policyArn = resource.getPhysicalId(); + List detachedRoles = new ArrayList<>(); + try { + for (String roleName : managedPolicyRoleTargets(resource)) { + try { + iamService.detachRolePolicy(roleName, policyArn); + detachedRoles.add(roleName); + } catch (AwsException e) { + if (!"NoSuchEntity".equals(e.getErrorCode())) { + throw e; + } + } + } + deleteManagedPolicySafe(policyArn); + } catch (RuntimeException failure) { + Collections.reverse(detachedRoles); + for (String roleName : detachedRoles) { + CfnRollback.attemptIamCleanup(failure, + "reattach legacy policy " + policyArn + " to role " + roleName, + () -> iamService.attachRolePolicy(roleName, policyArn)); + } + throw failure; + } + } + + private void deleteLegacyManagedPolicy(StackResource resource) { + String policyArn = resource.getPhysicalId(); + for (String roleName : managedPolicyRoleTargets(resource)) { + try { + iamService.detachRolePolicy(roleName, policyArn); + } catch (AwsException e) { + // Deletion is idempotent: the role or attachment can already be absent on a retry, + // but permission/service failures must keep the stack in DELETE_FAILED. + if (!"NoSuchEntity".equals(e.getErrorCode())) { + throw e; + } + } + } + deleteManagedPolicySafe(policyArn); + } + + private void deleteManagedPolicySafe(String policyArn) { + try { + iamService.deletePolicy(policyArn); + } catch (AwsException e) { + if (!"NoSuchEntity".equals(e.getErrorCode())) { + throw e; + } + LOG.debugv("IAM policy already gone, treating as deleted: {0}", policyArn); + } + } + + private List managedPolicyRoleTargets(StackResource resource) { + String policyArn = resource.getPhysicalId(); + String targets = resource.getAttributes().get("ManagedPolicyRoleTargets"); + if (targets == null) { + // Stacks persisted before target metadata was introduced still need to be deletable. + // The policy is stack-owned, so discover only roles that currently reference this ARN. + targets = iamService.listRoles("/").stream() + .filter(role -> role.getAttachedPolicyArns().contains(policyArn)) + .map(IamRole::getRoleName) + .collect(Collectors.joining("\n")); + } + if (targets == null || targets.isBlank()) { + return List.of(); + } + return Arrays.stream(targets.split("\n")) + .filter(roleName -> !roleName.isBlank()) + .toList(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java index c57d94ff6d..1a2e845311 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java @@ -113,6 +113,17 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio return new ArrayList<>(engine.resolveStringList(props.get(name))); } + /** + * The resolved {@code PolicyDocument} of an IAM policy resource as a JSON string, defaulting to + * an empty policy when the property is absent. Shared by the IAM policy provisioners so neither + * carries its own copy. + */ + public String resolvePolicyDocument(JsonNode props) { + JsonNode documentNode = props != null ? props.get("PolicyDocument") : null; + String resolved = documentNode != null ? engine.resolveJsonAttributeStrict(documentNode) : null; + return resolved != null ? resolved : "{\"Version\":\"2012-10-17\",\"Statement\":[]}"; + } + /** * The physical name for a resource whose name is create-only: the template's name when it gives * one, otherwise the name this resource already had, and only failing both a freshly generated 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 b7f5cd0cfc..b8eed188a4 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.IamPolicyCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.IamRoleCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.IamUserCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.IotCfnProvisioner; @@ -297,6 +298,7 @@ final class CfnProvisionerFixture { discovered.add(new IamUserCfnProvisioner(iamService)); discovered.add(new IamAccessKeyCfnProvisioner(iamService)); discovered.add(new IamInstanceProfileCfnProvisioner(iamService)); + discovered.add(new IamPolicyCfnProvisioner(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 69ec475559..92cfe537cb 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.IamPolicyCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.IamRoleCfnProvisioner; import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.services.iam.model.IamPolicy; @@ -49,7 +50,7 @@ class CloudFormationIamAttachmentProvisionerTest { provisioner = CfnProvisionerFixture.builder() .iam(iamService) .objectMapper(mapper) - .provisioners(new IamRoleCfnProvisioner(iamService)) + .provisioners(new IamRoleCfnProvisioner(iamService), new IamPolicyCfnProvisioner(iamService)) .build(); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamPolicyCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamPolicyCfnProvisionerTest.java new file mode 100644 index 0000000000..56ea31195e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamPolicyCfnProvisionerTest.java @@ -0,0 +1,135 @@ +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 org.junit.jupiter.api.Test; + +import java.util.HashMap; + +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.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * {@code AWS::IAM::Policy} (an inline policy) in isolation: it embeds the document into each + * declared role, user and group, Ref is the policy name with no ARN, an update reuses the name and + * detaches principals no longer listed, and delete removes the policy from every recorded target. + */ +class IamPolicyCfnProvisionerTest { + + private static final String TYPE = "AWS::IAM::Policy"; + + private final IamService iam = mock(IamService.class); + private final IamPolicyCfnProvisioner provisioner = new IamPolicyCfnProvisioner(iam); + private final ObjectMapper mapper = new ObjectMapper(); + + @Test + void embedsThePolicyIntoEachPrincipalAndRefIsTheName() throws Exception { + StackResource r = resource(); + provisioner.provision(r, props(""" + {"PolicyName": "app-policy", + "PolicyDocument": {"Version": "2012-10-17", "Statement": []}, + "Roles": ["web-role"], "Users": ["ci-user"]} + """), ctx(null)); + + assertEquals("app-policy", r.getPhysicalId()); + verify(iam).putRolePolicy(eq("web-role"), eq("app-policy"), any()); + verify(iam).putUserPolicy(eq("ci-user"), eq("app-policy"), any()); + assertEquals("web-role", r.getAttributes().get("InlineRoleTargets")); + assertEquals("ci-user", r.getAttributes().get("InlineUserTargets")); + // Inline policies have no ARN. + assertEquals(null, r.getAttributes().get("Arn")); + } + + @Test + void updateReusesTheNameAndDetachesAPrincipalNoLongerListed() throws Exception { + StackResource r = resource(); + r.setPhysicalId("app-policy"); + r.getAttributes().put("InlineRoleTargets", "web-role\nold-role"); + + provisioner.provision(r, props(""" + {"PolicyDocument": {"Version": "2012-10-17", "Statement": []}, + "Roles": ["web-role"]} + """), ctx("app-policy")); + + assertEquals("app-policy", r.getPhysicalId()); + verify(iam).putRolePolicy(eq("web-role"), eq("app-policy"), any()); + // old-role dropped from the template, so its inline copy is deleted. + verify(iam).deleteRolePolicy("old-role", "app-policy"); + verify(iam, never()).deleteRolePolicy("web-role", "app-policy"); + } + + @Test + void deleteRemovesThePolicyFromEveryRecordedTarget() { + StackResource r = resource(); + r.setPhysicalId("app-policy"); + r.getAttributes().put("InlineRoleTargets", "web-role"); + r.getAttributes().put("InlineUserTargets", "ci-user"); + r.getAttributes().put("InlineGroupTargets", ""); + + provisioner.delete(r, "us-east-1"); + + verify(iam).deleteRolePolicy("web-role", "app-policy"); + verify(iam).deleteUserPolicy("ci-user", "app-policy"); + } + + @Test + void deleteToleratesAPrincipalAlreadyGone() { + StackResource r = resource(); + r.setPhysicalId("app-policy"); + r.getAttributes().put("InlineRoleTargets", "web-role"); + doThrow(new AwsException("NoSuchEntity", "gone", 404)) + .when(iam).deleteRolePolicy("web-role", "app-policy"); + + assertDoesNotThrow(() -> provisioner.delete(r, "us-east-1")); + } + + @Test + void deletePropagatesANonNotFoundFailure() { + StackResource r = resource(); + r.setPhysicalId("app-policy"); + r.getAttributes().put("InlineRoleTargets", "web-role"); + doThrow(new AwsException("AccessDenied", "nope", 403)) + .when(iam).deleteRolePolicy("web-role", "app-policy"); + + 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(); + }); + 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 3bca27a4d1..953c709f19 100644 --- a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv +++ b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv @@ -54,3 +54,4 @@ AWS::EKS::Cluster ClusterSecurityGroupId not modeled: Floci does not create a cl AWS::EKS::Cluster EncryptionConfigKeyArn not modeled: Floci does not apply envelope encryption, so no KMS key arn is resolved 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 diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 8e269e5311..060ae557f6 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -90,7 +90,7 @@ AWS::Events::Rule EventsCfnProvisioner AWS::IAM::AccessKey IamAccessKeyCfnProvisioner AWS::IAM::InstanceProfile IamInstanceProfileCfnProvisioner AWS::IAM::ManagedPolicy LEGACY_SWITCH -AWS::IAM::Policy LEGACY_SWITCH +AWS::IAM::Policy IamPolicyCfnProvisioner AWS::IAM::Role IamRoleCfnProvisioner AWS::IAM::User IamUserCfnProvisioner AWS::IoT::DomainConfiguration IotDomainConfigurationCfnProvisioner