fix(cloudformation): attach managed policies to users and groups (#8708)

This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-11-17 09:47:02 -04:00
1 parent 2fdcbecdf0
commit 76413ce74a
7 files changed
+736 -118

No files matched your search

@@ -1,11 +1,18 @@
package io.floci.aws.services.cloudformation;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -326,6 +333,98 @@ class CloudFormationIamInlinePolicyIntegrationTest {
.body(containsString(":policy/" + managedName));
}
@Test
void managedPolicyAttachesUsersAndGroups() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String userName = "managed-policy-user-" + suffix;
String groupName = "managed-policy-group-" + suffix;
String policyName = "managed-principal-policy-" + suffix;
String policyArn = "arn:aws:iam::000000000000:policy/" + policyName;
String stackName = "cfn-managed-principals-" + suffix;
String template = """
{
"Resources": {
"ManagedPolicy": {
"Type": "AWS::IAM::ManagedPolicy",
"Properties": {
"ManagedPolicyName": "%s",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]
},
"Users": ["%s"],
"Groups": ["%s"]
}
}
}
}
""".formatted(policyName, userName, groupName);
try (IamClient iam = AwsTestClients.create(IamClient.builder(), "test", Region.US_EAST_1)) {
iam.createUser(request -> request.userName(userName));
iam.createGroup(request -> request.groupName(groupName));
createStack(stackName, template);
assertStackComplete(stackName);
assertAll(
() -> assertEquals(List.of(policyArn), iam.listAttachedUserPolicies(request ->
request.userName(userName)).attachedPolicies().stream()
.map(policy -> policy.policyArn()).toList()),
() -> assertEquals(List.of(policyArn), iam.listAttachedGroupPolicies(request ->
request.groupName(groupName)).attachedPolicies().stream()
.map(policy -> policy.policyArn()).toList()));
CfnStackWaits.deleteStack(stackName, CFN_AUTH);
assertAll(
() -> assertTrue(iam.listAttachedUserPolicies(request ->
request.userName(userName)).attachedPolicies().isEmpty()),
() -> assertTrue(iam.listAttachedGroupPolicies(request ->
request.groupName(groupName)).attachedPolicies().isEmpty()));
}
}
@Test
void managedPolicyAttachesSameStackUserRefAndDeletesBeforeUser() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String userName = "managed-ref-user-" + suffix;
String policyName = "managed-ref-policy-" + suffix;
String policyArn = "arn:aws:iam::000000000000:policy/" + policyName;
String stackName = "cfn-managed-user-ref-" + suffix;
String template = """
{
"Resources": {
"User": {
"Type": "AWS::IAM::User",
"Properties": {"UserName": "%s"}
},
"ManagedPolicy": {
"Type": "AWS::IAM::ManagedPolicy",
"Properties": {
"ManagedPolicyName": "%s",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]
},
"Users": [{"Ref": "User"}]
}
}
}
}
""".formatted(userName, policyName);
try (IamClient iam = AwsTestClients.create(IamClient.builder(), "test", Region.US_EAST_1)) {
createStack(stackName, template);
assertStackComplete(stackName);
assertEquals(List.of(policyArn), iam.listAttachedUserPolicies(request ->
request.userName(userName)).attachedPolicies().stream()
.map(policy -> policy.policyArn()).toList());
CfnStackWaits.deleteStack(stackName, CFN_AUTH);
}
}
@Test
void deletingManagedPolicyDetachesItFromSurvivingRole() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
@@ -364,14 +463,7 @@ class CloudFormationIamInlinePolicyIntegrationTest {
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);
CfnStackWaits.deleteStack(stackName, CFN_AUTH);
given()
.contentType("application/x-www-form-urlencoded")
@@ -753,22 +845,6 @@ class CloudFormationIamInlinePolicyIntegrationTest {
+ " 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) {
CfnStackWaits.awaitStatus(stackName, "ROLLBACK_COMPLETE", CFN_AUTH);
@@ -3,6 +3,7 @@ package io.floci.aws.services.cloudformation;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.services.cloudformation.model.Stack;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.iam.model.IamRole;
import io.floci.aws.testing.CfnStackWaits;
@@ -20,6 +21,8 @@ import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
@@ -59,7 +62,7 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
}
@SuppressWarnings("unchecked")
private void forgetPolicyId(String stackName, String logicalId) throws ReflectiveOperationException {
private StackResource stackResource(String stackName, String logicalId) throws ReflectiveOperationException {
Object target = cloudFormationService instanceof ClientProxy proxy
? proxy.arc_contextualInstance()
: cloudFormationService;
@@ -70,7 +73,11 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
.filter(s -> stackName.equals(s.getStackName()))
.findFirst()
.orElseThrow(() -> new IllegalStateException("Stack not found: " + stackName));
stack.getResources().get(logicalId).getAttributes().remove("PolicyId");
return stack.getResources().get(logicalId);
}
private void forgetPolicyId(String stackName, String logicalId) throws ReflectiveOperationException {
stackResource(stackName, logicalId).getAttributes().remove("PolicyId");
}
@SuppressWarnings("unchecked")
@@ -303,6 +310,136 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
.body(containsString(policyArn(policyName)));
}
@Test
void updateRetargetingUsersAndGroupsDetachesRemovedTargets() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-mp-principal-update-" + suffix;
String policyName = "mp-principal-update-" + suffix;
String oldUser = "mp-old-user-" + suffix;
String newUser = "mp-new-user-" + suffix;
String oldGroup = "mp-old-group-" + suffix;
String newGroup = "mp-new-group-" + suffix;
String arn = policyArn(policyName);
for (String userName : new String[] {oldUser, newUser}) {
iam("CreateUser", "UserName", userName);
}
for (String groupName : new String[] {oldGroup, newGroup}) {
iam("CreateGroup", "GroupName", groupName);
}
createStack(stackName, literalPrincipalManagedPolicyTemplate(
policyName, "s3:GetObject", oldUser, oldGroup));
assertStackStatus(stackName, "CREATE_COMPLETE");
updateStack(stackName, literalPrincipalManagedPolicyTemplate(
policyName, "s3:PutObject", newUser, newGroup));
assertStackStatus(stackName, "UPDATE_COMPLETE");
assertFalse(iam("ListAttachedUserPolicies", "UserName", oldUser).contains(arn));
assertFalse(iam("ListAttachedGroupPolicies", "GroupName", oldGroup).contains(arn));
assertTrue(iam("ListAttachedUserPolicies", "UserName", newUser).contains(arn));
assertTrue(iam("ListAttachedGroupPolicies", "GroupName", newGroup).contains(arn));
}
@Test
void updateDetachesRenamedUsersAndGroupsByIdentity() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-mp-renamed-update-" + suffix;
String policyName = "mp-renamed-update-" + suffix;
String oldUser = "mp-user-before-" + suffix;
String newUser = "mp-user-after-" + suffix;
String oldGroup = "mp-group-before-" + suffix;
String newGroup = "mp-group-after-" + suffix;
String arn = policyArn(policyName);
iam("CreateUser", "UserName", oldUser);
iam("CreateGroup", "GroupName", oldGroup);
createStack(stackName, literalPrincipalManagedPolicyTemplate(
policyName, "s3:GetObject", oldUser, oldGroup));
assertStackStatus(stackName, "CREATE_COMPLETE");
iam("UpdateUser", "UserName", oldUser, "NewUserName", newUser);
iam("UpdateGroup", "GroupName", oldGroup, "NewGroupName", newGroup);
updateStack(stackName, literalRoleManagedPolicyTemplate(policyName, "s3:PutObject"));
assertStackStatus(stackName, "UPDATE_COMPLETE");
assertFalse(iam("ListAttachedUserPolicies", "UserName", newUser).contains(arn));
assertFalse(iam("ListAttachedGroupPolicies", "GroupName", newGroup).contains(arn));
}
@Test
void failedGroupAttachOnUpdateRestoresPriorUserAndGroupAttachments()
throws ReflectiveOperationException {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-mp-principal-rollback-" + suffix;
String policyName = "mp-principal-rollback-" + suffix;
String oldUser = "mp-old-user-" + suffix;
String newUser = "mp-new-user-" + suffix;
String oldGroup = "mp-old-group-" + suffix;
String newGroup = "mp-new-group-" + suffix;
String arn = policyArn(policyName);
for (String userName : new String[] {oldUser, newUser}) {
iam("CreateUser", "UserName", userName);
}
for (String groupName : new String[] {oldGroup, newGroup}) {
iam("CreateGroup", "GroupName", groupName);
}
createStack(stackName, literalPrincipalManagedPolicyTemplate(
policyName, "s3:GetObject", oldUser, oldGroup));
assertStackStatus(stackName, "CREATE_COMPLETE");
doThrow(new AwsException("ServiceFailure", "simulated group attach failure", 500))
.when(iamService).attachGroupPolicy(eq(newGroup), eq(arn));
updateStack(stackName, literalPrincipalManagedPolicyTemplate(
policyName, "s3:PutObject", newUser, newGroup));
assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
assertTrue(iam("ListAttachedUserPolicies", "UserName", oldUser).contains(arn));
assertTrue(iam("ListAttachedGroupPolicies", "GroupName", oldGroup).contains(arn));
assertFalse(iam("ListAttachedUserPolicies", "UserName", newUser).contains(arn));
assertFalse(iam("ListAttachedGroupPolicies", "GroupName", newGroup).contains(arn));
assertTrue(iam("GetPolicy", "PolicyArn", arn).contains("<DefaultVersionId>v1</DefaultVersionId>"));
assertEquals("v1", stackResource(stackName, "SessionPolicy")
.getAttributes().get("DefaultVersionId"));
}
@Test
void failedGroupDetachOnUpdateRestoresEarlierUserDetach() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-mp-principal-detach-" + suffix;
String policyName = "mp-principal-detach-" + suffix;
String oldUser = "mp-old-user-" + suffix;
String newUser = "mp-new-user-" + suffix;
String oldGroup = "mp-old-group-" + suffix;
String newGroup = "mp-new-group-" + suffix;
String arn = policyArn(policyName);
for (String userName : new String[] {oldUser, newUser}) {
iam("CreateUser", "UserName", userName);
}
for (String groupName : new String[] {oldGroup, newGroup}) {
iam("CreateGroup", "GroupName", groupName);
}
createStack(stackName, literalPrincipalManagedPolicyTemplate(
policyName, "s3:GetObject", oldUser, oldGroup));
assertStackStatus(stackName, "CREATE_COMPLETE");
doThrow(new AwsException("ServiceFailure", "simulated group detach failure", 500))
.when(iamService).detachGroupPolicy(eq(oldGroup), eq(arn));
updateStack(stackName, literalPrincipalManagedPolicyTemplate(
policyName, "s3:PutObject", newUser, newGroup));
assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
assertTrue(iam("ListAttachedUserPolicies", "UserName", oldUser).contains(arn));
assertTrue(iam("ListAttachedGroupPolicies", "GroupName", oldGroup).contains(arn));
assertFalse(iam("ListAttachedUserPolicies", "UserName", newUser).contains(arn));
assertFalse(iam("ListAttachedGroupPolicies", "GroupName", newGroup).contains(arn));
assertTrue(iam("GetPolicy", "PolicyArn", arn).contains("<DefaultVersionId>v1</DefaultVersionId>"));
}
@Test
void updateRefusesToAdoptAPolicyRecreatedUnderTheStackOwnedName() throws ReflectiveOperationException {
String suffix = Long.toString(System.nanoTime(), 36);
@@ -387,13 +524,35 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
""".formatted(policyName, action, roleList);
}
private static String literalPrincipalManagedPolicyTemplate(
String policyName, String action, String userName, String groupName) {
return """
{
"Resources": {
"SessionPolicy": {
"Type": "AWS::IAM::ManagedPolicy",
"Properties": {
"ManagedPolicyName": "%s",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "%s", "Resource": "*"}]
},
"Users": ["%s"],
"Groups": ["%s"]
}
}
}
}
""".formatted(policyName, action, userName, groupName);
}
@Test
void failedRoleAttachOnUpdateRestoresThePriorVersionAndDetachedRoles() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-mp-partial-" + suffix;
String policyName = "mp-partial-" + suffix;
String oldRole = "mp-partial-old-" + suffix;
String badRole = "mp-partial-missing-" + suffix;
String badRole = "mp-partial-failing-" + suffix;
// Roles are plain IAM entities outside the stack (referenced by literal name, not Ref) so
// this stack's only resource is the managed policy — isolating the assertion from the
@@ -401,12 +560,16 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
iam("CreateRole", "RoleName", oldRole, "AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}");
iam("CreateRole", "RoleName", badRole, "AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[]}");
createStack(stackName, literalRoleManagedPolicyTemplate(policyName, "s3:GetObject", oldRole));
assertStackStatus(stackName, "CREATE_COMPLETE");
// Retarget to a role that does not exist: AttachRolePolicy fails after the update path
// has already replaced the default version and detached the old (now-obsolete) role.
// The target exists at validation time; a late attach failure exercises compensation
// after the update replaced the default version and detached the old role.
doThrow(new AwsException("ServiceFailure", "simulated attach failure", 500))
.when(iamService).attachRolePolicy(eq(badRole), eq(policyArn(policyName)));
updateStack(stackName, literalRoleManagedPolicyTemplate(policyName, "s3:PutObject", badRole));
assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
@@ -482,19 +645,23 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
String stackName = "cfn-mp-restorefail-" + suffix;
String policyName = "mp-restorefail-" + suffix;
String oldRole = "mp-restorefail-old-" + suffix;
String badRole = "mp-restorefail-missing-" + suffix;
String badRole = "mp-restorefail-failing-" + suffix;
iam("CreateRole", "RoleName", oldRole, "AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}");
iam("CreateRole", "RoleName", badRole, "AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[]}");
createStack(stackName, literalRoleManagedPolicyTemplate(policyName, "s3:GetObject", oldRole));
assertStackStatus(stackName, "CREATE_COMPLETE");
// Retargeting to a role that does not exist fails the attach loop after the obsolete-role
// detach loop has already detached oldRole. The compensating reattach that restore()
// performs for oldRole is made to fail here too, so cleanup itself does not complete —
// A late attach failure occurs after the obsolete-role detach loop. The compensating
// reattach that restore() performs for oldRole is made to fail here too, so cleanup itself
// does not complete:
// the stack must report UPDATE_ROLLBACK_FAILED, not silently claim UPDATE_ROLLBACK_COMPLETE.
doThrow(new AwsException("ServiceFailure", "simulated attach failure", 500))
.when(iamService).attachRolePolicy(eq(badRole), eq(policyArn(policyName)));
doThrow(new AwsException("ServiceFailure", "simulated reattach failure", 500))
.when(iamService).attachRolePolicy(eq(oldRole), eq(policyArn(policyName)));
@@ -508,11 +675,13 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
String stackName = "cfn-mp-prunefail-" + suffix;
String policyName = "mp-prunefail-" + suffix;
String oldRole = "mp-prunefail-old-" + suffix;
String badRole = "mp-prunefail-missing-" + suffix;
String badRole = "mp-prunefail-failing-" + suffix;
iam("CreateRole", "RoleName", oldRole, "AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}");
iam("CreateRole", "RoleName", badRole, "AssumeRolePolicyDocument",
"{\"Version\":\"2012-10-17\",\"Statement\":[]}");
createStack(stackName, literalRoleManagedPolicyTemplate(policyName, "s3:GetObject", oldRole));
assertStackStatus(stackName, "CREATE_COMPLETE");
@@ -526,8 +695,9 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
assertStackStatus(stackName, "UPDATE_COMPLETE");
}
// Retargeting to a role that does not exist fails the attach loop AFTER the update path
// has already pruned v1 (to stay under the cap) and published v6 as the new default.
// The late attach failure happens AFTER pruning v1 and publishing v6.
doThrow(new AwsException("ServiceFailure", "simulated attach failure", 500))
.when(iamService).attachRolePolicy(eq(badRole), eq(policyArn(policyName)));
updateStack(stackName,
literalRoleManagedPolicyTemplate(policyName, "s3:AbortMultipartUpload", badRole));
assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
@@ -6,7 +6,9 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.iam.model.IamGroup;
import io.floci.aws.services.iam.model.IamPolicy;
import io.floci.aws.services.iam.model.IamUser;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
@@ -23,6 +25,7 @@ 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;
@@ -64,6 +67,98 @@ class IamManagedPolicyCfnProvisionerTest {
verify(iam).attachRolePolicy("web-role", ARN);
}
@Test
void missingGroupFailsBeforeCreatingThePolicy() throws Exception {
when(iam.getGroup("missing-group"))
.thenThrow(new AwsException("NoSuchEntity", "missing group", 404));
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(resource(), props("""
{"ManagedPolicyName": "app-policy",
"PolicyDocument": {"Version": "2012-10-17", "Statement": []},
"Users": ["app-user"], "Groups": ["missing-group"]}
"""), ctx(null)));
assertEquals("NoSuchEntity", failure.getErrorCode());
verify(iam, never()).createPolicy(eq("app-policy"), eq("/"), eq(null), any(), eq(Map.of()));
}
@Test
void failedAttachmentSnapshotDoesNotMutateAnExistingPolicy() throws Exception {
IamPolicy policy = mock(IamPolicy.class);
when(policy.getPolicyId()).thenReturn("AID1");
when(iam.createPolicy(eq("app-policy"), eq("/"), eq(null), any(), eq(Map.of())))
.thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409));
when(iam.getPolicy(ARN)).thenReturn(policy);
when(iam.listEntitiesForPolicy(ARN))
.thenThrow(new AwsException("ServiceFailure", "snapshot failed", 500));
StackResource r = resource();
r.setPhysicalId(ARN);
r.getAttributes().put("PolicyId", "AID1");
assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
{"ManagedPolicyName": "app-policy",
"PolicyDocument": {"Version": "2012-10-17", "Statement": []},
"Users": ["app-user"]}
"""), ctx(ARN)));
verify(iam, never()).createPolicyVersion(eq(ARN), any(), eq(true));
verify(iam, never()).detachUserPolicy("app-user", ARN);
}
@Test
void updateDetachesExplicitLegacyUserAndGroupTargets() throws Exception {
IamPolicy policy = mock(IamPolicy.class);
when(policy.getArn()).thenReturn(ARN);
when(policy.getPolicyId()).thenReturn("AID1");
when(policy.getDefaultVersionId()).thenReturn("v1");
when(iam.createPolicy(eq("app-policy"), eq("/"), eq(null), any(), eq(Map.of())))
.thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409));
when(iam.getPolicy(ARN)).thenReturn(policy);
when(iam.listEntitiesForPolicy(ARN))
.thenReturn(new IamService.PolicyEntities(List.of(), List.of(), List.of()));
when(iam.listPolicyVersions(ARN)).thenReturn(List.of());
StackResource r = resource();
r.setPhysicalId(ARN);
r.getAttributes().put("PolicyId", "AID1");
r.getAttributes().put("ManagedPolicyUserTargets", "legacy-user");
r.getAttributes().put("ManagedPolicyGroupTargets", "legacy-group");
provisioner.provision(r, props("""
{"ManagedPolicyName": "app-policy",
"PolicyDocument": {"Version": "2012-10-17", "Statement": []}}
"""), ctx(ARN));
verify(iam).detachUserPolicy("legacy-user", ARN);
verify(iam).detachGroupPolicy("legacy-group", ARN);
verify(iam, never()).listUsers("/");
verify(iam, never()).listGroups("/");
assertEquals("", r.getAttributes().get("ManagedPolicyUserTargets"));
assertEquals("", r.getAttributes().get("ManagedPolicyGroupTargets"));
}
@Test
void failedGroupAttachUndoesNewRoleAndUserAttachments() throws Exception {
IamPolicy policy = mock(IamPolicy.class);
when(policy.getArn()).thenReturn(ARN);
when(iam.createPolicy(eq("app-policy"), eq("/"), eq(null), any(), eq(Map.of()))).thenReturn(policy);
doThrow(new AwsException("ServiceFailure", "group attach failed", 500))
.when(iam).attachGroupPolicy("app-group", ARN);
assertThrows(AwsException.class, () -> provisioner.provision(resource(), props("""
{"ManagedPolicyName": "app-policy",
"PolicyDocument": {"Version": "2012-10-17", "Statement": []},
"Roles": ["app-role"], "Users": ["app-user"], "Groups": ["app-group"]}
"""), ctx(null)));
InOrder order = inOrder(iam);
order.verify(iam).attachRolePolicy("app-role", ARN);
order.verify(iam).attachUserPolicy("app-user", ARN);
order.verify(iam).attachGroupPolicy("app-group", ARN);
order.verify(iam).detachUserPolicy("app-user", ARN);
order.verify(iam).detachRolePolicy("app-role", ARN);
order.verify(iam).deletePolicy(ARN);
}
@Test
void deleteDetachesRolesThenRemovesThePolicy() {
StackResource r = resource();
@@ -77,6 +172,92 @@ class IamManagedPolicyCfnProvisionerTest {
order.verify(iam).deletePolicy(ARN);
}
@Test
void deleteDetachesEveryStoredPrincipalBeforeRemovingThePolicy() {
StackResource r = resource();
r.setPhysicalId(ARN);
r.getAttributes().put("ManagedPolicyRoleTargets", "app-role");
r.getAttributes().put("ManagedPolicyUserTargets", "app-user");
r.getAttributes().put("ManagedPolicyGroupTargets", "app-group");
r.getAttributes().put("ManagedPolicyUserTargetIds", "AIDAUSER");
r.getAttributes().put("ManagedPolicyGroupTargetIds", "AGROUP");
IamUser user = mock(IamUser.class);
when(user.getUserId()).thenReturn("AIDAUSER");
when(user.getUserName()).thenReturn("app-user");
when(iam.listUsers("/")).thenReturn(List.of(user));
IamGroup group = mock(IamGroup.class);
when(group.getGroupId()).thenReturn("AGROUP");
when(group.getGroupName()).thenReturn("app-group");
when(iam.listGroups("/")).thenReturn(List.of(group));
provisioner.delete(r, "us-east-1");
InOrder order = inOrder(iam);
order.verify(iam).detachRolePolicy("app-role", ARN);
order.verify(iam).detachUserPolicy("app-user", ARN);
order.verify(iam).detachGroupPolicy("app-group", ARN);
order.verify(iam).deletePolicy(ARN);
}
@Test
void deleteUsesExplicitLegacyUserAndGroupTargetsWithoutScanning() {
StackResource r = resource();
r.setPhysicalId(ARN);
r.getAttributes().put("ManagedPolicyUserTargets", "legacy-user");
r.getAttributes().put("ManagedPolicyGroupTargets", "legacy-group");
provisioner.delete(r, "us-east-1");
verify(iam).detachUserPolicy("legacy-user", ARN);
verify(iam).detachGroupPolicy("legacy-group", ARN);
verify(iam, never()).listUsers("/");
verify(iam, never()).listGroups("/");
verify(iam).deletePolicy(ARN);
}
@Test
void legacyPolicyDeletePreservesUnrecordedUserAndGroupAttachments() {
StackResource r = resource();
r.setPhysicalId(ARN);
when(iam.listRoles("/")).thenReturn(List.of());
IamUser outsideUser = mock(IamUser.class);
when(outsideUser.getAttachedPolicyArns()).thenReturn(new ArrayList<>(List.of(ARN)));
when(outsideUser.getUserName()).thenReturn("outside-user");
when(iam.listUsers("/")).thenReturn(List.of(outsideUser));
IamGroup outsideGroup = mock(IamGroup.class);
when(outsideGroup.getAttachedPolicyArns()).thenReturn(new ArrayList<>(List.of(ARN)));
when(outsideGroup.getGroupName()).thenReturn("outside-group");
when(iam.listGroups("/")).thenReturn(List.of(outsideGroup));
doThrow(new AwsException("DeleteConflict", "policy still attached", 409))
.when(iam).deletePolicy(ARN);
AwsException failure = assertThrows(AwsException.class, () -> provisioner.delete(r, "us-east-1"));
assertEquals("DeleteConflict", failure.getErrorCode());
verify(iam, never()).detachUserPolicy("outside-user", ARN);
verify(iam, never()).detachGroupPolicy("outside-group", ARN);
verify(iam, never()).listUsers("/");
verify(iam, never()).listGroups("/");
}
@Test
void emptyRecordedPrincipalTargetsDoNotScanOrDetach() {
StackResource r = resource();
r.setPhysicalId(ARN);
r.getAttributes().put("ManagedPolicyUserTargets", "\n");
r.getAttributes().put("ManagedPolicyGroupTargets", "\n");
r.getAttributes().put("ManagedPolicyUserTargetIds", "AIDAUSER");
r.getAttributes().put("ManagedPolicyGroupTargetIds", "AGROUP");
provisioner.delete(r, "us-east-1");
verify(iam, never()).listUsers("/");
verify(iam, never()).listGroups("/");
verify(iam, never()).detachUserPolicy(any(), eq(ARN));
verify(iam, never()).detachGroupPolicy(any(), eq(ARN));
verify(iam).deletePolicy(ARN);
}
@Test
void deleteToleratesAnAlreadyDetachedRole() {
StackResource r = resource();