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

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

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

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

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

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

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

* fix(cloudformation): surface IAM attachment failures

* fix(cloudformation): roll back IAM resources safely

* fix(cloudformation): roll back partial inline policies

* fix(cloudformation): detach removed IAM targets

* fix(cloudformation): verify IAM policy target updates

* fix(cloudformation): preserve inline policy update state

* fix(cloudformation): migrate legacy IAM policies

* fix(cloudformation): roll back legacy policy migration

---------

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

No files matched your search

@@ -0,0 +1,650 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.IamPolicy;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class CloudFormationIamAttachmentProvisionerTest {
private static final String ACCOUNT_ID = "000000000000";
private static final String EXISTING_POLICY = "arn:aws:iam::aws:policy/ReadOnlyAccess";
private static final String NEW_POLICY = "arn:aws:iam::aws:policy/SecurityAudit";
private static final String MISSING_POLICY = "arn:aws:iam::aws:policy/Missing";
private final ObjectMapper mapper = new ObjectMapper();
private IamService iamService;
private CloudFormationResourceProvisioner provisioner;
@BeforeEach
void setUp() {
iamService = mock(IamService.class);
provisioner = new CloudFormationResourceProvisioner(
null, null, null, null, null, iamService, null, null, null, null,
null, null, null, null, null, null,
mapper,
null, null, null, null, null, null, null,
null, null, null, null, null, null, null,
new CloudFormationResourceRegistry(List.of()));
}
@Test
void newRoleAttachmentFailureDetachesPolicyThenDeletesRole() {
IamRole role = role("new-role");
when(iamService.createRole("new-role", "/", emptyTrustPolicy(), null, 3600, Map.of()))
.thenReturn(role);
doThrow(new AwsException("NoSuchEntity", "missing policy", 404))
.when(iamService).attachRolePolicy("new-role", MISSING_POLICY);
StackResource result = provisionRole("new-role", List.of(NEW_POLICY, MISSING_POLICY));
assertEquals("CREATE_FAILED", result.getStatus());
assertEquals("missing policy", result.getStatusReason());
InOrder cleanup = inOrder(iamService);
cleanup.verify(iamService).detachRolePolicy("new-role", NEW_POLICY);
cleanup.verify(iamService).deleteRole("new-role");
}
@Test
void sameStackRoleRetryPreservesOriginalPoliciesAndRole() {
IamRole role = role("existing-role");
role.getAttachedPolicyArns().add(EXISTING_POLICY);
when(iamService.createRole("existing-role", "/", emptyTrustPolicy(), null, 3600, Map.of()))
.thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409));
when(iamService.getRole("existing-role")).thenReturn(role);
doThrow(new AwsException("NoSuchEntity", "missing policy", 404))
.when(iamService).attachRolePolicy("existing-role", MISSING_POLICY);
StackResource result = provisionRole(
"existing-role", List.of(EXISTING_POLICY, NEW_POLICY, MISSING_POLICY),
"existing-role", Map.of("RoleId", role.getRoleId()));
assertEquals("CREATE_FAILED", result.getStatus());
verify(iamService).detachRolePolicy("existing-role", NEW_POLICY);
verify(iamService, never()).detachRolePolicy("existing-role", EXISTING_POLICY);
verify(iamService, never()).deleteRole("existing-role");
}
@Test
void freshRoleCollisionDoesNotAdoptUserOwnedRole() {
when(iamService.createRole("external-role", "/", emptyTrustPolicy(), null, 3600, Map.of()))
.thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409));
StackResource result = provisionRole("external-role", List.of(NEW_POLICY));
assertEquals("CREATE_FAILED", result.getStatus());
assertNull(result.getPhysicalId());
verify(iamService, never()).getRole("external-role");
verify(iamService, never()).attachRolePolicy("external-role", NEW_POLICY);
verify(iamService, never()).deleteRole("external-role");
}
@Test
void generatedRoleNameRemainsStableOnUpdate() {
IamRole role = role("generated-role");
when(iamService.createRole("generated-role", "/", emptyTrustPolicy(), null, 3600, Map.of()))
.thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409));
when(iamService.getRole("generated-role")).thenReturn(role);
StackResource result = provision(
"Role", "AWS::IAM::Role", "{}", "generated-role",
Map.of("RoleId", role.getRoleId()));
assertEquals("CREATE_COMPLETE", result.getStatus());
assertEquals("generated-role", result.getPhysicalId());
}
@Test
void sameNameRoleWithDifferentIdIsNotAdopted() {
IamRole replacement = role("same-name");
when(iamService.createRole("same-name", "/", emptyTrustPolicy(), null, 3600, Map.of()))
.thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409));
when(iamService.getRole("same-name")).thenReturn(replacement);
StackResource result = provision(
"Role", "AWS::IAM::Role", """
{"RoleName":"same-name","ManagedPolicyArns":["%s"]}
""".formatted(NEW_POLICY), "same-name",
Map.of("RoleId", "AROAOLD", CloudFormationResourceProvisioner.ROLLBACK_OWNED_ATTR, "true"));
assertEquals("CREATE_FAILED", result.getStatus());
assertEquals("already exists", result.getStatusReason());
assertNull(result.getAttributes().get(CloudFormationResourceProvisioner.ROLLBACK_OWNED_ATTR));
verify(iamService, never()).attachRolePolicy("same-name", NEW_POLICY);
verify(iamService, never()).deleteRole("same-name");
}
@Test
void roleNameChangeFailsBeforeCreatingReplacement() {
StackResource result = provision(
"Role", "AWS::IAM::Role", "{\"RoleName\":\"new-role\"}",
"old-role", Map.of());
assertEquals("CREATE_FAILED", result.getStatus());
assertEquals("Updating RoleName requires resource replacement, which is not supported.",
result.getStatusReason());
verify(iamService, never()).createRole(
"new-role", "/", emptyTrustPolicy(), null, 3600, Map.of());
}
@Test
void unexpectedRoleCreationFailureIsNotTreatedAsAnExistingRole() {
when(iamService.createRole("denied-role", "/", emptyTrustPolicy(), null, 3600, Map.of()))
.thenThrow(new AwsException("AccessDenied", "denied", 403));
StackResource result = provisionRole("denied-role", List.of());
assertEquals("CREATE_FAILED", result.getStatus());
assertEquals("denied", result.getStatusReason());
verify(iamService, never()).getRole("denied-role");
}
@Test
void managedPolicyAttachmentFailureDetachesRolesThenDeletesPolicy() {
String policyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/test-policy";
IamPolicy policy = new IamPolicy(
"ANPATEST", "test-policy", "/", policyArn, null, "{}");
when(iamService.createPolicy("test-policy", "/", null, policyDocument(), Map.of()))
.thenReturn(policy);
doThrow(new AwsException("NoSuchEntity", "missing role", 404))
.when(iamService).attachRolePolicy("missing-role", policyArn);
StackResource result = provision("ManagedPolicy", "AWS::IAM::ManagedPolicy", """
{
"ManagedPolicyName": "test-policy",
"PolicyDocument": {"Version": "2012-10-17", "Statement": []},
"Roles": ["existing-role", "missing-role"]
}
""");
assertEquals("CREATE_FAILED", result.getStatus());
InOrder cleanup = inOrder(iamService);
cleanup.verify(iamService).detachRolePolicy("existing-role", policyArn);
cleanup.verify(iamService).deletePolicy(policyArn);
verify(iamService, never()).deleteRole("existing-role");
}
@Test
void cleanupFailureDoesNotMaskPrimaryFailureOrSkipDeletion() {
IamRole role = role("cleanup-role");
when(iamService.createRole("cleanup-role", "/", emptyTrustPolicy(), null, 3600, Map.of()))
.thenReturn(role);
doThrow(new AwsException("NoSuchEntity", "primary failure", 404))
.when(iamService).attachRolePolicy("cleanup-role", MISSING_POLICY);
doThrow(new AwsException("ServiceFailure", "cleanup failure", 500))
.when(iamService).detachRolePolicy("cleanup-role", NEW_POLICY);
StackResource result = provisionRole("cleanup-role", List.of(NEW_POLICY, MISSING_POLICY));
assertEquals("CREATE_FAILED", result.getStatus());
assertEquals("primary failure", result.getStatusReason());
verify(iamService).detachRolePolicy("cleanup-role", NEW_POLICY);
verify(iamService).deleteRole("cleanup-role");
}
@Test
void inlinePolicyAttachmentFailurePreservesSuccessfulTargetsForRollback() {
String policyName = "test-inline-policy";
doThrow(new AwsException("NoSuchEntity", "missing role", 404))
.when(iamService).putRolePolicy("missing-role", policyName, policyDocument());
StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """
{
"PolicyName": "%s",
"PolicyDocument": {"Version": "2012-10-17", "Statement": []},
"Roles": ["existing-role", "missing-role"]
}
""".formatted(policyName));
assertEquals("CREATE_FAILED", result.getStatus());
assertEquals("existing-role", result.getAttributes().get("InlineRoleTargets"));
assertEquals("true", result.getAttributes().get(
CloudFormationResourceProvisioner.ROLLBACK_OWNED_ATTR));
provisioner.delete(result, "us-east-1");
verify(iamService).deleteRolePolicy("existing-role", policyName);
verify(iamService, never()).deleteRolePolicy("missing-role", policyName);
}
@Test
void inlinePolicyUpdateDetachesRemovedTargetsAcrossPrincipalTypes() {
String policyName = "test-inline-policy";
StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """
{
"PolicyName": "%s",
"PolicyDocument": {"Version": "2012-10-17", "Statement": []},
"Roles": ["retained-role", "added-role"],
"Users": ["added-user"],
"Groups": ["retained-group"]
}
""".formatted(policyName), policyName, Map.of(
"InlineRoleTargets", "removed-role\nretained-role",
"InlineUserTargets", "removed-user",
"InlineGroupTargets", "removed-group\nretained-group"));
assertEquals("CREATE_COMPLETE", result.getStatus());
assertEquals("retained-role\nadded-role", result.getAttributes().get("InlineRoleTargets"));
assertEquals("added-user", result.getAttributes().get("InlineUserTargets"));
assertEquals("retained-group", result.getAttributes().get("InlineGroupTargets"));
verify(iamService).deleteRolePolicy("removed-role", policyName);
verify(iamService, never()).deleteRolePolicy("retained-role", policyName);
verify(iamService).deleteUserPolicy("removed-user", policyName);
verify(iamService).deleteGroupPolicy("removed-group", policyName);
verify(iamService, never()).deleteGroupPolicy("retained-group", policyName);
}
@Test
void inlinePolicyNameChangeDeletesOldPolicyFromRetainedTargets() {
String previousPolicyName = "previous-inline-policy";
String currentPolicyName = "current-inline-policy";
StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """
{
"PolicyName": "%s",
"PolicyDocument": {"Version": "2012-10-17", "Statement": []},
"Roles": ["retained-role"],
"Users": ["retained-user"],
"Groups": ["retained-group"]
}
""".formatted(currentPolicyName), previousPolicyName, Map.of(
"InlineRoleTargets", "retained-role",
"InlineUserTargets", "retained-user",
"InlineGroupTargets", "retained-group"));
assertEquals("CREATE_COMPLETE", result.getStatus());
assertEquals(currentPolicyName, result.getPhysicalId());
verify(iamService).deleteRolePolicy("retained-role", previousPolicyName);
verify(iamService).deleteUserPolicy("retained-user", previousPolicyName);
verify(iamService).deleteGroupPolicy("retained-group", previousPolicyName);
}
@Test
void inlinePolicyUpdateFailurePreservesPreviousTargetsAndRemovesNewAttachments() {
String policyName = "test-inline-policy";
doThrow(new AwsException("NoSuchEntity", "missing user", 404))
.when(iamService).putUserPolicy("missing-user", policyName, policyDocument());
StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """
{
"PolicyName": "%s",
"PolicyDocument": {"Version": "2012-10-17", "Statement": []},
"Roles": ["new-role"],
"Users": ["missing-user"]
}
""".formatted(policyName), policyName, Map.of(
"InlineRoleTargets", "old-role",
"InlineUserTargets", "old-user",
"InlineGroupTargets", "old-group"));
assertEquals("CREATE_FAILED", result.getStatus());
assertEquals(policyName, result.getPhysicalId());
assertEquals("old-role", result.getAttributes().get("InlineRoleTargets"));
assertEquals("old-user", result.getAttributes().get("InlineUserTargets"));
assertEquals("old-group", result.getAttributes().get("InlineGroupTargets"));
assertEquals("true", result.getAttributes().get(
CloudFormationResourceProvisioner.UPDATE_ROLLBACK_RESTORED_ATTR));
verify(iamService).deleteRolePolicy("new-role", policyName);
verify(iamService, never()).deleteRolePolicy("old-role", policyName);
}
@Test
void inlinePolicyNameChangeFailureRemovesNewNameAndPreservesOldMetadata() {
String previousPolicyName = "previous-inline-policy";
String currentPolicyName = "current-inline-policy";
doThrow(new AwsException("NoSuchEntity", "missing user", 404))
.when(iamService).putUserPolicy("missing-user", currentPolicyName, policyDocument());
StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """
{
"PolicyName": "%s",
"PolicyDocument": {"Version": "2012-10-17", "Statement": []},
"Roles": ["retained-role"],
"Users": ["missing-user"]
}
""".formatted(currentPolicyName), previousPolicyName, Map.of(
"InlineRoleTargets", "retained-role",
"InlineUserTargets", "",
"InlineGroupTargets", ""));
assertEquals("CREATE_FAILED", result.getStatus());
assertEquals(previousPolicyName, result.getPhysicalId());
assertEquals("retained-role", result.getAttributes().get("InlineRoleTargets"));
verify(iamService).deleteRolePolicy("retained-role", currentPolicyName);
verify(iamService, never()).deleteRolePolicy("retained-role", previousPolicyName);
}
@Test
void generatedInlinePolicyNameRemainsStableOnUpdate() {
String policyName = "generated-inline-policy";
StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """
{
"PolicyDocument": {"Version": "2012-10-17", "Statement": []},
"Roles": ["retained-role"]
}
""", policyName, Map.of("InlineRoleTargets", "retained-role"));
assertEquals("CREATE_COMPLETE", result.getStatus());
assertEquals(policyName, result.getPhysicalId());
verify(iamService).putRolePolicy("retained-role", policyName, policyDocument());
}
@Test
void legacyManagedInlinePolicyMigratesDuringUpdate() {
String legacyPolicyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/legacy-policy";
IamRole oldRole = role("old-role");
oldRole.getAttachedPolicyArns().add(legacyPolicyArn);
when(iamService.listRoles("/")).thenReturn(List.of(oldRole));
StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """
{
"PolicyDocument": {"Version": "2012-10-17", "Statement": []},
"Roles": ["new-role"]
}
""", legacyPolicyArn, Map.of("Arn", legacyPolicyArn));
assertEquals("CREATE_COMPLETE", result.getStatus());
assertFalse(result.getPhysicalId().startsWith("arn:"));
assertNull(result.getAttributes().get("Arn"));
InOrder migration = inOrder(iamService);
migration.verify(iamService).putRolePolicy("new-role", result.getPhysicalId(), policyDocument());
migration.verify(iamService).detachRolePolicy("old-role", legacyPolicyArn);
migration.verify(iamService).deletePolicy(legacyPolicyArn);
}
@Test
void failedLegacyMigrationPreservesManagedPolicyForRetry() {
String legacyPolicyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/legacy-policy";
doThrow(new AwsException("NoSuchEntity", "missing user", 404))
.when(iamService).putUserPolicy(eq("missing-user"), anyString(), eq(policyDocument()));
StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """
{
"PolicyDocument": {"Version": "2012-10-17", "Statement": []},
"Users": ["missing-user"]
}
""", legacyPolicyArn, Map.of("Arn", legacyPolicyArn));
assertEquals("CREATE_FAILED", result.getStatus());
assertEquals(legacyPolicyArn, result.getPhysicalId());
assertEquals(legacyPolicyArn, result.getAttributes().get("Arn"));
verify(iamService, never()).deletePolicy(legacyPolicyArn);
}
@Test
void legacyMigrationRestoresDetachedRoleWhenPolicyDeletionFails() {
String legacyPolicyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/legacy-policy";
IamRole oldRole = role("old-role");
oldRole.getAttachedPolicyArns().add(legacyPolicyArn);
when(iamService.listRoles("/")).thenReturn(List.of(oldRole));
doThrow(new AwsException("ServiceFailure", "delete failed", 500))
.when(iamService).deletePolicy(legacyPolicyArn);
StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """
{
"PolicyDocument": {"Version": "2012-10-17", "Statement": []},
"Roles": ["new-role"]
}
""", legacyPolicyArn, Map.of("Arn", legacyPolicyArn));
assertEquals("CREATE_FAILED", result.getStatus());
assertEquals(legacyPolicyArn, result.getPhysicalId());
assertEquals(legacyPolicyArn, result.getAttributes().get("Arn"));
InOrder rollback = inOrder(iamService);
rollback.verify(iamService).putRolePolicy(eq("new-role"), anyString(), eq(policyDocument()));
rollback.verify(iamService).detachRolePolicy("old-role", legacyPolicyArn);
rollback.verify(iamService).deletePolicy(legacyPolicyArn);
rollback.verify(iamService).attachRolePolicy("old-role", legacyPolicyArn);
rollback.verify(iamService).deleteRolePolicy(eq("new-role"), anyString());
}
@Test
void inlinePolicyUpdateTracksFailedCleanupForStackDeletion() {
String policyName = "test-inline-policy";
doThrow(new AwsException("NoSuchEntity", "missing user", 404))
.when(iamService).putUserPolicy("missing-user", policyName, policyDocument());
doThrow(new AwsException("AccessDenied", "cleanup denied", 403))
.doNothing()
.when(iamService).deleteRolePolicy("new-role", policyName);
StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """
{
"PolicyName": "%s",
"PolicyDocument": {"Version": "2012-10-17", "Statement": []},
"Roles": ["new-role"],
"Users": ["missing-user"]
}
""".formatted(policyName), policyName,
Map.of("InlineRoleTargets", "old-role"));
assertEquals("CREATE_FAILED", result.getStatus());
assertEquals("old-role", result.getAttributes().get("InlineRoleTargets"));
provisioner.delete(result, "us-east-1");
verify(iamService, times(2)).deleteRolePolicy("new-role", policyName);
verify(iamService).deleteRolePolicy("old-role", policyName);
}
@Test
void inlinePolicyRemovalFailureDoesNotCommitTheNewTargetLedger() {
String policyName = "test-inline-policy";
doThrow(new AwsException("AccessDenied", "cannot remove old role", 403))
.when(iamService).deleteRolePolicy("old-role", policyName);
StackResource result = provision("InlinePolicy", "AWS::IAM::Policy", """
{
"PolicyName": "%s",
"PolicyDocument": {"Version": "2012-10-17", "Statement": []},
"Roles": ["new-role"]
}
""".formatted(policyName), policyName,
Map.of("InlineRoleTargets", "old-role"));
assertEquals("CREATE_FAILED", result.getStatus());
assertEquals("old-role", result.getAttributes().get("InlineRoleTargets"));
verify(iamService).deleteRolePolicy("old-role", policyName);
verify(iamService).deleteRolePolicy("new-role", policyName);
}
@Test
void inlinePolicyDeletionIgnoresAlreadyMissingPrincipal() {
String policyName = "test-inline-policy";
StackResource resource = new StackResource();
resource.setResourceType("AWS::IAM::Policy");
resource.setPhysicalId(policyName);
resource.setAttributes(Map.of("InlineRoleTargets", "missing-role"));
doThrow(new AwsException("NoSuchEntity", "already gone", 404))
.when(iamService).deleteRolePolicy("missing-role", policyName);
provisioner.delete(resource, "us-east-1");
verify(iamService).deleteRolePolicy("missing-role", policyName);
}
@Test
void inlinePolicyDeletionPropagatesUnexpectedFailure() {
String policyName = "test-inline-policy";
StackResource resource = new StackResource();
resource.setResourceType("AWS::IAM::Policy");
resource.setPhysicalId(policyName);
resource.setAttributes(Map.of("InlineRoleTargets", "role-a"));
doThrow(new AwsException("AccessDenied", "denied", 403))
.when(iamService).deleteRolePolicy("role-a", policyName);
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.delete(resource, "us-east-1"));
assertEquals("AccessDenied", failure.getErrorCode());
}
@Test
void legacyManagedInlinePolicyIsDetachedAndDeleted() {
String policyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/legacy-policy";
IamRole role = role("legacy-role");
role.getAttachedPolicyArns().add(policyArn);
when(iamService.listRoles("/")).thenReturn(List.of(role));
StackResource resource = new StackResource();
resource.setResourceType("AWS::IAM::Policy");
resource.setPhysicalId(policyArn);
resource.setAttributes(Map.of("Arn", policyArn));
provisioner.delete(resource, "us-east-1");
InOrder deletion = inOrder(iamService);
deletion.verify(iamService).detachRolePolicy("legacy-role", policyArn);
deletion.verify(iamService).deletePolicy(policyArn);
}
@Test
void managedPolicyDeletionDetachesStoredRolesBeforeDeletingPolicy() {
String policyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/test-policy";
StackResource resource = new StackResource();
resource.setResourceType("AWS::IAM::ManagedPolicy");
resource.setPhysicalId(policyArn);
resource.setAttributes(Map.of("ManagedPolicyRoleTargets", "role-a\nrole-b"));
provisioner.delete(resource, "us-east-1");
InOrder deletion = inOrder(iamService);
deletion.verify(iamService).detachRolePolicy("role-a", policyArn);
deletion.verify(iamService).detachRolePolicy("role-b", policyArn);
deletion.verify(iamService).deletePolicy(policyArn);
}
@Test
void managedPolicyDeletionIgnoresAlreadyMissingAttachments() {
String policyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/test-policy";
StackResource resource = new StackResource();
resource.setResourceType("AWS::IAM::ManagedPolicy");
resource.setPhysicalId(policyArn);
resource.setAttributes(Map.of("ManagedPolicyRoleTargets", "missing-role"));
doThrow(new AwsException("NoSuchEntity", "already gone", 404))
.when(iamService).detachRolePolicy("missing-role", policyArn);
provisioner.delete(resource, "us-east-1");
verify(iamService).deletePolicy(policyArn);
}
@Test
void managedPolicyDeletionDiscoversTargetsForOlderPersistedStacks() {
String policyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/test-policy";
IamRole role = role("legacy-role");
role.getAttachedPolicyArns().add(policyArn);
when(iamService.listRoles("/")).thenReturn(List.of(role));
StackResource resource = new StackResource();
resource.setResourceType("AWS::IAM::ManagedPolicy");
resource.setPhysicalId(policyArn);
resource.setAttributes(Map.of());
provisioner.delete(resource, "us-east-1");
InOrder deletion = inOrder(iamService);
deletion.verify(iamService).detachRolePolicy("legacy-role", policyArn);
deletion.verify(iamService).deletePolicy(policyArn);
}
@Test
void managedPolicyDeletionPropagatesUnexpectedDetachFailure() {
String policyArn = "arn:aws:iam::" + ACCOUNT_ID + ":policy/test-policy";
StackResource resource = new StackResource();
resource.setResourceType("AWS::IAM::ManagedPolicy");
resource.setPhysicalId(policyArn);
resource.setAttributes(Map.of("ManagedPolicyRoleTargets", "role-a"));
doThrow(new AwsException("AccessDenied", "denied", 403))
.when(iamService).detachRolePolicy("role-a", policyArn);
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.delete(resource, "us-east-1"));
assertEquals("AccessDenied", failure.getErrorCode());
verify(iamService, never()).deletePolicy(policyArn);
}
private StackResource provisionRole(String roleName, List<String> policyArns) {
return provisionRole(roleName, policyArns, null);
}
private StackResource provisionRole(String roleName, List<String> policyArns,
String existingPhysicalId) {
return provisionRole(roleName, policyArns, existingPhysicalId, Map.of());
}
private StackResource provisionRole(String roleName, List<String> policyArns,
String existingPhysicalId,
Map<String, String> existingAttributes) {
String policies = policyArns.stream()
.map(value -> "\"" + value + "\"")
.reduce((left, right) -> left + "," + right)
.orElse("");
return provision("Role", "AWS::IAM::Role", """
{"RoleName":"%s","ManagedPolicyArns":[%s]}
""".formatted(roleName, policies), existingPhysicalId, existingAttributes);
}
private StackResource provision(String logicalId, String type, String json) {
return provision(logicalId, type, json, null, Map.of());
}
private StackResource provision(String logicalId, String type, String json,
String existingPhysicalId, Map<String, String> existingAttributes) {
return provisioner.provision(logicalId, type, props(json), engine(),
"us-east-1", ACCOUNT_ID, "test-stack", existingPhysicalId, existingAttributes);
}
private CloudFormationTemplateEngine engine() {
return new CloudFormationTemplateEngine(
ACCOUNT_ID, "us-east-1", "test-stack", "stack/id",
Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), mapper,
(Function<String, String>) name -> null);
}
private JsonNode props(String json) {
try {
return mapper.readTree(json);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static IamRole role(String name) {
return new IamRole("AROA" + name, name, "/",
"arn:aws:iam::" + ACCOUNT_ID + ":role/" + name, emptyTrustPolicy());
}
private static String emptyTrustPolicy() {
return "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
}
private static String policyDocument() {
return "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
}
}
@@ -0,0 +1,798 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Regression for GH-1531: two CloudFormation stacks in the same account each declare an
* {@code AWS::IAM::Policy} with the same auto-generated {@code PolicyName} (as CDK emits when two
* stacks reuse a construct sub-tree — e.g. {@code IamTaskRoleDefaultPolicy<hash>}) but attach it to
* different roles. {@code AWS::IAM::Policy} is an <em>inline</em> policy, scoped to its owning
* principal, so both stacks must deploy. Previously Floci modelled it as a standalone (account-global)
* managed policy, so the second stack failed with "Policy ... already exists" and rolled back.
*
* <p>Also asserts that {@code AWS::IAM::ManagedPolicy} remains a standalone managed policy with an ARN.
* IAM is the Query API (form-encoded request, XML response); no containers involved, so Docker-free.
*/
@QuarkusTest
class CloudFormationIamInlinePolicyIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/iam/aws4_request";
private static String stackWithInlinePolicy(String roleName, String policyName) {
return """
{
"Resources": {
"Role": {
"Type": "AWS::IAM::Role",
"Properties": {
"RoleName": "%s",
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "ecs-tasks.amazonaws.com"},
"Action": "sts:AssumeRole"
}]
}
}
},
"DefaultPolicy": {
"Type": "AWS::IAM::Policy",
"Properties": {
"PolicyName": "%s",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "*"
}]
},
"Roles": [{"Ref": "Role"}]
}
}
}
}
""".formatted(roleName, policyName);
}
private static String inlinePolicyForExistingRole(String policyName, String roleName, String action) {
return """
{
"Resources": {
"DefaultPolicy": {
"Type": "AWS::IAM::Policy",
"Properties": {
"PolicyName": "%s",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "%s", "Resource": "*"}]
},
"Roles": ["%s"]
}
}
}
}
""".formatted(policyName, action, roleName);
}
private static String inlinePolicyForExistingRoleAndUser(
String policyName, String roleName, String userName, String action) {
return """
{
"Resources": {
"DefaultPolicy": {
"Type": "AWS::IAM::Policy",
"Properties": {
"PolicyName": "%s",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "%s", "Resource": "*"}]
},
"Roles": ["%s"],
"Users": ["%s"]
}
}
}
}
""".formatted(policyName, action, roleName, userName);
}
private static void createStack(String stackName, String template) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
}
private static void updateStack(String stackName, String template) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
}
private static void assertStackComplete(String stackName) {
assertStackStatus(stackName, "CREATE_COMPLETE");
}
private static void assertStackStatus(String stackName, String status) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>" + status + "</StackStatus>"));
}
@Test
void twoStacksReusingSameInlinePolicyNameBothDeploy() {
String suffix = Long.toString(System.nanoTime(), 36);
// Same auto-generated policy name in both stacks — the exact GH-1531 collision.
String sharedPolicyName = "IamTaskRoleDefaultPolicy" + suffix;
String roleA = "role-a-" + suffix;
String roleB = "role-b-" + suffix;
createStack("cfn-iam-inline-a-" + suffix, stackWithInlinePolicy(roleA, sharedPolicyName));
assertStackComplete("cfn-iam-inline-a-" + suffix);
// Before the fix this second stack rolled back ("Policy ... already exists").
createStack("cfn-iam-inline-b-" + suffix, stackWithInlinePolicy(roleB, sharedPolicyName));
assertStackComplete("cfn-iam-inline-b-" + suffix);
// Each role really carries the inline policy, scoped to that role.
for (String roleName : new String[] {roleA, roleB}) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRolePolicy")
.formParam("RoleName", roleName)
.formParam("PolicyName", sharedPolicyName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString(sharedPolicyName))
.body(containsString("s3:GetObject"));
}
}
@Test
void updateRemovingRoleDetachesInlinePolicy() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-iam-inline-update-" + suffix;
String policyName = "inline-update-policy-" + suffix;
String oldRole = "inline-update-old-" + suffix;
String newRole = "inline-update-new-" + suffix;
for (String roleName : new String[] {oldRole, newRole}) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "CreateRole")
.formParam("RoleName", roleName)
.formParam("AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[]}")
.when().post("/").then().statusCode(200);
}
createStack(stackName, inlinePolicyForExistingRole(policyName, oldRole, "s3:GetObject"));
assertStackComplete(stackName);
updateStack(stackName, inlinePolicyForExistingRole(policyName, newRole, "s3:PutObject"));
assertStackStatus(stackName, "UPDATE_COMPLETE");
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRolePolicy")
.formParam("RoleName", oldRole)
.formParam("PolicyName", policyName)
.when().post("/").then().statusCode(404).body(containsString("NoSuchEntity"));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRolePolicy")
.formParam("RoleName", newRole)
.formParam("PolicyName", policyName)
.when().post("/").then().statusCode(200).body(containsString("s3:PutObject"));
}
@Test
void failedUpdatePreservesPriorInlinePolicyForStackDeletion() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-iam-inline-failed-update-" + suffix;
String policyName = "inline-failed-update-policy-" + suffix;
String oldRole = "inline-failed-update-old-" + suffix;
String newRole = "inline-failed-update-new-" + suffix;
String missingUser = "inline-failed-update-missing-" + suffix;
for (String roleName : new String[] {oldRole, newRole}) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "CreateRole")
.formParam("RoleName", roleName)
.formParam("AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[]}")
.when().post("/").then().statusCode(200);
}
createStack(stackName, inlinePolicyForExistingRole(policyName, oldRole, "s3:GetObject"));
assertStackComplete(stackName);
updateStack(stackName, inlinePolicyForExistingRoleAndUser(
policyName, newRole, missingUser, "s3:PutObject"));
assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRolePolicy")
.formParam("RoleName", oldRole)
.formParam("PolicyName", policyName)
.when().post("/").then().statusCode(200).body(containsString("s3:GetObject"));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRolePolicy")
.formParam("RoleName", newRole)
.formParam("PolicyName", policyName)
.when().post("/").then().statusCode(404).body(containsString("NoSuchEntity"));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when().post("/").then().statusCode(200);
awaitInlinePolicyGone(oldRole, policyName);
}
@Test
void managedPolicyRemainsStandaloneWithArn() {
String suffix = Long.toString(System.nanoTime(), 36);
String managedName = "managed-policy-" + suffix;
String stackName = "cfn-iam-managed-" + suffix;
String template = """
{
"Resources": {
"ManagedPolicy": {
"Type": "AWS::IAM::ManagedPolicy",
"Properties": {
"ManagedPolicyName": "%s",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "*"
}]
}
}
}
},
"Outputs": {
"PolicyArn": {"Value": {"Ref": "ManagedPolicy"}}
}
}
""".formatted(managedName);
createStack(stackName, template);
// Managed policy has an ARN (unlike inline), surfaced through Ref.
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
.body(containsString(":policy/" + managedName));
}
@Test
void deletingManagedPolicyDetachesItFromSurvivingRole() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String roleName = "managed-policy-role-" + suffix;
String policyName = "attached-managed-policy-" + suffix;
String policyArn = "arn:aws:iam::000000000000:policy/" + policyName;
String stackName = "cfn-iam-managed-del-" + suffix;
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "CreateRole")
.formParam("RoleName", roleName)
.formParam("AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[]}")
.when().post("/").then().statusCode(200);
String template = """
{
"Resources": {
"ManagedPolicy": {
"Type": "AWS::IAM::ManagedPolicy",
"Properties": {
"ManagedPolicyName": "%s",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]
},
"Roles": ["%s"]
}
}
}
}
""".formatted(policyName, roleName);
createStack(stackName, template);
assertStackComplete(stackName);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when().post("/").then().statusCode(200);
awaitManagedPolicyGone(policyArn);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRole")
.formParam("RoleName", roleName)
.when().post("/").then().statusCode(200).body(containsString(roleName));
String attachments = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "ListAttachedRolePolicies")
.formParam("RoleName", roleName)
.when().post("/").then().statusCode(200).extract().asString();
assertFalse(attachments.contains(policyName), "deleted policy must be detached: " + attachments);
}
@Test
void roleWithMissingManagedPolicyFailsAndRollsBack() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-iam-role-missing-policy-" + suffix;
String roleName = "missing-policy-role-" + suffix;
String validArn = "arn:aws:iam::aws:policy/ReadOnlyAccess";
String missingArn = "arn:aws:iam::aws:policy/DefinitelyMissing-" + suffix;
String template = """
{
"Resources": {
"Role": {
"Type": "AWS::IAM::Role",
"Properties": {
"RoleName": "missing-policy-role-%s",
"ManagedPolicyArns": ["%s", "%s"]
}
}
}
}
""".formatted(suffix, validArn, missingArn);
createStack(stackName, template);
assertFailedResource(stackName, "Role", missingArn, "does not exist");
// The first attachment succeeded before the second failed. Rollback must detach it and
// delete the role created by this failed resource instead of leaking a partial IAM entity.
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRole")
.formParam("RoleName", roleName)
.when().post("/").then().statusCode(404).body(containsString("NoSuchEntity"));
}
@Test
void freshStackDoesNotAdoptExistingRole() {
String suffix = Long.toString(System.nanoTime(), 36);
String roleName = "externally-owned-role-" + suffix;
String stackName = "cfn-iam-role-collision-" + suffix;
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "CreateRole")
.formParam("RoleName", roleName)
.formParam("AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[]}")
.when().post("/").then().statusCode(200);
String template = """
{
"Resources": {
"Role": {
"Type": "AWS::IAM::Role",
"Properties": {"RoleName": "%s"}
}
}
}
""".formatted(roleName);
createStack(stackName, template);
assertFailedResource(stackName, "Role", roleName, "already exists");
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRole")
.formParam("RoleName", roleName)
.when().post("/").then().statusCode(200).body(containsString(roleName));
}
@Test
void managedPolicyWithMissingRoleFailsAndRollsBack() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-iam-policy-missing-role-" + suffix;
String existingRole = "existing-role-" + suffix;
String missingRole = "missing-role-" + suffix;
String policyName = "missing-role-policy-" + suffix;
String policyArn = "arn:aws:iam::000000000000:policy/" + policyName;
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "CreateRole")
.formParam("RoleName", existingRole)
.formParam("AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[]}")
.when().post("/").then().statusCode(200);
String template = """
{
"Resources": {
"ManagedPolicy": {
"Type": "AWS::IAM::ManagedPolicy",
"Properties": {
"ManagedPolicyName": "missing-role-policy-%s",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]
},
"Roles": ["%s", "%s"]
}
}
}
}
""".formatted(suffix, existingRole, missingRole);
createStack(stackName, template);
assertFailedResource(stackName, "ManagedPolicy", missingRole, "cannot be found");
// Rollback removes the policy it created and only detaches the role supplied by the user.
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetPolicy")
.formParam("PolicyArn", policyArn)
.when().post("/").then().statusCode(404).body(containsString("NoSuchEntity"));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRole")
.formParam("RoleName", existingRole)
.when().post("/").then().statusCode(200).body(containsString(existingRole));
String attachments = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "ListAttachedRolePolicies")
.formParam("RoleName", existingRole)
.when().post("/").then().statusCode(200).extract().asString();
assertFalse(attachments.contains(policyName), "failed policy must be detached: " + attachments);
}
@Test
void inlinePolicyWithMissingRoleRollsBackSuccessfulAttachment() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-iam-inline-missing-role-" + suffix;
String existingRole = "inline-existing-role-" + suffix;
String missingRole = "inline-missing-role-" + suffix;
String policyName = "inline-missing-role-policy-" + suffix;
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "CreateRole")
.formParam("RoleName", existingRole)
.formParam("AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[]}")
.when().post("/").then().statusCode(200);
String template = """
{
"Resources": {
"InlinePolicy": {
"Type": "AWS::IAM::Policy",
"Properties": {
"PolicyName": "%s",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]
},
"Roles": ["%s", "%s"]
}
}
}
}
""".formatted(policyName, existingRole, missingRole);
createStack(stackName, template);
String stack = describeStack(stackName, "DescribeStacks");
assertTrue(stack.contains("<StackStatus>ROLLBACK_COMPLETE</StackStatus>"),
"stack should roll back after the inline attachment failure: " + stack);
String resources = describeStack(stackName, "DescribeStackResources");
assertTrue(
resources.contains("<LogicalResourceId>InlinePolicy</LogicalResourceId>")
&& resources.contains("<ResourceStatus>DELETE_COMPLETE</ResourceStatus>"),
"partially attached inline policy should be rolled back: " + resources);
String events = describeStack(stackName, "DescribeStackEvents");
assertTrue(events.contains(missingRole) && events.contains("cannot be found"),
"failure reason should identify the missing role: " + events);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRolePolicy")
.formParam("RoleName", existingRole)
.formParam("PolicyName", policyName)
.when().post("/").then().statusCode(404).body(containsString("NoSuchEntity"));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRole")
.formParam("RoleName", existingRole)
.when().post("/").then().statusCode(200).body(containsString(existingRole));
}
@Test
void laterResourceFailureRollsBackCompletedManagedPolicyAttachments() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-iam-later-failure-" + suffix;
String existingRole = "rollback-target-role-" + suffix;
String policyName = "rollback-target-policy-" + suffix;
String policyArn = "arn:aws:iam::000000000000:policy/" + policyName;
String missingArn = "arn:aws:iam::aws:policy/RollbackMissing-" + suffix;
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "CreateRole")
.formParam("RoleName", existingRole)
.formParam("AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[]}")
.when().post("/").then().statusCode(200);
String template = """
{
"Resources": {
"ManagedPolicy": {
"Type": "AWS::IAM::ManagedPolicy",
"Properties": {
"ManagedPolicyName": "%s",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]
},
"Roles": ["%s"]
}
},
"FailingRole": {
"Type": "AWS::IAM::Role",
"DependsOn": "ManagedPolicy",
"Properties": {
"RoleName": "later-failing-role-%s",
"ManagedPolicyArns": ["%s"]
}
}
}
}
""".formatted(policyName, existingRole, suffix, missingArn);
createStack(stackName, template);
assertFailedResource(stackName, "FailingRole", missingArn, "does not exist");
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetPolicy")
.formParam("PolicyArn", policyArn)
.when().post("/").then().statusCode(404).body(containsString("NoSuchEntity"));
String attachments = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "ListAttachedRolePolicies")
.formParam("RoleName", existingRole)
.when().post("/").then().statusCode(200).extract().asString();
assertFalse(attachments.contains(policyName), "rolled-back policy must be detached: " + attachments);
}
@Test
void deletingStackDetachesInlinePolicyFromSurvivingRole() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String roleName = "ext-role-" + suffix;
String policyName = "InlinePolicy" + suffix;
String stackName = "cfn-iam-inline-del-" + suffix;
// Role owned OUTSIDE the stack, so it survives DeleteStack — this isolates the inline-policy
// detach (deleteInlinePolicySafe/detachInline) from a cascade role delete.
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "CreateRole")
.formParam("RoleName", roleName)
.formParam("AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"ecs-tasks.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}")
.when().post("/").then().statusCode(200);
String template = """
{
"Resources": {
"DefaultPolicy": {
"Type": "AWS::IAM::Policy",
"Properties": {
"PolicyName": "%s",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]
},
"Roles": ["%s"]
}
}
}
}
""".formatted(policyName, roleName);
createStack(stackName, template);
assertStackComplete(stackName);
// The inline policy is embedded in the pre-existing role.
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRolePolicy")
.formParam("RoleName", roleName)
.formParam("PolicyName", policyName)
.when().post("/").then().statusCode(200).body(containsString("s3:GetObject"));
// Deleting the stack must detach the inline policy from the surviving role (async delete).
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when().post("/").then().statusCode(200);
awaitInlinePolicyGone(roleName, policyName);
// The role still exists ...
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRole")
.formParam("RoleName", roleName)
.when().post("/").then().statusCode(200).body(containsString(roleName));
// ... but its inline policy is gone (NoSuchEntity, HTTP 404).
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRolePolicy")
.formParam("RoleName", roleName)
.formParam("PolicyName", policyName)
.when().post("/").then().statusCode(404).body(containsString("NoSuchEntity"));
}
/** DeleteStack runs asynchronously; poll until the inline policy has been detached (404) or time out. */
private static void awaitInlinePolicyGone(String roleName, String policyName) throws InterruptedException {
for (int i = 0; i < 100; i++) {
int sc = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRolePolicy")
.formParam("RoleName", roleName)
.formParam("PolicyName", policyName)
.when().post("/").then().extract().statusCode();
if (sc == 404) {
return;
}
Thread.sleep(50);
}
throw new AssertionError("Timed out waiting for inline policy " + policyName
+ " to be detached from role " + roleName);
}
private static void awaitManagedPolicyGone(String policyArn) throws InterruptedException {
for (int i = 0; i < 100; i++) {
int status = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetPolicy")
.formParam("PolicyArn", policyArn)
.when().post("/").then().extract().statusCode();
if (status == 404) {
return;
}
Thread.sleep(50);
}
throw new AssertionError("Timed out waiting for managed policy " + policyArn + " to be deleted");
}
private static void assertFailedResource(String stackName, String logicalId,
String expectedSubject, String expectedReason) {
String stack = describeStack(stackName, "DescribeStacks");
assertTrue(
stack.contains("<StackStatus>ROLLBACK_COMPLETE</StackStatus>"),
"stack should roll back after the attachment failure: " + stack);
assertFalse(
stack.contains("<StackStatus>CREATE_COMPLETE</StackStatus>"),
"stack must not report false success: " + stack);
String resources = describeStack(stackName, "DescribeStackResources");
assertTrue(
resources.contains("<LogicalResourceId>" + logicalId + "</LogicalResourceId>")
&& resources.contains("<ResourceStatus>CREATE_FAILED</ResourceStatus>"),
"failed resource status should be visible: " + resources);
String events = describeStack(stackName, "DescribeStackEvents");
assertTrue(
events.contains(expectedSubject) && events.contains(expectedReason),
"failure reason should identify the missing attachment target: " + events);
}
private static String describeStack(String stackName, String action) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stackName)
.when().post("/").then().statusCode(200).extract().asString();
}
}