Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(cloudformation): honour PermissionsBoundary on AWS::IAM::Role and AWS::IAM::User (#5266)

Allen Sanborn7d71df6ac9c0
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java
index f29b9d1a5e..a79003fa48 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java
@@ -18,6 +18,7 @@ import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
/**
@@ -70,6 +71,8 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner {
}
String description = ctx.resolveOptional(props, "Description");
List<String> managedPolicyArns = ctx.resolveStringList(props, "ManagedPolicyArns");
+ // Blank means absent: Fn::If with Ref AWS::NoValue resolves to "" (CDK bootstrap does this).
+ String permissionsBoundary = ctx.resolveOrDefault(props, "PermissionsBoundary", null);
IamRole role;
boolean createdRole = false;
@@ -80,8 +83,11 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner {
// replacement that took the name in the meantime.
String priorAssumeRolePolicyDocument = null;
String priorAssumeRoleId = null;
+ // The adopted role's boundary before this attempt, restored on failure like the trust policy.
+ String priorPermissionsBoundary = null;
try {
- role = iamService.createRole(resolvedRoleName, path, assumeDoc, description, 3600, Map.of());
+ role = iamService.createRole(resolvedRoleName, path, assumeDoc, description, 3600, Map.of(),
+ permissionsBoundary);
createdRole = true;
r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
} catch (AwsException e) {
@@ -114,6 +120,7 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner {
// meant for the role this stack actually owns.
priorAssumeRolePolicyDocument = role.getAssumeRolePolicyDocument();
priorAssumeRoleId = existingRoleId;
+ priorPermissionsBoundary = role.getPermissionsBoundaryArn();
iamService.updateAssumeRolePolicy(resolvedRoleName, assumeDoc, existingRoleId);
}
@@ -138,7 +145,21 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner {
LinkedHashSet<String> inlineWrittenByThisAttempt = new LinkedHashSet<>();
final String documentToRestore = priorAssumeRolePolicyDocument;
final String roleIdToRestore = priorAssumeRoleId;
+ final String boundaryToRestore = priorPermissionsBoundary;
+ boolean boundaryChangedByThisAttempt = false;
try {
+ // createRole() only applies PermissionsBoundary on first create. On adoption, set a
+ // changed boundary, and remove one only if the role has one and the template dropped it.
+ // ID-verified like the trust-policy write, here and in the rollback restore.
+ if (!createdRole && !Objects.equals(permissionsBoundary, boundaryToRestore)) {
+ if (permissionsBoundary != null) {
+ iamService.putRolePermissionsBoundary(resolvedRoleName, permissionsBoundary, roleIdToRestore);
+ } else {
+ iamService.deleteRolePermissionsBoundary(resolvedRoleName, roleIdToRestore);
+ }
+ boundaryChangedByThisAttempt = true;
+ }
+
for (String policyArn : managedPolicyArns) {
iamService.attachRolePolicy(resolvedRoleName, policyArn);
if (!originalPolicyArns.contains(policyArn)) {
@@ -239,6 +260,18 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner {
cleanupSucceeded = false;
}
}
+ if (boundaryChangedByThisAttempt) {
+ if (!CfnRollback.attemptIamCleanup(failure,
+ "restore prior permissions boundary on role " + resolvedRoleName, () -> {
+ if (boundaryToRestore == null) {
+ iamService.deleteRolePermissionsBoundary(resolvedRoleName, roleIdToRestore);
+ } else {
+ iamService.putRolePermissionsBoundary(resolvedRoleName, boundaryToRestore, roleIdToRestore);
+ }
+ })) {
+ cleanupSucceeded = false;
+ }
+ }
if (documentToRestore != null) {
// ID-verified, same as the primary write above: if the role was deleted and
// recreated under this name in between, this must not write the restored document
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamUserCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamUserCfnProvisioner.java
index bac757d20c..880ba3a1ed 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamUserCfnProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamUserCfnProvisioner.java
@@ -18,6 +18,7 @@ import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
/**
@@ -65,13 +66,16 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
List<String> managedPolicyArns = ctx.resolveStringList(props, "ManagedPolicyArns");
List<String> groups = ctx.resolveStringList(props, "Groups");
Map<String, String> tags = ctx.resolveTags(props, "Tags");
+ // Blank means absent: Fn::If with Ref AWS::NoValue resolves to "" (CDK bootstrap does this).
+ String permissionsBoundary = ctx.resolveOrDefault(props, "PermissionsBoundary", null);
IamUser user;
boolean createdUser = false;
String priorPath = null;
String priorUserId = null;
+ String priorPermissionsBoundary = null;
try {
- user = iamService.createUser(resolvedUserName, resolvedPath);
+ user = iamService.createUser(resolvedUserName, resolvedPath, permissionsBoundary);
createdUser = true;
r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
} catch (AwsException e) {
@@ -87,6 +91,7 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
}
priorPath = user.getPath();
priorUserId = existingUserId;
+ priorPermissionsBoundary = user.getPermissionsBoundaryArn();
if (!resolvedPath.equals(user.getPath())) {
iamService.updateUser(resolvedUserName, null, resolvedPath, existingUserId);
user = iamService.getUser(resolvedUserName);
@@ -130,8 +135,22 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
final String pathToRestore = priorPath;
final String userIdToRestore = priorUserId;
+ final String boundaryToRestore = priorPermissionsBoundary;
+ boolean boundaryChangedByThisAttempt = false;
try {
+ // createUser() only applies PermissionsBoundary on first create. On adoption, set a
+ // changed boundary, and remove one only if the user has one and the template dropped it.
+ // ID-verified like the path write, here and in the rollback restore.
+ if (!createdUser && !Objects.equals(permissionsBoundary, boundaryToRestore)) {
+ if (permissionsBoundary != null) {
+ iamService.putUserPermissionsBoundary(resolvedUserName, permissionsBoundary, userIdToRestore);
+ } else {
+ iamService.deleteUserPermissionsBoundary(resolvedUserName, userIdToRestore);
+ }
+ boundaryChangedByThisAttempt = true;
+ }
+
for (String groupName : groups) {
iamService.addUserToGroup(groupName, resolvedUserName);
if (!originalGroups.contains(groupName)) {
@@ -277,6 +296,19 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
}
}
+ if (boundaryChangedByThisAttempt) {
+ if (!CfnRollback.attemptIamCleanup(failure,
+ "restore prior permissions boundary on user " + resolvedUserName, () -> {
+ if (boundaryToRestore == null) {
+ iamService.deleteUserPermissionsBoundary(resolvedUserName, userIdToRestore);
+ } else {
+ iamService.putUserPermissionsBoundary(resolvedUserName, boundaryToRestore, userIdToRestore);
+ }
+ })) {
+ cleanupSucceeded = false;
+ }
+ }
+
if (pathToRestore != null) {
if (!CfnRollback.attemptIamCleanup(failure, "restore prior path on user " + resolvedUserName,
() -> iamService.updateUser(resolvedUserName, null, pathToRestore, userIdToRestore))) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
index 6dce9f1ace..03ab399579 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
@@ -784,11 +784,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public void updateUser(String userName, String newUserName, String newPath, String expectedUserId) {
synchronized (resourceNameLock) {
IamUser user = getUser(userName);
- if (expectedUserId != null && !expectedUserId.equals(user.getUserId())) {
- throw new AwsException("EntityAlreadyExists",
- "User " + userName + " was replaced by a different user of the same name; "
- + "refusing to apply an update meant for the original user.", 409);
- }
+ requireSameUser(user, userName, expectedUserId);
if (newUserName != null && !newUserName.equals(userName)) {
boolean nameTaken = resourcesInCurrentAccount(users)
.filter(existing -> !existing.getUserId().equals(user.getUserId()))
@@ -1288,14 +1284,12 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
*/
public void updateAssumeRolePolicy(String roleName, String policyDocument, String expectedRoleId) {
validateRoleName(roleName);
- IamRole role = getRole(roleName);
- if (expectedRoleId != null && !expectedRoleId.equals(role.getRoleId())) {
- throw new AwsException("EntityAlreadyExists",
- "Role " + roleName + " was replaced by a different role of the same name; "
- + "refusing to apply an update meant for the original role.", 409);
+ synchronized (resourceNameLock) {
+ IamRole role = getRole(roleName);
+ requireSameRole(role, roleName, expectedRoleId);
+ role.setAssumeRolePolicyDocument(policyDocument);
+ roles.put(roleName, role);
}
- role.setAssumeRolePolicyDocument(policyDocument);
- roles.put(roleName, role);
}
public void tagRole(String roleName, Map<String, String> newTags) {
@@ -4869,47 +4863,103 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
// =========================================================================
public void putUserPermissionsBoundary(String userName, String permissionsBoundaryArn) {
+ putUserPermissionsBoundary(userName, permissionsBoundaryArn, null);
+ }
+
+ /**
+ * Same as {@link #putUserPermissionsBoundary(String, String)}, but refuses the write if the user
+ * named here is no longer the one with {@code expectedUserId}, like
+ * {@link #updateUser(String, String, String, String)}. A null ID skips the check.
+ */
+ public void putUserPermissionsBoundary(String userName, String permissionsBoundaryArn, String expectedUserId) {
requirePolicy(permissionsBoundaryArn); // validate policy exists
- IamUser user = getUser(userName);
- user.setPermissionsBoundaryArn(permissionsBoundaryArn);
- users.put(userName, user);
+ synchronized (resourceNameLock) {
+ IamUser user = getUser(userName);
+ requireSameUser(user, userName, expectedUserId);
+ user.setPermissionsBoundaryArn(permissionsBoundaryArn);
+ users.put(userName, user);
+ }
LOG.infov("Set permissions boundary for user {0}: {1}", userName, permissionsBoundaryArn);
}
public void deleteUserPermissionsBoundary(String userName) {
- IamUser user = getUser(userName);
- if (user.getPermissionsBoundaryArn() == null) {
- throw new AwsException("NoSuchEntity",
- "User " + userName + " does not have a permissions boundary.", 404);
+ deleteUserPermissionsBoundary(userName, null);
+ }
+
+ /** ID-verified like {@link #putUserPermissionsBoundary(String, String, String)}. */
+ public void deleteUserPermissionsBoundary(String userName, String expectedUserId) {
+ synchronized (resourceNameLock) {
+ IamUser user = getUser(userName);
+ requireSameUser(user, userName, expectedUserId);
+ if (user.getPermissionsBoundaryArn() == null) {
+ throw new AwsException("NoSuchEntity",
+ "User " + userName + " does not have a permissions boundary.", 404);
+ }
+ user.setPermissionsBoundaryArn(null);
+ users.put(userName, user);
}
- user.setPermissionsBoundaryArn(null);
- users.put(userName, user);
LOG.infov("Deleted permissions boundary for user: {0}", userName);
}
public void putRolePermissionsBoundary(String roleName, String permissionsBoundaryArn) {
+ putRolePermissionsBoundary(roleName, permissionsBoundaryArn, null);
+ }
+
+ /**
+ * Same as {@link #putRolePermissionsBoundary(String, String)}, but refuses the write if the role
+ * named here is no longer the one with {@code expectedRoleId}, like
+ * {@link #updateAssumeRolePolicy(String, String, String)}. A null ID skips the check.
+ */
+ public void putRolePermissionsBoundary(String roleName, String permissionsBoundaryArn, String expectedRoleId) {
validateRoleName(roleName);
- IamRole role = getRole(roleName);
- requireNotServiceLinked(role, roleName);
- requirePolicy(permissionsBoundaryArn); // validate policy exists
- role.setPermissionsBoundaryArn(permissionsBoundaryArn);
- roles.put(roleName, role);
+ synchronized (resourceNameLock) {
+ IamRole role = getRole(roleName);
+ requireSameRole(role, roleName, expectedRoleId);
+ requireNotServiceLinked(role, roleName);
+ requirePolicy(permissionsBoundaryArn); // validate policy exists
+ role.setPermissionsBoundaryArn(permissionsBoundaryArn);
+ roles.put(roleName, role);
+ }
LOG.infov("Set permissions boundary for role {0}: {1}", roleName, permissionsBoundaryArn);
}
public void deleteRolePermissionsBoundary(String roleName) {
+ deleteRolePermissionsBoundary(roleName, null);
+ }
+
+ /** ID-verified like {@link #putRolePermissionsBoundary(String, String, String)}. */
+ public void deleteRolePermissionsBoundary(String roleName, String expectedRoleId) {
validateRoleName(roleName);
- IamRole role = getRole(roleName);
- requireNotServiceLinked(role, roleName);
- if (role.getPermissionsBoundaryArn() == null) {
- throw new AwsException("NoSuchEntity",
- "Role " + roleName + " does not have a permissions boundary.", 404);
+ synchronized (resourceNameLock) {
+ IamRole role = getRole(roleName);
+ requireSameRole(role, roleName, expectedRoleId);
+ requireNotServiceLinked(role, roleName);
+ if (role.getPermissionsBoundaryArn() == null) {
+ throw new AwsException("NoSuchEntity",
+ "Role " + roleName + " does not have a permissions boundary.", 404);
+ }
+ role.setPermissionsBoundaryArn(null);
+ roles.put(roleName, role);
}
- role.setPermissionsBoundaryArn(null);
- roles.put(roleName, role);
LOG.infov("Deleted permissions boundary for role: {0}", roleName);
}
+ private static void requireSameUser(IamUser user, String userName, String expectedUserId) {
+ if (expectedUserId != null && !expectedUserId.equals(user.getUserId())) {
+ throw new AwsException("EntityAlreadyExists",
+ "User " + userName + " was replaced by a different user of the same name; "
+ + "refusing to apply an update meant for the original user.", 409);
+ }
+ }
+
+ private static void requireSameRole(IamRole role, String roleName, String expectedRoleId) {
+ if (expectedRoleId != null && !expectedRoleId.equals(role.getRoleId())) {
+ throw new AwsException("EntityAlreadyExists",
+ "Role " + roleName + " was replaced by a different role of the same name; "
+ + "refusing to apply an update meant for the original role.", 409);
+ }
+ }
+
/**
* Resolves a user for policy collection. Given an ARN, the lookup is scoped to the account the
* ARN itself names: two accounts can hold a same-named user, and evaluating account A's ARN
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java
index a1268e2f3e..6eaff53b81 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java
@@ -60,7 +60,7 @@ class CloudFormationIamAttachmentProvisionerTest {
@Test
void newRoleAttachmentFailureDetachesPolicyThenDeletesRole() {
IamRole role = role("new-role");
- when(iamService.createRole("new-role", "/", emptyTrustPolicy(), null, 3600, Map.of()))
+ when(iamService.createRole("new-role", "/", emptyTrustPolicy(), null, 3600, Map.of(), null))
.thenReturn(role);
doThrow(new AwsException("NoSuchEntity", "missing policy", 404))
.when(iamService).attachRolePolicy("new-role", MISSING_POLICY);
@@ -78,7 +78,7 @@ class CloudFormationIamAttachmentProvisionerTest {
void sameStackRoleRetryPreservesOriginalPoliciesAndRole() {
IamRole role = role("existing-role");
role.getAttachedPolicyArns().add(EXISTING_POLICY);
- when(iamService.createRole("existing-role", "/", emptyTrustPolicy(), null, 3600, Map.of()))
+ when(iamService.createRole("existing-role", "/", emptyTrustPolicy(), null, 3600, Map.of(), null))
.thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409));
when(iamService.getRole("existing-role")).thenReturn(role);
doThrow(new AwsException("NoSuchEntity", "missing policy", 404))
@@ -103,7 +103,7 @@ class CloudFormationIamAttachmentProvisionerTest {
String newTrustPolicyJson =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}";
- when(iamService.createRole(eq("existing-role"), eq("/"), anyString(), eq(null), eq(3600), eq(Map.of())))
+ when(iamService.createRole(eq("existing-role"), eq("/"), anyString(), eq(null), eq(3600), eq(Map.of()), eq(null)))
.thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409));
when(iamService.getRole("existing-role")).thenReturn(role);
@@ -128,7 +128,7 @@ class CloudFormationIamAttachmentProvisionerTest {
String newTrustPolicyJson =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}";
- when(iamService.createRole(eq("existing-role"), eq("/"), anyString(), eq(null), eq(3600), eq(Map.of())))
+ when(iamService.createRole(eq("existing-role"), eq("/"), anyString(), eq(null), eq(3600), eq(Map.of()), eq(null)))
.thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409));
when(iamService.getRole("existing-role")).thenReturn(role);
doThrow(new AwsException("NoSuchEntity", "missing policy", 404))
@@ -155,7 +155,7 @@ class CloudFormationIamAttachmentProvisionerTest {
@Test
void freshRoleCreationDoesNotRedundantlyUpdateTrustPolicy() {
IamRole role = role("new-role");
- when(iamService.createRole("new-role", "/", emptyTrustPolicy(), null, 3600, Map.of()))
+ when(iamService.createRole("new-role", "/", emptyTrustPolicy(), null, 3600, Map.of(), null))
.thenReturn(role);
provisionRole("new-role", List.of());
@@ -166,7 +166,7 @@ class CloudFormationIamAttachmentProvisionerTest {
@Test
void freshRoleCollisionDoesNotAdoptUserOwnedRole() {
- when(iamService.createRole("external-role", "/", emptyTrustPolicy(), null, 3600, Map.of()))
+ when(iamService.createRole("external-role", "/", emptyTrustPolicy(), null, 3600, Map.of(), null))
.thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409));
StackResource result = provisionRole("external-role", List.of(NEW_POLICY));
@@ -181,7 +181,7 @@ class CloudFormationIamAttachmentProvisionerTest {
@Test
void generatedRoleNameRemainsStableOnUpdate() {
IamRole role = role("generated-role");
- when(iamService.createRole("generated-role", "/", emptyTrustPolicy(), null, 3600, Map.of()))
+ when(iamService.createRole("generated-role", "/", emptyTrustPolicy(), null, 3600, Map.of(), null))
.thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409));
when(iamService.getRole("generated-role")).thenReturn(role);
@@ -196,7 +196,7 @@ class CloudFormationIamAttachmentProvisionerTest {
@Test
void sameNameRoleWithDifferentIdIsNotAdopted() {
IamRole replacement = role("same-name");
- when(iamService.createRole("same-name", "/", emptyTrustPolicy(), null, 3600, Map.of()))
+ when(iamService.createRole("same-name", "/", emptyTrustPolicy(), null, 3600, Map.of(), null))
.thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409));
when(iamService.getRole("same-name")).thenReturn(replacement);
@@ -223,12 +223,12 @@ class CloudFormationIamAttachmentProvisionerTest {
assertEquals("Updating RoleName requires resource replacement, which is not supported.",
result.getStatusReason());
verify(iamService, never()).createRole(
- "new-role", "/", emptyTrustPolicy(), null, 3600, Map.of());
+ "new-role", "/", emptyTrustPolicy(), null, 3600, Map.of(), null);
}
@Test
void unexpectedRoleCreationFailureIsNotTreatedAsAnExistingRole() {
- when(iamService.createRole("denied-role", "/", emptyTrustPolicy(), null, 3600, Map.of()))
+ when(iamService.createRole("denied-role", "/", emptyTrustPolicy(), null, 3600, Map.of(), null))
.thenThrow(new AwsException("AccessDenied", "denied", 403));
StackResource result = provisionRole("denied-role", List.of());
@@ -288,7 +288,7 @@ class CloudFormationIamAttachmentProvisionerTest {
@Test
void cleanupFailureDoesNotMaskPrimaryFailureOrSkipDeletion() {
IamRole role = role("cleanup-role");
- when(iamService.createRole("cleanup-role", "/", emptyTrustPolicy(), null, 3600, Map.of()))
+ when(iamService.createRole("cleanup-role", "/", emptyTrustPolicy(), null, 3600, Map.of(), null))
.thenReturn(role);
doThrow(new AwsException("NoSuchEntity", "primary failure", 404))
.when(iamService).attachRolePolicy("cleanup-role", MISSING_POLICY);
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamUserIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamUserIntegrationTest.java
index fcbb68eac2..dce09ed9a0 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamUserIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamUserIntegrationTest.java
@@ -9,6 +9,7 @@ import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
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.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -324,7 +325,7 @@ class CloudFormationIamUserIntegrationTest {
.formParam("UserName", userName)
.when().post("/").then().statusCode(200).extract().asString();
assertThat(attachedPolicies, containsString("ReadOnlyAccess"));
- assertThat(attachedPolicies, org.hamcrest.Matchers.not(containsString("PowerUserAccess")));
+ assertThat(attachedPolicies, not(containsString("PowerUserAccess")));
// Verify drop-policy was deleted
String inlinePolicies = given()
@@ -334,7 +335,7 @@ class CloudFormationIamUserIntegrationTest {
.formParam("UserName", userName)
.when().post("/").then().statusCode(200).extract().asString();
assertThat(inlinePolicies, containsString("<member>keep-policy</member>"));
- assertThat(inlinePolicies, org.hamcrest.Matchers.not(containsString("<member>drop-policy</member>")));
+ assertThat(inlinePolicies, not(containsString("<member>drop-policy</member>")));
// Verify group-b was removed
String userGroups = given()
@@ -344,7 +345,7 @@ class CloudFormationIamUserIntegrationTest {
.formParam("UserName", userName)
.when().post("/").then().statusCode(200).extract().asString();
assertThat(userGroups, containsString("group-a-" + suffix));
- assertThat(userGroups, org.hamcrest.Matchers.not(containsString("group-b-" + suffix)));
+ assertThat(userGroups, not(containsString("group-b-" + suffix)));
deleteStack(stackName);
awaitStackStatus(stackId, "DELETE_COMPLETE");
@@ -407,7 +408,65 @@ class CloudFormationIamUserIntegrationTest {
assertThat(updatedTags, containsString("<Value>production</Value>"));
assertThat(updatedTags, containsString("<Key>Team</Key>"));
assertThat(updatedTags, containsString("<Value>identity</Value>"));
- assertThat(updatedTags, org.hamcrest.Matchers.not(containsString("<Key>Owner</Key>")));
+ assertThat(updatedTags, not(containsString("<Key>Owner</Key>")));
+
+ deleteStack(stackName);
+ awaitStackStatus(stackId, "DELETE_COMPLETE");
+ }
+
+ /**
+ * The CDK bootstrap template's shape: PermissionsBoundary is an Fn::If whose false branch is
+ * Ref AWS::NoValue. That must create the role and user with no boundary, not fail looking up a
+ * policy named "".
+ */
+ @Test
+ void noValuePermissionsBoundaryCreatesRoleAndUserWithoutOne() throws InterruptedException {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String roleName = "novalue-role-" + suffix;
+ String userName = "novalue-user-" + suffix;
+ String stackName = "cfn-novalue-boundary-" + suffix;
+ String boundary = """
+ {"Fn::If": ["HasBoundary",
+ {"Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/${InputPermissionsBoundary}"},
+ {"Ref": "AWS::NoValue"}]}""";
+ String template = """
+ {
+ "Parameters": {"InputPermissionsBoundary": {"Type": "String", "Default": ""}},
+ "Conditions": {"HasBoundary": {"Fn::Not": [{"Fn::Equals": ["", {"Ref": "InputPermissionsBoundary"}]}]}},
+ "Resources": {
+ "ExecRole": {
+ "Type": "AWS::IAM::Role",
+ "Properties": {
+ "RoleName": "%s",
+ "AssumeRolePolicyDocument": {"Version": "2012-10-17", "Statement": []},
+ "PermissionsBoundary": %s
+ }
+ },
+ "ExecUser": {
+ "Type": "AWS::IAM::User",
+ "Properties": {"UserName": "%s", "PermissionsBoundary": %s}
+ }
+ }
+ }
+ """.formatted(roleName, boundary, userName, boundary);
+
+ String stackId = createStack(stackName, template);
+ awaitStackStatus(stackId, "CREATE_COMPLETE");
+
+ for (String[] read : new String[][] {{"GetRole", "RoleName", roleName}, {"GetUser", "UserName", userName}}) {
+ String body = given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", IAM_AUTH)
+ .formParam("Action", read[0])
+ .formParam(read[1], read[2])
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().asString();
+ assertThat(body, containsString(read[2]));
+ assertThat(body, not(containsString("PermissionsBoundary")));
+ }
deleteStack(stackName);
awaitStackStatus(stackId, "DELETE_COMPLETE");
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java
index 708d711ca2..310d6643c5 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java
@@ -23,6 +23,7 @@ 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.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
@@ -90,7 +91,7 @@ class IamRoleCfnProvisionerTest {
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())))
+ when(iam.createRole(eq(roleName), eq("/"), anyString(), any(), eq(3600), eq(Map.of()), any()))
.thenReturn(role);
return role;
}
@@ -216,7 +217,7 @@ class IamRoleCfnProvisionerTest {
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())))
+ when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), eq(Map.of()), any()))
.thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
when(iam.getRole("app-role")).thenReturn(existing);
@@ -251,7 +252,7 @@ class IamRoleCfnProvisionerTest {
// 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())))
+ when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), eq(Map.of()), any()))
.thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
when(iam.getRole("app-role")).thenReturn(existing);
@@ -277,7 +278,7 @@ class IamRoleCfnProvisionerTest {
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())))
+ when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), eq(Map.of()), any()))
.thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
when(iam.getRole("app-role")).thenReturn(existing);
@@ -322,7 +323,7 @@ class IamRoleCfnProvisionerTest {
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())))
+ when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), eq(Map.of()), any()))
.thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
when(iam.getRole("app-role")).thenReturn(existing);
doThrow(new AwsException("MalformedPolicyDocument", "bad policy", 400))
@@ -349,6 +350,130 @@ class IamRoleCfnProvisionerTest {
verify(iam, never()).deleteRole(anyString());
}
+ private static final String BOUNDARY_OLD = "arn:aws:iam::" + ACCOUNT_ID + ":policy/boundary-old";
+ private static final String BOUNDARY_NEW = "arn:aws:iam::" + ACCOUNT_ID + ":policy/boundary-new";
+
+ /** A role this stack already owns, so provision() takes the adoption (update) path. */
+ private StackResource adoptExistingRole(String currentBoundary) {
+ IamRole existing = new IamRole("AROAapp-role", "app-role", "/",
+ "arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST);
+ existing.setPermissionsBoundaryArn(currentBoundary);
+ when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), eq(Map.of()), any()))
+ .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");
+ return r;
+ }
+
+ @Test
+ void createPassesThePermissionsBoundaryToTheRole() {
+ StackResource r = resource();
+ when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), eq(Map.of()),
+ eq(BOUNDARY_NEW))).thenReturn(new IamRole("AROAapp-role", "app-role", "/",
+ "arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST));
+
+ provisioner.provision(r, props("""
+ {"RoleName": "app-role", "PermissionsBoundary": "%s"}
+ """.formatted(BOUNDARY_NEW)), ctx());
+
+ assertEquals("arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", r.getAttributes().get("Arn"));
+ }
+
+ @Test
+ void updateAppliesAChangedPermissionsBoundary() {
+ StackResource r = adoptExistingRole(BOUNDARY_OLD);
+
+ provisioner.provision(r, props("""
+ {"RoleName": "app-role", "PermissionsBoundary": "%s"}
+ """.formatted(BOUNDARY_NEW)), ctx());
+
+ verify(iam).putRolePermissionsBoundary("app-role", BOUNDARY_NEW, "AROAapp-role");
+ verify(iam, never()).deleteRolePermissionsBoundary(anyString(), any());
+ }
+
+ @Test
+ void updateRemovesAPermissionsBoundaryTheTemplateDropped() {
+ StackResource r = adoptExistingRole(BOUNDARY_OLD);
+
+ provisioner.provision(r, props("""
+ {"RoleName": "app-role"}
+ """), ctx());
+
+ verify(iam).deleteRolePermissionsBoundary("app-role", "AROAapp-role");
+ }
+
+ @Test
+ void updateLeavesAnUnchangedOrAbsentPermissionsBoundaryAlone() {
+ // deleteRolePermissionsBoundary raises NoSuchEntity on a role without one.
+ StackResource r = adoptExistingRole(null);
+
+ provisioner.provision(r, props("""
+ {"RoleName": "app-role"}
+ """), ctx());
+
+ verify(iam, never()).deleteRolePermissionsBoundary(anyString(), any());
+ verify(iam, never()).putRolePermissionsBoundary(anyString(), anyString(), any());
+ }
+
+ // {"Fn::If": [cond, arn, {"Ref": "AWS::NoValue"}]} resolves to "" (CDK bootstrap's
+ // CloudFormationExecutionRole), which must mean "no boundary", not a policy named "".
+ @Test
+ void createTreatsABlankPermissionsBoundaryAsAbsent() {
+ stubCreate("app-role");
+
+ provisioner.provision(resource(), props("""
+ {"RoleName": "app-role", "PermissionsBoundary": ""}
+ """), ctx());
+
+ verify(iam).createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), eq(Map.of()), isNull());
+ }
+
+ @Test
+ void updateTreatsABlankPermissionsBoundaryAsDropped() {
+ StackResource r = adoptExistingRole(BOUNDARY_OLD);
+
+ provisioner.provision(r, props("""
+ {"RoleName": "app-role", "PermissionsBoundary": ""}
+ """), ctx());
+
+ verify(iam).deleteRolePermissionsBoundary("app-role", "AROAapp-role");
+ verify(iam, never()).putRolePermissionsBoundary(anyString(), anyString(), any());
+ }
+
+ @Test
+ void failedUpdateRestoresThePriorPermissionsBoundary() {
+ StackResource r = adoptExistingRole(BOUNDARY_OLD);
+ doThrow(new AwsException("NoSuchEntity", "missing policy", 404))
+ .when(iam).attachRolePolicy("app-role", "arn:aws:iam::aws:policy/Missing");
+
+ assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
+ {"RoleName": "app-role", "PermissionsBoundary": "%s",
+ "ManagedPolicyArns": ["arn:aws:iam::aws:policy/Missing"]}
+ """.formatted(BOUNDARY_NEW)), ctx()));
+
+ InOrder order = inOrder(iam);
+ order.verify(iam).putRolePermissionsBoundary("app-role", BOUNDARY_NEW, "AROAapp-role");
+ order.verify(iam).putRolePermissionsBoundary("app-role", BOUNDARY_OLD, "AROAapp-role");
+ verify(iam, never()).deleteRole(anyString());
+ }
+
+ @Test
+ void failedUpdateRemovesTheBoundaryItAddedOnlyFromTheAdoptedRole() {
+ StackResource r = adoptExistingRole(null);
+ doThrow(new AwsException("NoSuchEntity", "missing policy", 404))
+ .when(iam).attachRolePolicy("app-role", "arn:aws:iam::aws:policy/Missing");
+
+ assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
+ {"RoleName": "app-role", "PermissionsBoundary": "%s",
+ "ManagedPolicyArns": ["arn:aws:iam::aws:policy/Missing"]}
+ """.formatted(BOUNDARY_NEW)), ctx()));
+
+ // The ID makes IamService refuse the delete if the name now belongs to a replacement role.
+ verify(iam).deleteRolePermissionsBoundary("app-role", "AROAapp-role");
+ }
+
@Test
void inlinePolicyFailureFailsTheResourceInsteadOfDroppingThePolicy() {
stubCreate("app-role");
@@ -469,7 +594,8 @@ void assumeRolePolicyIntrinsicsAreResolved() {
docCaptor.capture(),
any(),
eq(3600),
- eq(Map.of())
+ eq(Map.of()),
+ any()
);
String storedDoc = docCaptor.getValue();
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamUserCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamUserCfnProvisionerTest.java
index 1472ee123e..67c8546fe8 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamUserCfnProvisionerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamUserCfnProvisionerTest.java
@@ -21,6 +21,7 @@ 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.eq;
+import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
@@ -82,7 +83,7 @@ class IamUserCfnProvisionerTest {
private IamUser stubCreate(String userName, String path) {
IamUser user = new IamUser("AIDA" + userName, userName, path,
"arn:aws:iam::" + ACCOUNT_ID + ":user" + path + userName);
- when(iam.createUser(eq(userName), eq(path))).thenReturn(user);
+ when(iam.createUser(eq(userName), eq(path), any())).thenReturn(user);
return user;
}
@@ -104,7 +105,7 @@ class IamUserCfnProvisionerTest {
assertEquals("custom-user", r.getPhysicalId());
assertEquals("arn:aws:iam::" + ACCOUNT_ID + ":user/custom-user", r.getAttributes().get("Arn"));
- verify(iam).createUser("custom-user", "/");
+ verify(iam).createUser("custom-user", "/", null);
}
@Test
@@ -121,12 +122,12 @@ class IamUserCfnProvisionerTest {
assertEquals("custom-user", r.getPhysicalId());
assertEquals("arn:aws:iam::" + ACCOUNT_ID + ":user/engineering/custom-user", r.getAttributes().get("Arn"));
- verify(iam).createUser("custom-user", "/engineering/");
+ verify(iam).createUser("custom-user", "/engineering/", null);
}
@Test
void provisionGeneratesPhysicalNameWhenUserNameIsOmitted() {
- when(iam.createUser(any(), eq("/"))).thenAnswer(inv -> {
+ when(iam.createUser(any(), eq("/"), any())).thenAnswer(inv -> {
String name = inv.getArgument(0);
return new IamUser("AIDA" + name, name, "/", "arn:aws:iam::" + ACCOUNT_ID + ":user/" + name);
});
@@ -187,7 +188,7 @@ class IamUserCfnProvisionerTest {
assertEquals("ValidationError", failure.getErrorCode());
assertTrue(failure.getMessage().contains("resource replacement"));
- verify(iam, never()).createUser(any(), any());
+ verify(iam, never()).createUser(any(), any(), any());
}
@Test
@@ -257,7 +258,7 @@ class IamUserCfnProvisionerTest {
existing.getTags().put("update-tag", "old");
existing.getTags().put("drop-tag", "remove-me");
- when(iam.createUser(eq("my-user"), eq("/"))).thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
+ when(iam.createUser(eq("my-user"), eq("/"), any())).thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
when(iam.getUser("my-user")).thenReturn(existing);
StackResource r = resource();
@@ -301,7 +302,7 @@ class IamUserCfnProvisionerTest {
IamUser existing = new IamUser("AIDAuser", "my-user", "/", "arn:aws:iam::" + ACCOUNT_ID + ":user/my-user");
existing.getTags().put("keep-tag", "old");
existing.getTags().put("drop-tag", "restore-me");
- when(iam.createUser(eq("my-user"), eq("/")))
+ when(iam.createUser(eq("my-user"), eq("/"), any()))
.thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
when(iam.getUser("my-user")).thenReturn(existing);
doThrow(new AwsException("ServiceFailure", "tag removal failed", 500))
@@ -330,7 +331,7 @@ class IamUserCfnProvisionerTest {
@Test
void updateReconcilesPathChange() {
IamUser existing = new IamUser("AIDAuser", "my-user", "/", "arn:aws:iam::" + ACCOUNT_ID + ":user/my-user");
- when(iam.createUser(eq("my-user"), eq("/new-path/"))).thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
+ when(iam.createUser(eq("my-user"), eq("/new-path/"), any())).thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
when(iam.getUser("my-user")).thenReturn(existing);
StackResource r = resource();
@@ -350,7 +351,7 @@ class IamUserCfnProvisionerTest {
@Test
void updateRefusesToAdoptReplacementUserWithDifferentUserId() {
IamUser replacement = new IamUser("AIDAnew-user", "my-user", "/", "arn:aws:iam::" + ACCOUNT_ID + ":user/my-user");
- when(iam.createUser(eq("my-user"), eq("/"))).thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
+ when(iam.createUser(eq("my-user"), eq("/"), any())).thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
when(iam.getUser("my-user")).thenReturn(replacement);
StackResource r = resource();
@@ -374,7 +375,7 @@ class IamUserCfnProvisionerTest {
IamUser existing = new IamUser("AIDAuser", "my-user", "/", "arn:aws:iam::" + ACCOUNT_ID + ":user/my-user");
String priorDocument = "{\"Version\":\"2012-10-17\",\"Statement\":[\"prior\"]}";
existing.getInlinePolicies().put("first", priorDocument);
- when(iam.createUser(eq("my-user"), eq("/"))).thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
+ when(iam.createUser(eq("my-user"), eq("/"), any())).thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
when(iam.getUser("my-user")).thenReturn(existing);
doThrow(new AwsException("MalformedPolicyDocument", "bad policy", 400))
.when(iam).putUserPolicy(eq("my-user"), eq("second"), any());
@@ -399,4 +400,123 @@ class IamUserCfnProvisionerTest {
verify(iam).putUserPolicy("my-user", "first", priorDocument);
verify(iam, never()).deleteUser("my-user");
}
+ private static final String BOUNDARY_OLD = "arn:aws:iam::" + ACCOUNT_ID + ":policy/boundary-old";
+ private static final String BOUNDARY_NEW = "arn:aws:iam::" + ACCOUNT_ID + ":policy/boundary-new";
+
+ /** A user this stack already owns, so provision() takes the adoption (update) path. */
+ private StackResource adoptExistingUser(String currentBoundary) {
+ IamUser existing = new IamUser("AIDAuser", "my-user", "/", "arn:aws:iam::" + ACCOUNT_ID + ":user/my-user");
+ existing.setPermissionsBoundaryArn(currentBoundary);
+ when(iam.createUser(eq("my-user"), eq("/"), any()))
+ .thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
+ when(iam.getUser("my-user")).thenReturn(existing);
+ StackResource r = resource();
+ r.setPhysicalId("my-user");
+ r.getAttributes().put("__FlociUserId", "AIDAuser");
+ return r;
+ }
+
+ @Test
+ void createPassesThePermissionsBoundaryToTheUser() {
+ stubCreate("custom-user", "/");
+
+ provisioner.provision(resource(), props("""
+ {"UserName": "custom-user", "PermissionsBoundary": "%s"}
+ """.formatted(BOUNDARY_NEW)), ctx());
+
+ verify(iam).createUser("custom-user", "/", BOUNDARY_NEW);
+ }
+
+ @Test
+ void updateAppliesAChangedPermissionsBoundary() {
+ StackResource r = adoptExistingUser(BOUNDARY_OLD);
+
+ provisioner.provision(r, props("""
+ {"UserName": "my-user", "PermissionsBoundary": "%s"}
+ """.formatted(BOUNDARY_NEW)), updateCtx("my-user"));
+
+ verify(iam).putUserPermissionsBoundary("my-user", BOUNDARY_NEW, "AIDAuser");
+ verify(iam, never()).deleteUserPermissionsBoundary(any(), any());
+ }
+
+ @Test
+ void updateRemovesAPermissionsBoundaryTheTemplateDropped() {
+ StackResource r = adoptExistingUser(BOUNDARY_OLD);
+
+ provisioner.provision(r, props("""
+ {"UserName": "my-user"}
+ """), updateCtx("my-user"));
+
+ verify(iam).deleteUserPermissionsBoundary("my-user", "AIDAuser");
+ }
+
+ @Test
+ void updateLeavesAnUnchangedOrAbsentPermissionsBoundaryAlone() {
+ // deleteUserPermissionsBoundary raises NoSuchEntity on a user without one.
+ StackResource r = adoptExistingUser(null);
+
+ provisioner.provision(r, props("""
+ {"UserName": "my-user"}
+ """), updateCtx("my-user"));
+
+ verify(iam, never()).deleteUserPermissionsBoundary(any(), any());
+ verify(iam, never()).putUserPermissionsBoundary(any(), any(), any());
+ }
+
+ // {"Fn::If": [cond, arn, {"Ref": "AWS::NoValue"}]} resolves to "", which must mean
+ // "no boundary", not a policy named "".
+ @Test
+ void createTreatsABlankPermissionsBoundaryAsAbsent() {
+ stubCreate("custom-user", "/");
+
+ provisioner.provision(resource(), props("""
+ {"UserName": "custom-user", "PermissionsBoundary": ""}
+ """), ctx());
+
+ verify(iam).createUser(eq("custom-user"), eq("/"), isNull());
+ }
+
+ @Test
+ void updateTreatsABlankPermissionsBoundaryAsDropped() {
+ StackResource r = adoptExistingUser(BOUNDARY_OLD);
+
+ provisioner.provision(r, props("""
+ {"UserName": "my-user", "PermissionsBoundary": ""}
+ """), updateCtx("my-user"));
+
+ verify(iam).deleteUserPermissionsBoundary("my-user", "AIDAuser");
+ verify(iam, never()).putUserPermissionsBoundary(any(), any(), any());
+ }
+
+ @Test
+ void failedUpdateRestoresThePriorPermissionsBoundary() {
+ StackResource r = adoptExistingUser(BOUNDARY_OLD);
+ doThrow(new AwsException("NoSuchEntity", "missing policy", 404))
+ .when(iam).attachUserPolicy("my-user", "arn:aws:iam::aws:policy/Missing");
+
+ assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
+ {"UserName": "my-user", "PermissionsBoundary": "%s",
+ "ManagedPolicyArns": ["arn:aws:iam::aws:policy/Missing"]}
+ """.formatted(BOUNDARY_NEW)), updateCtx("my-user")));
+
+ InOrder order = inOrder(iam);
+ order.verify(iam).putUserPermissionsBoundary("my-user", BOUNDARY_NEW, "AIDAuser");
+ order.verify(iam).putUserPermissionsBoundary("my-user", BOUNDARY_OLD, "AIDAuser");
+ verify(iam, never()).deleteUser(any());
+ }
+
+ @Test
+ void failedUpdateRemovesTheBoundaryItAddedOnlyFromTheAdoptedUser() {
+ StackResource r = adoptExistingUser(null);
+ doThrow(new AwsException("NoSuchEntity", "missing policy", 404))
+ .when(iam).attachUserPolicy("my-user", "arn:aws:iam::aws:policy/Missing");
+
+ assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
+ {"UserName": "my-user", "PermissionsBoundary": "%s",
+ "ManagedPolicyArns": ["arn:aws:iam::aws:policy/Missing"]}
+ """.formatted(BOUNDARY_NEW)), updateCtx("my-user")));
+
+ // The ID makes IamService refuse the delete if the name now belongs to a replacement user.
+ verify(iam).deleteUserPermissionsBoundary("my-user", "AIDAuser");
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryHandlerTest.java
index a65acdb1f7..92078a4808 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryHandlerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryHandlerTest.java
@@ -89,7 +89,7 @@ class IamQueryHandlerTest {
role.setCreateDate(Instant.parse(stored));
IamService service = mock(IamService.class);
when(service.createRole(ROLE_NAME, "/", "{}", null, 3600, Map.of(), null)).thenReturn(role);
- when(service.getRole(ROLE_NAME)).thenReturn(role);
+ when(service.getValidatedRole(ROLE_NAME)).thenReturn(role);
IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null);
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
index 16eb890ba9..f36637b5fd 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
@@ -1027,6 +1027,40 @@ class IamServiceTest {
"rejected update must not have changed the role's trust policy");
}
+ @Test
+ void permissionsBoundaryWritesRefuseARoleRecreatedUnderTheSameName() {
+ String boundary = iamService.createPolicy("Bound", "/", null, "{}", null).getArn();
+ String staleId = iamService.createRole("Reused", "/", "{}", null, 3600, null).getRoleId();
+ iamService.deleteRole("Reused");
+ iamService.createRole("Reused", "/", "{}", null, 3600, null);
+ iamService.putRolePermissionsBoundary("Reused", boundary);
+
+ assertEquals("EntityAlreadyExists", assertThrows(AwsException.class,
+ () -> iamService.deleteRolePermissionsBoundary("Reused", staleId)).getErrorCode());
+ assertEquals("EntityAlreadyExists", assertThrows(AwsException.class,
+ () -> iamService.putRolePermissionsBoundary("Reused", "arn:aws:iam::aws:policy/ReadOnlyAccess",
+ staleId)).getErrorCode());
+ assertEquals(boundary, iamService.getRole("Reused").getPermissionsBoundaryArn(),
+ "the replacement role's boundary must survive a write meant for the original");
+ }
+
+ @Test
+ void permissionsBoundaryWritesRefuseAUserRecreatedUnderTheSameName() {
+ String boundary = iamService.createPolicy("Bound", "/", null, "{}", null).getArn();
+ String staleId = iamService.createUser("reused", "/").getUserId();
+ iamService.deleteUser("reused");
+ iamService.createUser("reused", "/");
+ iamService.putUserPermissionsBoundary("reused", boundary);
+
+ assertEquals("EntityAlreadyExists", assertThrows(AwsException.class,
+ () -> iamService.deleteUserPermissionsBoundary("reused", staleId)).getErrorCode());
+ assertEquals("EntityAlreadyExists", assertThrows(AwsException.class,
+ () -> iamService.putUserPermissionsBoundary("reused", "arn:aws:iam::aws:policy/ReadOnlyAccess",
+ staleId)).getErrorCode());
+ assertEquals(boundary, iamService.getUser("reused").getPermissionsBoundaryArn(),
+ "the replacement user's boundary must survive a write meant for the original");
+ }
+
@Test
void createServiceLinkedRoleForAccessAnalyzer() {
IamRole role = iamService.createServiceLinkedRole(