fix(cloudformation): create AWS::IAM::Role inline Policies instead of silently dropping them (#1969)

* fix(cloudformation): create AWS::IAM::Role inline Policies instead of silently dropping them

CreateStack now applies each entry of an IAM role's Policies array as an
inline role policy (PutRolePolicy semantics), resolving intrinsics inside
the policy document. Failures propagate so a policy that cannot be created
fails the stack instead of reporting CREATE_COMPLETE without it.

Fixes #1952

* refactor(cloudformation): move AWS::IAM::Role into its own provisioner

Continues the per-service decomposition started with SQS (#1825) by taking the
resource type this branch touches out of the CloudFormationResourceProvisioner
switch, carrying the #1952 inline-Policies fix with it.

- IamRoleCfnProvisioner owns provision and delete for AWS::IAM::Role: name
  resolution and same-stack adoption, managed-policy attachment with its
  rollback, the inline Policies of #1952, and the former deleteRoleSafe, whose
  only caller was the role delete arm.
- CfnRollback holds what both halves of the migration need instead of
  duplicating it: the __FlociRollbackOwned attribute that CloudFormationService
  reads to decide rollback deletion, and attemptIamCleanup, still used by the
  AWS::IAM::Policy and AWS::IAM::ManagedPolicy arms.
- ProvisionContext gains resolveStringList next to the resolveOptional and
  generatePhysicalName it already lifts from the monolith.
- IamRoleCfnProvisionerTest covers the inline policies and the delete path with
  one mocked service; the existing role rollback tests keep running through the
  public provision entry point, now with the provisioner registered.

Role provisioning behavior is otherwise unchanged.

* fix(cloudformation): inline role policies fail loudly and unwind on failure

Three review findings on the IAM role provisioner.

A Policies entry with a null or absent PolicyDocument was skipped, so the stack
reached CREATE_COMPLETE without the declared inline policy — the same silent
drop this PR set out to fix, one level in. It is a ValidationError now.

The inline-policy loop sat outside the block that unwinds a failed provision.
When putRolePolicy failed after createRole succeeded, the resource went
CREATE_FAILED, and because rollback only deletes resources that reached
CREATE_COMPLETE, the role, its managed attachments and any inline policies
already written were left behind. The loop now runs inside that block.

A failed update that adopted an existing role kept whatever the half-applied
attempt had granted. Inline writes are recorded with the value they replaced,
so unwinding restores the previous document, or removes the policy when this
attempt introduced the name. A role the stack did not create is not deleted.

* fix(cloudformation): reconcile role policies an update stopped declaring

An inline policy or managed attachment written by a previous execution and
absent from the new template stayed on the role while the stack still reported
UPDATE_COMPLETE. Both sets are now recorded on the resource and reconciled on
the success path, so what the template drops is removed. Only names a previous
execution recorded are touched, which leaves out-of-band policies alone.

PolicyName is required on AWS::IAM::Role Policies. Generating one gave the same
policy a fresh name on every execution, so an update accumulated copies instead
of replacing it. A missing PolicyName is now a ValidationError, matching what
this resource already does for a missing PolicyDocument.

* fix(cloudformation): skip reconciliation of a role policy already removed

deleteRolePolicy and detachRolePolicy both raise NoSuchEntity on an absent
target, so a tracked policy removed out of band between executions failed an
update whose desired end state already held. Reconciliation now skips what the
role no longer carries.
This commit is contained in:
lex00 authored and GitHub committed 2026-08-08 22:44:49 -05:00
1 parent 6d829ff7a4
commit 8d2a5bdd46
8 files changed
+841 -136

No files matched your search

@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.batch.BatchService;
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.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ProvisionContext;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceProvisioner;
@@ -113,7 +114,6 @@ 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";
@@ -287,7 +287,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::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" -> provisionIamInlinePolicy(resource, properties, engine, stackName);
@@ -488,10 +487,9 @@ public class CloudFormationResourceProvisioner {
case "AWS::SNS::Subscription" -> snsService.unsubscribe(physicalId, region);
case "AWS::DynamoDB::Table" -> deleteDynamoTableSafe(physicalId, region);
case "AWS::Lambda::Function" -> deleteLambdaFunctionSafe(physicalId, region);
case "AWS::IAM::Role" -> deleteRoleSafe(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.
// 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);
case "AWS::IAM::InstanceProfile" -> iamService.deleteInstanceProfile(physicalId);
@@ -2028,92 +2026,6 @@ public class CloudFormationResourceProvisioner {
}
}
// ── IAM Role ──────────────────────────────────────────────────────────────
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 = 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()
: "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
String path = resolveOptional(props, "Path", engine);
if (path == null) {
path = "/";
}
String description = resolveOptional(props, "Description", engine);
List<String> managedPolicyArns = resolveStringList(props, "ManagedPolicyArns", engine);
IamRole role;
boolean createdRole = false;
try {
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;
}
}
r.setPhysicalId(resolvedRoleName);
r.getAttributes().put("Arn", role.getArn());
r.getAttributes().put("RoleId", role.getRoleId());
Set<String> originalPolicyArns = new HashSet<>(role.getAttachedPolicyArns());
LinkedHashSet<String> attachedByThisAttempt = new LinkedHashSet<>();
try {
for (String policyArn : managedPolicyArns) {
iamService.attachRolePolicy(resolvedRoleName, policyArn);
if (!originalPolicyArns.contains(policyArn)) {
attachedByThisAttempt.add(policyArn);
}
}
} catch (RuntimeException failure) {
List<String> rollbackArns = new ArrayList<>(attachedByThisAttempt);
Collections.reverse(rollbackArns);
boolean cleanupSucceeded = true;
for (String policyArn : rollbackArns) {
String cleanupDescription = "detach policy " + policyArn + " from role " + resolvedRoleName;
if (!attemptIamCleanup(failure, cleanupDescription,
() -> iamService.detachRolePolicy(resolvedRoleName, policyArn))) {
cleanupSucceeded = false;
}
}
if (createdRole) {
if (!attemptIamCleanup(failure, "delete role " + resolvedRoleName,
() -> iamService.deleteRole(resolvedRoleName))) {
cleanupSucceeded = false;
}
if (cleanupSucceeded) {
r.getAttributes().remove(ROLLBACK_OWNED_ATTR);
}
}
throw failure;
}
}
// ── IAM Policy ────────────────────────────────────────────────────────────
/**
@@ -2215,7 +2127,7 @@ public class CloudFormationResourceProvisioner {
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");
resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
}
}
@@ -2262,7 +2174,7 @@ public class CloudFormationResourceProvisioner {
List<String> pendingTargets = new ArrayList<>();
for (String target : rollbackTargets) {
String description = "delete inline policy " + currentPolicyName + " from " + target;
if (!attemptIamCleanup(failure, description, () -> detachInline(target, cleanup))) {
if (!CfnRollback.attemptIamCleanup(failure, description, () -> detachInline(target, cleanup))) {
pendingTargets.add(target);
}
}
@@ -2303,7 +2215,7 @@ public class CloudFormationResourceProvisioner {
List<String> roleNames = resolveStringList(props, "Roles", engine);
var policy = iamService.createPolicy(policyName, "/", null, document, Map.of());
r.getAttributes().put(ROLLBACK_OWNED_ATTR, "true");
r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
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
@@ -2326,34 +2238,22 @@ public class CloudFormationResourceProvisioner {
boolean cleanupSucceeded = true;
for (String roleName : rollbackRoles) {
String cleanupDescription = "detach policy " + policy.getArn() + " from role " + roleName;
if (!attemptIamCleanup(failure, cleanupDescription,
if (!CfnRollback.attemptIamCleanup(failure, cleanupDescription,
() -> iamService.detachRolePolicy(roleName, policy.getArn()))) {
cleanupSucceeded = false;
}
}
if (!attemptIamCleanup(failure, "delete policy " + policy.getArn(),
if (!CfnRollback.attemptIamCleanup(failure, "delete policy " + policy.getArn(),
() -> iamService.deletePolicy(policy.getArn()))) {
cleanupSucceeded = false;
}
if (cleanupSucceeded) {
r.getAttributes().remove(ROLLBACK_OWNED_ATTR);
r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
}
throw failure;
}
}
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 ──────────────────────────────────────────────────
private void provisionInstanceProfile(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
@@ -4785,26 +4685,6 @@ public class CloudFormationResourceProvisioner {
return (value != null && !value.isBlank()) ? value : defaultValue;
}
private void deleteRoleSafe(String roleName) {
IamRole role;
try {
role = iamService.getRole(roleName);
} catch (AwsException e) {
if (!"NoSuchEntity".equals(e.getErrorCode())) {
throw e;
}
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);
@@ -4872,7 +4752,7 @@ public class CloudFormationResourceProvisioner {
} catch (RuntimeException failure) {
Collections.reverse(detachedRoles);
for (String roleName : detachedRoles) {
attemptIamCleanup(failure,
CfnRollback.attemptIamCleanup(failure,
"reattach legacy policy " + policyArn + " to role " + roleName,
() -> iamService.attachRolePolicy(roleName, policyArn));
}
@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.cloudformation.model.ChangeSet;
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
import io.github.hectorvent.floci.services.s3.S3Service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
@@ -632,7 +633,7 @@ public class CloudFormationService {
boolean completed = "CREATE_COMPLETE".equals(resource.getStatus());
boolean ownedFailedResource = "CREATE_FAILED".equals(resource.getStatus())
&& "true".equals(resource.getAttributes().get(
CloudFormationResourceProvisioner.ROLLBACK_OWNED_ATTR));
CfnRollback.ROLLBACK_OWNED_ATTR));
if (resource.getPhysicalId() == null || (!completed && !ownedFailedResource)) {
continue;
}
@@ -0,0 +1,42 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import org.jboss.logging.Logger;
/**
* Rollback bookkeeping shared by every resource handler, on both sides of the ongoing
* decomposition: the remaining {@code CloudFormationResourceProvisioner} switch arms and the
* extracted {@link CfnResourceProvisioner} implementations. It lives here instead of in either
* half so the ownership marker and the cleanup logging stay single-sourced while types migrate
* out one service at a time.
*/
public final class CfnRollback {
private static final Logger LOG = Logger.getLogger(CfnRollback.class);
/**
* Marks a resource whose backing entity this stack created. {@code CloudFormationService} reads
* it to decide whether a CREATE_FAILED resource still has to be deleted during stack rollback.
*/
public static final String ROLLBACK_OWNED_ATTR = "__FlociRollbackOwned";
private CfnRollback() {
}
/**
* Runs one compensating IAM call while unwinding a failed provision. The stack must report the
* primary failure, so a cleanup failure is attached to it as suppressed and logged rather than
* thrown. Returns false when the cleanup itself failed, leaving the caller to keep the
* resource marked as stack-owned.
*/
public static 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;
}
}
}
@@ -0,0 +1,275 @@
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.IamRole;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* CloudFormation provisioning for {@code AWS::IAM::Role}, moved out of the
* {@code CloudFormationResourceProvisioner} switch. The other IAM types (User, AccessKey, Policy,
* ManagedPolicy, InstanceProfile) still live there and share {@link CfnRollback} with this class.
*/
@ApplicationScoped
public class IamRoleCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(IamRoleCfnProvisioner.class);
private static final String INLINE_NAMES_ATTR = "__FlociInlinePolicyNames";
private static final String MANAGED_ARNS_ATTR = "__FlociManagedPolicyArns";
private final IamService iamService;
@Inject
public IamRoleCfnProvisioner(IamService iamService) {
this.iamService = iamService;
}
@Override
public Set<String> resourceTypes() {
return Set.of("AWS::IAM::Role");
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
String existingRoleName = r.getPhysicalId();
String roleName = ctx.resolveOptional(props, "RoleName");
if (roleName == null || roleName.isBlank()) {
roleName = existingRoleName != null && !existingRoleName.isBlank()
? existingRoleName
: ctx.generatePhysicalName(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()
: "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
String path = ctx.resolveOptional(props, "Path");
if (path == null) {
path = "/";
}
String description = ctx.resolveOptional(props, "Description");
List<String> managedPolicyArns = ctx.resolveStringList(props, "ManagedPolicyArns");
IamRole role;
boolean createdRole = false;
try {
role = iamService.createRole(resolvedRoleName, path, assumeDoc, description, 3600, Map.of());
createdRole = true;
r.getAttributes().put(CfnRollback.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(CfnRollback.ROLLBACK_OWNED_ATTR);
throw e;
}
}
r.setPhysicalId(resolvedRoleName);
r.getAttributes().put("Arn", role.getArn());
r.getAttributes().put("RoleId", role.getRoleId());
// What the previous execution of this resource wrote, so an update can take out what the
// template stopped declaring. Only these names are removed, which leaves inline policies and
// attachments added out of band alone.
Set<String> previousInlineNames = readTrackedSet(r, INLINE_NAMES_ATTR);
Set<String> previousManagedArns = readTrackedSet(r, MANAGED_ARNS_ATTR);
Set<String> originalPolicyArns = new HashSet<>(role.getAttachedPolicyArns());
LinkedHashSet<String> attachedByThisAttempt = new LinkedHashSet<>();
LinkedHashSet<String> detachedByThisAttempt = new LinkedHashSet<>();
LinkedHashSet<String> inlineRemovedByThisAttempt = new LinkedHashSet<>();
// What the inline policies looked like before this attempt, so a partial write can be put
// back. On an update that adopts an existing role these are the values to restore; for a
// name this attempt introduced there is no prior value and the policy is removed instead.
Map<String, String> originalInlinePolicies = new HashMap<>(role.getInlinePolicies());
LinkedHashSet<String> inlineWrittenByThisAttempt = new LinkedHashSet<>();
try {
for (String policyArn : managedPolicyArns) {
iamService.attachRolePolicy(resolvedRoleName, policyArn);
if (!originalPolicyArns.contains(policyArn)) {
attachedByThisAttempt.add(policyArn);
}
}
// Inline policies run inside the same protected block: a failure here used to leave
// the created role, its managed attachments and any earlier inline writes behind,
// because rollback only deletes resources that reached CREATE_COMPLETE.
if (props != null && props.has("Policies")) {
for (JsonNode policy : props.get("Policies")) {
String declaredName = ctx.resolveOptional(policy, "PolicyName");
if (declaredName == null || declaredName.isBlank()) {
// PolicyName is a required property of AWS::IAM::Role Policies. Generating
// one produced a fresh name on every execution, so an update accumulated
// copies of the same policy instead of replacing it.
throw new AwsException("ValidationError",
"An inline policy on role " + resolvedRoleName + " has no PolicyName.", 400);
}
final String policyName = declaredName;
JsonNode document = policy.get("PolicyDocument");
if (document == null || document.isNull()) {
// Skipping it and reporting CREATE_COMPLETE without the declared policy is
// the same class of bug as #1952 itself.
throw new AwsException("ValidationError",
"Inline policy '" + policyName + "' on role " + resolvedRoleName
+ " has no PolicyDocument.", 400);
}
iamService.putRolePolicy(resolvedRoleName, policyName,
ctx.engine().resolveNode(document).toString());
inlineWrittenByThisAttempt.add(policyName);
}
}
// Anything the previous execution wrote and this template no longer declares. Without
// this the role keeps permissions the stack stopped declaring while the stack still
// reports UPDATE_COMPLETE, which is the failure mode #1952 is about one level over.
// A tracked policy that is already gone is skipped rather than deleted again. Both IAM
// calls raise NoSuchEntity on an absent target, which would fail an update whose desired
// end state, the policy not being on the role, already holds.
for (String stale : previousInlineNames) {
if (!inlineWrittenByThisAttempt.contains(stale)
&& originalInlinePolicies.containsKey(stale)) {
iamService.deleteRolePolicy(resolvedRoleName, stale);
inlineRemovedByThisAttempt.add(stale);
}
}
for (String stale : previousManagedArns) {
if (!managedPolicyArns.contains(stale) && originalPolicyArns.contains(stale)) {
iamService.detachRolePolicy(resolvedRoleName, stale);
detachedByThisAttempt.add(stale);
}
}
} catch (RuntimeException failure) {
boolean cleanupSucceeded = true;
// Reconciliation runs last, so unwinding it comes first. A policy this attempt took out
// because the template stopped declaring it goes back with the document it had.
for (String policyName : inlineRemovedByThisAttempt) {
String prior = originalInlinePolicies.get(policyName);
if (prior == null) {
continue;
}
if (!CfnRollback.attemptIamCleanup(failure,
"restore inline policy " + policyName + " on role " + resolvedRoleName,
() -> iamService.putRolePolicy(resolvedRoleName, policyName, prior))) {
cleanupSucceeded = false;
}
}
for (String policyArn : detachedByThisAttempt) {
if (!CfnRollback.attemptIamCleanup(failure,
"reattach policy " + policyArn + " to role " + resolvedRoleName,
() -> iamService.attachRolePolicy(resolvedRoleName, policyArn))) {
cleanupSucceeded = false;
}
}
List<String> inlineRollback = new ArrayList<>(inlineWrittenByThisAttempt);
Collections.reverse(inlineRollback);
for (String policyName : inlineRollback) {
String prior = originalInlinePolicies.get(policyName);
String cleanupDescription = (prior == null ? "remove" : "restore")
+ " inline policy " + policyName + " on role " + resolvedRoleName;
if (!CfnRollback.attemptIamCleanup(failure, cleanupDescription, () -> {
if (prior == null) {
iamService.deleteRolePolicy(resolvedRoleName, policyName);
} else {
iamService.putRolePolicy(resolvedRoleName, policyName, prior);
}
})) {
cleanupSucceeded = false;
}
}
List<String> rollbackArns = new ArrayList<>(attachedByThisAttempt);
Collections.reverse(rollbackArns);
for (String policyArn : rollbackArns) {
String cleanupDescription = "detach policy " + policyArn + " from role " + resolvedRoleName;
if (!CfnRollback.attemptIamCleanup(failure, cleanupDescription,
() -> iamService.detachRolePolicy(resolvedRoleName, policyArn))) {
cleanupSucceeded = false;
}
}
if (createdRole) {
if (!CfnRollback.attemptIamCleanup(failure, "delete role " + resolvedRoleName,
() -> iamService.deleteRole(resolvedRoleName))) {
cleanupSucceeded = false;
}
if (cleanupSucceeded) {
r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
}
}
throw failure;
}
// What the next execution compares its template against.
writeTrackedSet(r, INLINE_NAMES_ATTR, inlineWrittenByThisAttempt);
writeTrackedSet(r, MANAGED_ARNS_ATTR, managedPolicyArns);
}
private static Set<String> readTrackedSet(StackResource r, String attribute) {
String raw = r.getAttributes().get(attribute);
if (raw == null || raw.isEmpty()) {
return Set.of();
}
return new LinkedHashSet<>(List.of(raw.split("\n")));
}
/**
* Newline separated because an IAM policy name may contain a comma, per the
* {@code [\w+=,.@-]+} pattern CloudFormation documents for {@code PolicyName}.
*/
private static void writeTrackedSet(StackResource r, String attribute, Collection<String> values) {
if (values.isEmpty()) {
r.getAttributes().remove(attribute);
return;
}
r.getAttributes().put(attribute, String.join("\n", values));
}
@Override
public void delete(String resourceType, String physicalId, String region) {
IamRole role;
try {
role = iamService.getRole(physicalId);
} catch (AwsException e) {
if (!"NoSuchEntity".equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("IAM role already gone, treating as deleted: {0}", physicalId);
return;
}
for (String policyArn : new ArrayList<>(role.getAttachedPolicyArns())) {
iamService.detachRolePolicy(physicalId, policyArn);
}
for (String policyName : new ArrayList<>(role.getInlinePolicies().keySet())) {
iamService.deleteRolePolicy(physicalId, policyName);
}
iamService.deleteRole(physicalId);
}
}
@@ -3,12 +3,14 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* The per-provision context every resource handler drew from: the template engine (for resolving
* intrinsic functions in properties) plus the region/account/stack it is being created in. The
* two helpers are lifted verbatim from {@code CloudFormationResourceProvisioner}'s private methods
* helpers are lifted verbatim from {@code CloudFormationResourceProvisioner}'s private methods
* so extracted provisioners produce byte-identical physical ids and resolved values.
*/
public record ProvisionContext(CloudFormationTemplateEngine engine, String region,
@@ -22,6 +24,20 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio
return engine.resolve(props.get(name));
}
/** Resolves an array property to its non-blank elements, or an empty list when absent. */
public List<String> resolveStringList(JsonNode props, String name) {
List<String> values = new ArrayList<>();
if (props != null && props.has(name) && props.get(name).isArray()) {
for (JsonNode element : props.get(name)) {
String resolved = engine.resolve(element);
if (resolved != null && !resolved.isBlank()) {
values.add(resolved);
}
}
}
return values;
}
/** Generates a CloudFormation-style physical name: {@code <stack>-<logicalId>-<suffix>}. */
public String generatePhysicalName(String logicalId, int maxLength, boolean lowercase) {
String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
@@ -4,7 +4,9 @@ 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.CfnRollback;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
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;
import io.github.hectorvent.floci.services.iam.model.IamRole;
@@ -51,7 +53,7 @@ class CloudFormationIamAttachmentProvisionerTest {
null, null, null, null, null, null, null,
null, null, null, null, null, null, null,
null,
new CloudFormationResourceRegistry(List.of()));
new CloudFormationResourceRegistry(List.of(new IamRoleCfnProvisioner(iamService))));
}
@Test
@@ -131,11 +133,11 @@ class CloudFormationIamAttachmentProvisionerTest {
"Role", "AWS::IAM::Role", """
{"RoleName":"same-name","ManagedPolicyArns":["%s"]}
""".formatted(NEW_POLICY), "same-name",
Map.of("RoleId", "AROAOLD", CloudFormationResourceProvisioner.ROLLBACK_OWNED_ATTR, "true"));
Map.of("RoleId", "AROAOLD", CfnRollback.ROLLBACK_OWNED_ATTR, "true"));
assertEquals("CREATE_FAILED", result.getStatus());
assertEquals("already exists", result.getStatusReason());
assertNull(result.getAttributes().get(CloudFormationResourceProvisioner.ROLLBACK_OWNED_ATTR));
assertNull(result.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
verify(iamService, never()).attachRolePolicy("same-name", NEW_POLICY);
verify(iamService, never()).deleteRole("same-name");
}
@@ -247,7 +249,7 @@ class CloudFormationIamAttachmentProvisionerTest {
assertEquals("CREATE_FAILED", result.getStatus());
assertEquals("existing-role", result.getAttributes().get("InlineRoleTargets"));
assertEquals("true", result.getAttributes().get(
CloudFormationResourceProvisioner.ROLLBACK_OWNED_ATTR));
CfnRollback.ROLLBACK_OWNED_ATTR));
provisioner.delete(result, "us-east-1");
@@ -0,0 +1,152 @@
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.hamcrest.Matchers.not;
/**
* End-to-end check that CloudFormation applies the inline {@code Policies} of an
* AWS::IAM::Role (issue #1952): the policies must be visible through the IAM API,
* intrinsics inside the policy documents must resolve, and DeleteStack must still
* be able to remove the role.
*/
@QuarkusTest
class CloudFormationIamRoleInlinePoliciesIntegrationTest {
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";
@Test
void createStackProvisionsInlineRolePoliciesAndDeleteStackRemovesRole() {
String suffix = Long.toString(System.nanoTime(), 36);
String roleName = "cfn-inline-role-" + suffix;
String bucketName = "cfn-inline-bucket-" + suffix;
String stackName = "cfn-inline-stack-" + suffix;
String template = """
{
"Resources": {
"DataBucket": {
"Type": "AWS::S3::Bucket",
"Properties": {"BucketName": "%s"}
},
"AppRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"RoleName": "%s",
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "lambda.amazonaws.com"},
"Action": "sts:AssumeRole"
}]
},
"Policies": [
{
"PolicyName": "bucket-read",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": {"Fn::GetAtt": ["DataBucket", "Arn"]}
}]
}
},
{
"PolicyName": "log-write",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "logs:PutLogEvents",
"Resource": "*"
}]
}
}
]
}
}
}
}
""".formatted(bucketName, roleName);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.formParam("Capabilities.member.1", "CAPABILITY_NAMED_IAM")
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
// Both inline policies exist on the role.
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "ListRolePolicies")
.formParam("RoleName", roleName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("bucket-read"))
.body(containsString("log-write"));
// The stored document resolved Fn::GetAtt to the bucket ARN.
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRolePolicy")
.formParam("RoleName", roleName)
.formParam("PolicyName", "bucket-read")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("s3:GetObject"))
.body(containsString("arn:aws:s3:::" + bucketName))
.body(not(containsString("Fn::GetAtt")));
// DeleteStack must remove the role despite its inline policies.
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRole")
.formParam("RoleName", roleName)
.when()
.post("/")
.then()
.statusCode(404);
}
}
@@ -0,0 +1,337 @@
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.IamRole;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
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.verify;
import static org.mockito.Mockito.when;
/**
* The IAM role CFN provisioner in isolation, with the inline {@code Policies} behavior of #1952.
* Rollback and role-adoption paths are covered end to end through the public provision entry point
* in {@code CloudFormationIamAttachmentProvisionerTest}.
*/
class IamRoleCfnProvisionerTest {
private static final String ACCOUNT_ID = "000000000000";
private static final String EMPTY_TRUST = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
private final IamService iam = mock(IamService.class);
private final IamRoleCfnProvisioner provisioner = new IamRoleCfnProvisioner(iam);
private final ObjectMapper mapper = new ObjectMapper();
private ProvisionContext ctx() {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
return new ProvisionContext(engine, "us-east-1", ACCOUNT_ID, "test-stack");
}
private StackResource resource() {
StackResource r = new StackResource();
r.setLogicalId("AppRole");
r.setResourceType("AWS::IAM::Role");
r.setAttributes(new HashMap<>());
return r;
}
private JsonNode props(String json) {
try {
return mapper.readTree(json);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private IamRole stubCreate(String roleName) {
IamRole role = new IamRole("AROA" + roleName, roleName, "/",
"arn:aws:iam::" + ACCOUNT_ID + ":role/" + roleName, EMPTY_TRUST);
when(iam.createRole(eq(roleName), eq("/"), anyString(), any(), eq(3600), eq(Map.of())))
.thenReturn(role);
return role;
}
@Test
void inlinePoliciesArePutOnTheRoleWithResolvedDocuments() {
stubCreate("app-role");
StackResource r = resource();
provisioner.provision(r, props("""
{
"RoleName": "app-role",
"Policies": [
{"PolicyName": "bucket-read",
"PolicyDocument": {"Version": "2012-10-17", "Statement": []}},
{"PolicyName": "log-write",
"PolicyDocument": {"Version": "2012-10-17", "Statement": []}}
]
}
"""), ctx());
assertEquals("app-role", r.getPhysicalId());
InOrder order = inOrder(iam);
order.verify(iam).putRolePolicy("app-role", "bucket-read", EMPTY_TRUST);
order.verify(iam).putRolePolicy("app-role", "log-write", EMPTY_TRUST);
}
@Test
void inlinePolicyWithoutANameFailsTheResource() {
// PolicyName is required on AWS::IAM::Role Policies. Generating one gave the same policy a
// fresh name on every execution, so an update accumulated copies instead of replacing it.
stubCreate("app-role");
StackResource r = resource();
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
{
"RoleName": "app-role",
"Policies": [{"PolicyDocument": {"Version": "2012-10-17", "Statement": []}}]
}
"""), ctx()));
assertEquals("ValidationError", failure.getErrorCode());
verify(iam, never()).putRolePolicy(anyString(), anyString(), anyString());
verify(iam).deleteRole("app-role");
assertNull(r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
}
@Test
void inlinePolicyWithoutADocumentFailsTheResource() {
// Skipping it reached CREATE_COMPLETE without the declared policy — the same class of
// bug as the silent drop this PR is about.
stubCreate("app-role");
StackResource r = resource();
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
{"RoleName": "app-role", "Policies": [{"PolicyName": "no-document"}]}
"""), ctx()));
assertEquals("ValidationError", failure.getErrorCode());
verify(iam, never()).putRolePolicy(anyString(), anyString(), anyString());
// The role this attempt created is cleaned up rather than left behind.
verify(iam).deleteRole("app-role");
assertNull(r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
}
@Test
void inlinePolicyFailureRemovesTheRoleAndTheEarlierInlineWrites() {
stubCreate("app-role");
doThrow(new AwsException("MalformedPolicyDocument", "bad policy", 400))
.when(iam).putRolePolicy(eq("app-role"), eq("second"), anyString());
StackResource r = resource();
assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
{
"RoleName": "app-role",
"Policies": [
{"PolicyName": "first", "PolicyDocument": {"Version": "2012-10-17", "Statement": []}},
{"PolicyName": "second", "PolicyDocument": {"Version": "2012-10-17", "Statement": []}}
]
}
"""), ctx()));
// "first" was written by this attempt and had no prior value, so it is removed, and the
// role goes with it. Previously both survived a CREATE_FAILED.
verify(iam).deleteRolePolicy("app-role", "first");
verify(iam).deleteRole("app-role");
assertNull(r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
}
@Test
void updateRemovesTheInlinePoliciesAndAttachmentsTheTemplateDropped() {
// A policy the previous execution wrote and the new template no longer declares used to
// stay on the role while the stack still reported UPDATE_COMPLETE.
IamRole existing = new IamRole("AROAapp-role", "app-role", "/",
"arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST);
existing.getInlinePolicies().put("keep", EMPTY_TRUST);
existing.getInlinePolicies().put("drop", EMPTY_TRUST);
existing.getAttachedPolicyArns().add("arn:aws:iam::aws:policy/Keep");
existing.getAttachedPolicyArns().add("arn:aws:iam::aws:policy/Drop");
when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), eq(Map.of())))
.thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
when(iam.getRole("app-role")).thenReturn(existing);
StackResource r = resource();
r.setPhysicalId("app-role");
r.getAttributes().put("RoleId", "AROAapp-role");
r.getAttributes().put("__FlociInlinePolicyNames", "keep\ndrop");
r.getAttributes().put("__FlociManagedPolicyArns",
"arn:aws:iam::aws:policy/Keep\narn:aws:iam::aws:policy/Drop");
provisioner.provision(r, props("""
{
"RoleName": "app-role",
"ManagedPolicyArns": ["arn:aws:iam::aws:policy/Keep"],
"Policies": [
{"PolicyName": "keep", "PolicyDocument": {"Version": "2012-10-17", "Statement": []}}
]
}
"""), ctx());
verify(iam).deleteRolePolicy("app-role", "drop");
verify(iam).detachRolePolicy("app-role", "arn:aws:iam::aws:policy/Drop");
verify(iam, never()).deleteRolePolicy("app-role", "keep");
verify(iam, never()).detachRolePolicy("app-role", "arn:aws:iam::aws:policy/Keep");
assertEquals("keep", r.getAttributes().get("__FlociInlinePolicyNames"));
}
@Test
void updateToleratesATrackedPolicyThatIsAlreadyGone() {
// Removed out of band between executions. deleteRolePolicy and detachRolePolicy both raise
// NoSuchEntity on an absent target, which would fail an update whose desired end state,
// the policy not being on the role, already holds.
IamRole existing = new IamRole("AROAapp-role", "app-role", "/",
"arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST);
when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), eq(Map.of())))
.thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
when(iam.getRole("app-role")).thenReturn(existing);
StackResource r = resource();
r.setPhysicalId("app-role");
r.getAttributes().put("RoleId", "AROAapp-role");
r.getAttributes().put("__FlociInlinePolicyNames", "gone");
r.getAttributes().put("__FlociManagedPolicyArns", "arn:aws:iam::aws:policy/Gone");
provisioner.provision(r, props("""
{"RoleName": "app-role", "Policies": []}
"""), ctx());
verify(iam, never()).deleteRolePolicy(anyString(), anyString());
verify(iam, never()).detachRolePolicy(anyString(), anyString());
assertNull(r.getAttributes().get("__FlociInlinePolicyNames"));
}
@Test
void updateLeavesInlinePoliciesTheStackNeverWroteAlone() {
// Only names a previous execution recorded are removed, so a policy added out of band
// survives an update that does not declare it.
IamRole existing = new IamRole("AROAapp-role", "app-role", "/",
"arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST);
existing.getInlinePolicies().put("added-out-of-band", EMPTY_TRUST);
when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), eq(Map.of())))
.thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
when(iam.getRole("app-role")).thenReturn(existing);
StackResource r = resource();
r.setPhysicalId("app-role");
r.getAttributes().put("RoleId", "AROAapp-role");
provisioner.provision(r, props("""
{"RoleName": "app-role", "Policies": []}
"""), ctx());
verify(iam, never()).deleteRolePolicy(anyString(), anyString());
}
@Test
void failedUpdateRestoresTheInlinePolicyItAlreadyOverwrote() {
// An update that adopts an existing role must not keep the permissions a half-applied
// attempt granted, and must not delete a role it did not create.
String priorDocument = "{\"Version\":\"2012-10-17\",\"Statement\":[\"prior\"]}";
IamRole existing = new IamRole("AROAapp-role", "app-role", "/",
"arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST);
existing.getInlinePolicies().put("first", priorDocument);
when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), eq(Map.of())))
.thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
when(iam.getRole("app-role")).thenReturn(existing);
doThrow(new AwsException("MalformedPolicyDocument", "bad policy", 400))
.when(iam).putRolePolicy(eq("app-role"), eq("second"), anyString());
StackResource r = resource();
r.setPhysicalId("app-role");
r.getAttributes().put("RoleId", "AROAapp-role");
assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
{
"RoleName": "app-role",
"Policies": [
{"PolicyName": "first", "PolicyDocument": {"Version": "2012-10-17", "Statement": []}},
{"PolicyName": "second", "PolicyDocument": {"Version": "2012-10-17", "Statement": []}}
]
}
"""), ctx()));
InOrder order = inOrder(iam);
order.verify(iam).putRolePolicy("app-role", "first", EMPTY_TRUST);
order.verify(iam).putRolePolicy("app-role", "first", priorDocument);
verify(iam, never()).deleteRolePolicy(anyString(), anyString());
verify(iam, never()).deleteRole(anyString());
}
@Test
void inlinePolicyFailureFailsTheResourceInsteadOfDroppingThePolicy() {
stubCreate("app-role");
doThrow(new AwsException("MalformedPolicyDocument", "bad policy", 400))
.when(iam).putRolePolicy(eq("app-role"), eq("broken"), anyString());
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(resource(), props("""
{
"RoleName": "app-role",
"Policies": [{"PolicyName": "broken",
"PolicyDocument": {"Version": "2012-10-17", "Statement": []}}]
}
"""), ctx()));
assertEquals("MalformedPolicyDocument", failure.getErrorCode());
}
@Test
void deleteRemovesAttachedAndInlinePoliciesBeforeTheRole() {
IamRole role = new IamRole("AROAapp-role", "app-role", "/",
"arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST);
role.getAttachedPolicyArns().add("arn:aws:iam::aws:policy/ReadOnlyAccess");
role.getInlinePolicies().put("bucket-read", EMPTY_TRUST);
when(iam.getRole("app-role")).thenReturn(role);
provisioner.delete("AWS::IAM::Role", "app-role", "us-east-1");
InOrder order = inOrder(iam);
order.verify(iam).detachRolePolicy("app-role", "arn:aws:iam::aws:policy/ReadOnlyAccess");
order.verify(iam).deleteRolePolicy("app-role", "bucket-read");
order.verify(iam).deleteRole("app-role");
}
@Test
void deleteTreatsAnAlreadyMissingRoleAsDeleted() {
when(iam.getRole("gone-role")).thenThrow(new AwsException("NoSuchEntity", "gone", 404));
provisioner.delete("AWS::IAM::Role", "gone-role", "us-east-1");
verify(iam, never()).deleteRole("gone-role");
}
@Test
void deletePropagatesUnexpectedLookupFailures() {
when(iam.getRole("denied-role")).thenThrow(new AwsException("AccessDenied", "denied", 403));
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.delete("AWS::IAM::Role", "denied-role", "us-east-1"));
assertEquals("AccessDenied", failure.getErrorCode());
verify(iam, never()).deleteRole("denied-role");
}
}