mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cloudformation): delete AWS::IAM::User on stack deletion (#3076)
* fix(cloudformation): delete AWS::IAM::User on stack deletion (#2490) * fix(cloudformation): reconcile IAM user updates and verify user identity * fix(cloudformation): log intentionally tolerated errors during IAM user deletion * fix(cloudformation): use context helpers and assert Fn::GetAtt in IAM user provisioner * test(cloudformation): add AWS SDK compatibility test for IAM user * test(cloudformation): log tolerated exception during IAM user test cleanup * test(cloudformation): use Logger for cleanup in IAM user SDK test * test(cloudformation): use JBoss Logging for cleanup in IAM user SDK test * fix(cloudformation): address review feedback on IAM user provisioner --------- Signed-off-by: Vũ Thế Huy <31652864+vuthehuyht@users.noreply.github.com>
This commit is contained in:
1 parent
4ee5a528f3
commit
7b5c6e272d
8 files changed
+1199
-14
No files matched your search
+171
@@ -0,0 +1,171 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;
|
||||
import software.amazon.awssdk.services.cloudformation.model.CreateStackRequest;
|
||||
import software.amazon.awssdk.services.cloudformation.model.DeleteStackRequest;
|
||||
import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Output;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Stack;
|
||||
import software.amazon.awssdk.services.iam.IamClient;
|
||||
import software.amazon.awssdk.services.iam.model.DeleteUserRequest;
|
||||
import software.amazon.awssdk.services.iam.model.GetUserRequest;
|
||||
import software.amazon.awssdk.services.iam.model.GetUserResponse;
|
||||
import software.amazon.awssdk.services.iam.model.NoSuchEntityException;
|
||||
import software.amazon.awssdk.services.iam.model.User;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
@DisplayName("CloudFormation AWS::IAM::User")
|
||||
class CloudFormationIamUserTest {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudFormationIamUserTest.class.getName());
|
||||
|
||||
private static CloudFormationClient cloudFormation;
|
||||
private static IamClient iam;
|
||||
private static String stackName;
|
||||
private static String userName;
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
cloudFormation = TestFixtures.cloudFormationClient();
|
||||
iam = TestFixtures.iamClient();
|
||||
stackName = TestFixtures.uniqueName("compat-cfn-iam-user");
|
||||
userName = TestFixtures.uniqueName("compat-user");
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void cleanup() {
|
||||
if (cloudFormation != null) {
|
||||
try {
|
||||
cloudFormation.deleteStack(
|
||||
DeleteStackRequest.builder().stackName(stackName).build());
|
||||
} catch (Exception e) {
|
||||
LOG.log(Level.WARNING, "Failed to delete CloudFormation IAM user test stack: " + stackName, e);
|
||||
}
|
||||
cloudFormation.close();
|
||||
}
|
||||
if (iam != null) {
|
||||
try {
|
||||
iam.deleteUser(DeleteUserRequest.builder().userName(userName).build());
|
||||
} catch (Exception e) {
|
||||
LOG.log(Level.WARNING, "Failed to delete IAM user directly during cleanup: " + userName, e);
|
||||
}
|
||||
iam.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsValidatesUpdatesAndDeletesIamUserThroughAwsSdk() throws InterruptedException {
|
||||
cloudFormation.createStack(CreateStackRequest.builder()
|
||||
.stackName(stackName)
|
||||
.templateBody(template(userName, "/initial/"))
|
||||
.build());
|
||||
assertThat(waitForTerminal(stackName, 30)).isEqualTo("CREATE_COMPLETE");
|
||||
|
||||
Stack createdStack = cloudFormation.describeStacks(
|
||||
DescribeStacksRequest.builder().stackName(stackName).build())
|
||||
.stacks().get(0);
|
||||
Map<String, String> outputs = createdStack.outputs().stream()
|
||||
.collect(Collectors.toMap(Output::outputKey, Output::outputValue));
|
||||
|
||||
assertThat(outputs).containsEntry("UserRef", userName);
|
||||
String userArn = outputs.get("UserArn");
|
||||
assertThat(userArn).startsWith("arn:aws:iam::").endsWith(":user/initial/" + userName);
|
||||
|
||||
GetUserResponse userResponse = iam.getUser(GetUserRequest.builder().userName(userName).build());
|
||||
User user = userResponse.user();
|
||||
assertThat(user.userName()).isEqualTo(userName);
|
||||
assertThat(user.path()).isEqualTo("/initial/");
|
||||
assertThat(user.arn()).isEqualTo(userArn);
|
||||
String userId = user.userId();
|
||||
assertThat(userId).startsWith("AIDA");
|
||||
|
||||
// Update path on existing user
|
||||
cloudFormation.updateStack(r -> r
|
||||
.stackName(stackName)
|
||||
.templateBody(template(userName, "/updated/")));
|
||||
assertThat(waitForTerminal(stackName, 30)).isEqualTo("UPDATE_COMPLETE");
|
||||
|
||||
GetUserResponse updatedUserResponse = iam.getUser(GetUserRequest.builder().userName(userName).build());
|
||||
assertThat(updatedUserResponse.user().path()).isEqualTo("/updated/");
|
||||
assertThat(updatedUserResponse.user().userId()).isEqualTo(userId);
|
||||
|
||||
// Delete stack and verify user is removed
|
||||
cloudFormation.deleteStack(DeleteStackRequest.builder().stackName(stackName).build());
|
||||
waitForDeleted(stackName, 30);
|
||||
|
||||
assertThatThrownBy(() -> iam.getUser(GetUserRequest.builder().userName(userName).build()))
|
||||
.isInstanceOf(NoSuchEntityException.class);
|
||||
}
|
||||
|
||||
private static String template(String name, String path) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"AppUser": {
|
||||
"Type": "AWS::IAM::User",
|
||||
"Properties": {
|
||||
"UserName": "%s",
|
||||
"Path": "%s"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"UserRef": {"Value": {"Ref": "AppUser"}},
|
||||
"UserArn": {"Value": {"Fn::GetAtt": ["AppUser", "Arn"]}}
|
||||
}
|
||||
}
|
||||
""".formatted(name, path);
|
||||
}
|
||||
|
||||
private static String waitForTerminal(String name, int maxSeconds) throws InterruptedException {
|
||||
long deadline = System.currentTimeMillis() + maxSeconds * 1000L;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
List<Stack> stacks = cloudFormation.describeStacks(
|
||||
DescribeStacksRequest.builder().stackName(name).build()).stacks();
|
||||
if (!stacks.isEmpty()) {
|
||||
String status = stacks.get(0).stackStatusAsString();
|
||||
if (!status.endsWith("_IN_PROGRESS")) {
|
||||
return status;
|
||||
}
|
||||
}
|
||||
Thread.sleep(500);
|
||||
}
|
||||
throw new AssertionError(
|
||||
"Stack " + name + " did not reach a terminal state within " + maxSeconds + "s");
|
||||
}
|
||||
|
||||
private static void waitForDeleted(String name, int maxSeconds) throws InterruptedException {
|
||||
long deadline = System.currentTimeMillis() + maxSeconds * 1000L;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
try {
|
||||
List<Stack> stacks = cloudFormation.describeStacks(
|
||||
DescribeStacksRequest.builder().stackName(name).build()).stacks();
|
||||
if (stacks.isEmpty()
|
||||
|| "DELETE_COMPLETE".equals(stacks.get(0).stackStatusAsString())) {
|
||||
return;
|
||||
}
|
||||
} catch (CloudFormationException e) {
|
||||
if (e.getMessage() != null && e.getMessage().contains("does not exist")) {
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
Thread.sleep(500);
|
||||
}
|
||||
throw new AssertionError(
|
||||
"Stack " + name + " was not deleted within " + maxSeconds + "s");
|
||||
}
|
||||
}
|
||||
-13
@@ -239,7 +239,6 @@ public class CloudFormationResourceProvisioner {
|
||||
"AWS::IAM::InstanceProfile",
|
||||
"AWS::IAM::ManagedPolicy",
|
||||
"AWS::IAM::Policy",
|
||||
"AWS::IAM::User",
|
||||
"AWS::Lambda::Function",
|
||||
"AWS::Lambda::LayerVersion",
|
||||
"AWS::RDS::DBCluster",
|
||||
@@ -399,7 +398,6 @@ public class CloudFormationResourceProvisioner {
|
||||
case "AWS::Lambda::Function" -> provisionLambda(resource, properties, engine, region, accountId, stackName);
|
||||
case "AWS::Lambda::LayerVersion" ->
|
||||
provisionLambdaLayerVersion(resource, properties, engine, region, stackName);
|
||||
case "AWS::IAM::User" -> provisionIamUser(resource, properties, engine, stackName);
|
||||
case "AWS::IAM::AccessKey" -> provisionIamAccessKey(resource, properties, engine);
|
||||
case "AWS::IAM::Policy" -> provisionIamInlinePolicy(resource, properties, engine, stackName);
|
||||
case "AWS::IAM::ManagedPolicy" ->
|
||||
@@ -4772,17 +4770,6 @@ public class CloudFormationResourceProvisioner {
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
private void provisionIamUser(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String stackName) {
|
||||
String userName = resolveOptional(props, "UserName", engine);
|
||||
if (userName == null || userName.isBlank()) {
|
||||
userName = generatePhysicalName(stackName, r.getLogicalId(), 64, false);
|
||||
}
|
||||
var user = iamService.createUser(userName, "/");
|
||||
r.setPhysicalId(userName);
|
||||
r.getAttributes().put("Arn", user.getArn());
|
||||
}
|
||||
|
||||
private void provisionIamAccessKey(StackResource r, JsonNode props, CloudFormationTemplateEngine engine) {
|
||||
String userName = resolveOptional(props, "UserName", engine);
|
||||
if (userName != null) {
|
||||
|
||||
+320
@@ -0,0 +1,320 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.model.AccessKey;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamUser;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* CloudFormation provisioning for {@code AWS::IAM::User}, moved out of the
|
||||
* {@code CloudFormationResourceProvisioner} switch.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class IamUserCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(IamUserCfnProvisioner.class);
|
||||
|
||||
private static final String INLINE_NAMES_ATTR = "__FlociInlinePolicyNames";
|
||||
private static final String MANAGED_ARNS_ATTR = "__FlociManagedPolicyArns";
|
||||
private static final String GROUPS_ATTR = "__FlociGroups";
|
||||
private static final String USER_ID_ATTR = "__FlociUserId";
|
||||
|
||||
private final IamService iamService;
|
||||
|
||||
@Inject
|
||||
public IamUserCfnProvisioner(IamService iamService) {
|
||||
this.iamService = iamService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of("AWS::IAM::User");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String userName = ctx.stablePhysicalName(ctx.resolveOptional(props, "UserName"),
|
||||
r.getLogicalId(), 64, false);
|
||||
final String resolvedUserName = userName;
|
||||
if (ctx.isUpdate() && !ctx.priorPhysicalId().equals(resolvedUserName)) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Updating UserName requires resource replacement, which is not supported.", 400);
|
||||
}
|
||||
|
||||
String path = ctx.resolveOptional(props, "Path");
|
||||
if (path == null) {
|
||||
path = "/";
|
||||
}
|
||||
final String resolvedPath = path;
|
||||
|
||||
List<String> managedPolicyArns = ctx.resolveStringList(props, "ManagedPolicyArns");
|
||||
List<String> groups = ctx.resolveStringList(props, "Groups");
|
||||
|
||||
IamUser user;
|
||||
boolean createdUser = false;
|
||||
String priorPath = null;
|
||||
String priorUserId = null;
|
||||
try {
|
||||
user = iamService.createUser(resolvedUserName, resolvedPath);
|
||||
createdUser = true;
|
||||
r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
|
||||
} catch (AwsException e) {
|
||||
if (!ctx.reusesPriorEntity(resolvedUserName) || !"EntityAlreadyExists".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
user = iamService.getUser(resolvedUserName);
|
||||
String existingUserId = r.getAttributes().get(USER_ID_ATTR);
|
||||
if (existingUserId == null || existingUserId.isBlank()
|
||||
|| !existingUserId.equals(user.getUserId())) {
|
||||
r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
|
||||
throw e;
|
||||
}
|
||||
priorPath = user.getPath();
|
||||
priorUserId = existingUserId;
|
||||
if (!resolvedPath.equals(user.getPath())) {
|
||||
iamService.updateUser(resolvedUserName, null, resolvedPath, existingUserId);
|
||||
user = iamService.getUser(resolvedUserName);
|
||||
}
|
||||
}
|
||||
|
||||
r.setPhysicalId(resolvedUserName);
|
||||
r.getAttributes().put("Arn", user.getArn());
|
||||
r.getAttributes().put(USER_ID_ATTR, user.getUserId());
|
||||
|
||||
Set<String> previousInlineNames = readTrackedSet(r, INLINE_NAMES_ATTR);
|
||||
Set<String> previousManagedArns = readTrackedSet(r, MANAGED_ARNS_ATTR);
|
||||
Set<String> previousGroups = readTrackedSet(r, GROUPS_ATTR);
|
||||
|
||||
Set<String> originalGroups = new HashSet<>(user.getGroupNames());
|
||||
Set<String> originalPolicyArns = new HashSet<>(user.getAttachedPolicyArns());
|
||||
Map<String, String> originalInlinePolicies = new HashMap<>(user.getInlinePolicies());
|
||||
|
||||
LinkedHashSet<String> groupsAddedByThisAttempt = new LinkedHashSet<>();
|
||||
LinkedHashSet<String> groupsRemovedByThisAttempt = new LinkedHashSet<>();
|
||||
LinkedHashSet<String> attachedByThisAttempt = new LinkedHashSet<>();
|
||||
LinkedHashSet<String> detachedByThisAttempt = new LinkedHashSet<>();
|
||||
LinkedHashSet<String> inlineWrittenByThisAttempt = new LinkedHashSet<>();
|
||||
LinkedHashSet<String> inlineRemovedByThisAttempt = new LinkedHashSet<>();
|
||||
|
||||
final String pathToRestore = priorPath;
|
||||
final String userIdToRestore = priorUserId;
|
||||
|
||||
try {
|
||||
for (String groupName : groups) {
|
||||
iamService.addUserToGroup(groupName, resolvedUserName);
|
||||
if (!originalGroups.contains(groupName)) {
|
||||
groupsAddedByThisAttempt.add(groupName);
|
||||
}
|
||||
}
|
||||
|
||||
for (String policyArn : managedPolicyArns) {
|
||||
iamService.attachUserPolicy(resolvedUserName, policyArn);
|
||||
if (!originalPolicyArns.contains(policyArn)) {
|
||||
attachedByThisAttempt.add(policyArn);
|
||||
}
|
||||
}
|
||||
|
||||
if (props != null && props.has("Policies")) {
|
||||
for (JsonNode policy : props.get("Policies")) {
|
||||
String declaredName = ctx.resolveOptional(policy, "PolicyName");
|
||||
if (declaredName == null || declaredName.isBlank()) {
|
||||
throw new AwsException("ValidationError",
|
||||
"An inline policy on user " + resolvedUserName + " has no PolicyName.", 400);
|
||||
}
|
||||
final String policyName = declaredName;
|
||||
JsonNode document = policy.get("PolicyDocument");
|
||||
if (document == null || document.isNull()) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Inline policy '" + policyName + "' on user " + resolvedUserName
|
||||
+ " has no PolicyDocument.", 400);
|
||||
}
|
||||
iamService.putUserPolicy(resolvedUserName, policyName,
|
||||
ctx.engine().resolveJsonAttribute(document));
|
||||
inlineWrittenByThisAttempt.add(policyName);
|
||||
}
|
||||
}
|
||||
|
||||
for (String stale : previousInlineNames) {
|
||||
if (!inlineWrittenByThisAttempt.contains(stale)
|
||||
&& originalInlinePolicies.containsKey(stale)) {
|
||||
iamService.deleteUserPolicy(resolvedUserName, stale);
|
||||
inlineRemovedByThisAttempt.add(stale);
|
||||
}
|
||||
}
|
||||
for (String stale : previousManagedArns) {
|
||||
if (!managedPolicyArns.contains(stale) && originalPolicyArns.contains(stale)) {
|
||||
iamService.detachUserPolicy(resolvedUserName, stale);
|
||||
detachedByThisAttempt.add(stale);
|
||||
}
|
||||
}
|
||||
for (String stale : previousGroups) {
|
||||
if (!groups.contains(stale) && originalGroups.contains(stale)) {
|
||||
iamService.removeUserFromGroup(stale, resolvedUserName);
|
||||
groupsRemovedByThisAttempt.add(stale);
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException failure) {
|
||||
boolean cleanupSucceeded = true;
|
||||
|
||||
for (String groupName : groupsRemovedByThisAttempt) {
|
||||
if (!CfnRollback.attemptIamCleanup(failure,
|
||||
"re-add user " + resolvedUserName + " to group " + groupName,
|
||||
() -> iamService.addUserToGroup(groupName, resolvedUserName))) {
|
||||
cleanupSucceeded = false;
|
||||
}
|
||||
}
|
||||
for (String policyName : inlineRemovedByThisAttempt) {
|
||||
String prior = originalInlinePolicies.get(policyName);
|
||||
if (prior == null) {
|
||||
continue;
|
||||
}
|
||||
if (!CfnRollback.attemptIamCleanup(failure,
|
||||
"restore inline policy " + policyName + " on user " + resolvedUserName,
|
||||
() -> iamService.putUserPolicy(resolvedUserName, policyName, prior))) {
|
||||
cleanupSucceeded = false;
|
||||
}
|
||||
}
|
||||
for (String policyArn : detachedByThisAttempt) {
|
||||
if (!CfnRollback.attemptIamCleanup(failure,
|
||||
"reattach policy " + policyArn + " to user " + resolvedUserName,
|
||||
() -> iamService.attachUserPolicy(resolvedUserName, policyArn))) {
|
||||
cleanupSucceeded = false;
|
||||
}
|
||||
}
|
||||
|
||||
List<String> inlineRollback = new ArrayList<>(inlineWrittenByThisAttempt);
|
||||
Collections.reverse(inlineRollback);
|
||||
for (String policyName : inlineRollback) {
|
||||
String prior = originalInlinePolicies.get(policyName);
|
||||
String cleanupDescription = (prior == null ? "remove" : "restore")
|
||||
+ " inline policy " + policyName + " on user " + resolvedUserName;
|
||||
if (!CfnRollback.attemptIamCleanup(failure, cleanupDescription, () -> {
|
||||
if (prior == null) {
|
||||
iamService.deleteUserPolicy(resolvedUserName, policyName);
|
||||
} else {
|
||||
iamService.putUserPolicy(resolvedUserName, policyName, prior);
|
||||
}
|
||||
})) {
|
||||
cleanupSucceeded = false;
|
||||
}
|
||||
}
|
||||
|
||||
List<String> rollbackArns = new ArrayList<>(attachedByThisAttempt);
|
||||
Collections.reverse(rollbackArns);
|
||||
for (String policyArn : rollbackArns) {
|
||||
String cleanupDescription = "detach policy " + policyArn + " from user " + resolvedUserName;
|
||||
if (!CfnRollback.attemptIamCleanup(failure, cleanupDescription,
|
||||
() -> iamService.detachUserPolicy(resolvedUserName, policyArn))) {
|
||||
cleanupSucceeded = false;
|
||||
}
|
||||
}
|
||||
|
||||
List<String> rollbackGroups = new ArrayList<>(groupsAddedByThisAttempt);
|
||||
Collections.reverse(rollbackGroups);
|
||||
for (String groupName : rollbackGroups) {
|
||||
String cleanupDescription = "remove user " + resolvedUserName + " from group " + groupName;
|
||||
if (!CfnRollback.attemptIamCleanup(failure, cleanupDescription,
|
||||
() -> iamService.removeUserFromGroup(groupName, resolvedUserName))) {
|
||||
cleanupSucceeded = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (pathToRestore != null) {
|
||||
if (!CfnRollback.attemptIamCleanup(failure, "restore prior path on user " + resolvedUserName,
|
||||
() -> iamService.updateUser(resolvedUserName, null, pathToRestore, userIdToRestore))) {
|
||||
cleanupSucceeded = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (createdUser) {
|
||||
if (!CfnRollback.attemptIamCleanup(failure, "delete user " + resolvedUserName,
|
||||
() -> iamService.deleteUser(resolvedUserName))) {
|
||||
cleanupSucceeded = false;
|
||||
}
|
||||
if (cleanupSucceeded) {
|
||||
r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
|
||||
}
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
|
||||
writeTrackedSet(r, INLINE_NAMES_ATTR, inlineWrittenByThisAttempt);
|
||||
writeTrackedSet(r, MANAGED_ARNS_ATTR, managedPolicyArns);
|
||||
writeTrackedSet(r, GROUPS_ATTR, groups);
|
||||
}
|
||||
|
||||
private static Set<String> readTrackedSet(StackResource r, String attribute) {
|
||||
String raw = r.getAttributes().get(attribute);
|
||||
if (raw == null || raw.isEmpty()) {
|
||||
return Set.of();
|
||||
}
|
||||
return new LinkedHashSet<>(List.of(raw.split("\n")));
|
||||
}
|
||||
|
||||
private static void writeTrackedSet(StackResource r, String attribute, Collection<String> values) {
|
||||
if (values.isEmpty()) {
|
||||
r.getAttributes().remove(attribute);
|
||||
return;
|
||||
}
|
||||
r.getAttributes().put(attribute, String.join("\n", values));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
IamUser user;
|
||||
try {
|
||||
user = iamService.getUser(physicalId);
|
||||
} catch (AwsException e) {
|
||||
if (!"NoSuchEntity".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
LOG.debugv("IAM user already gone, treating as deleted: {0}", physicalId);
|
||||
return;
|
||||
}
|
||||
|
||||
for (String policyArn : new ArrayList<>(user.getAttachedPolicyArns())) {
|
||||
CfnDeletes.safeDelete("attached policy " + policyArn + " on user", physicalId,
|
||||
() -> iamService.detachUserPolicy(physicalId, policyArn), "NoSuchEntity");
|
||||
}
|
||||
|
||||
for (String policyName : new ArrayList<>(user.getInlinePolicies().keySet())) {
|
||||
CfnDeletes.safeDelete("inline policy " + policyName + " on user", physicalId,
|
||||
() -> iamService.deleteUserPolicy(physicalId, policyName), "NoSuchEntity");
|
||||
}
|
||||
|
||||
for (String groupName : new ArrayList<>(user.getGroupNames())) {
|
||||
CfnDeletes.safeDelete("user " + physicalId + " membership in group " + groupName, physicalId,
|
||||
() -> iamService.removeUserFromGroup(groupName, physicalId), "NoSuchEntity");
|
||||
}
|
||||
|
||||
try {
|
||||
for (AccessKey key : iamService.listAccessKeys(physicalId)) {
|
||||
CfnDeletes.safeDelete("access key " + key.getAccessKeyId() + " on user", physicalId,
|
||||
() -> iamService.deleteAccessKey(physicalId, key.getAccessKeyId()), "NoSuchEntity");
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
if (!"NoSuchEntity".equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
LOG.debugv("IAM user access keys already gone, treating as deleted: {0}", physicalId);
|
||||
}
|
||||
|
||||
CfnDeletes.safeDelete("IAM user", physicalId,
|
||||
() -> iamService.deleteUser(physicalId), "NoSuchEntity");
|
||||
}
|
||||
}
|
||||
@@ -395,7 +395,21 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
public void updateUser(String userName, String newUserName, String newPath) {
|
||||
updateUser(userName, newUserName, newPath, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as {@link #updateUser(String, String, String)}, but verifies {@code expectedUserId}
|
||||
* against the resolved user's immutable ID before applying the update, atomically with the
|
||||
* name-based lookup.
|
||||
*/
|
||||
public void updateUser(String userName, String newUserName, String newPath, String expectedUserId) {
|
||||
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);
|
||||
}
|
||||
if (newUserName != null && !newUserName.equals(userName)) {
|
||||
if (users.get(newUserName).isPresent()) {
|
||||
throw new AwsException("EntityAlreadyExists",
|
||||
|
||||
+2
@@ -39,6 +39,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.EcsCapaci
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.EcsCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.FirehoseCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamRoleCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamUserCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.IotCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.IotDomainConfigurationCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.KinesisCfnProvisioner;
|
||||
@@ -233,6 +234,7 @@ final class CfnProvisionerFixture {
|
||||
}
|
||||
if (iamService != null) {
|
||||
discovered.add(new IamRoleCfnProvisioner(iamService));
|
||||
discovered.add(new IamUserCfnProvisioner(iamService));
|
||||
}
|
||||
if (ecsService != null) {
|
||||
discovered.add(new EcsCapacityCfnProvisioner(ecsService));
|
||||
|
||||
+361
@@ -0,0 +1,361 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
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.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* Verifies CloudFormation provisioning and deprovisioning lifecycle for {@code AWS::IAM::User}
|
||||
* (regression test for issue #2490).
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationIamUserIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=111122223333/20260205/us-east-1/cloudformation/aws4_request";
|
||||
private static final String IAM_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=111122223333/20260205/us-east-1/iam/aws4_request";
|
||||
|
||||
@Test
|
||||
void deleteStackDeletesIamUserAndAllowsRecreation() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String userName = "probe-user-" + suffix;
|
||||
String stackName = "cfn-user-stack-" + suffix;
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"ProbeUser": {
|
||||
"Type": "AWS::IAM::User",
|
||||
"Properties": {
|
||||
"UserName": "%s"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"UserRef": {"Value": {"Ref": "ProbeUser"}},
|
||||
"UserArn": {"Value": {"Fn::GetAtt": ["ProbeUser", "Arn"]}}
|
||||
}
|
||||
}
|
||||
""".formatted(userName);
|
||||
|
||||
String stackId = createStack(stackName, template);
|
||||
awaitStackStatus(stackId, "CREATE_COMPLETE");
|
||||
|
||||
String stackXml = describeStacks(stackId);
|
||||
assertEquals(userName, outputValue(stackXml, "UserRef"));
|
||||
String expectedArn = "arn:aws:iam::111122223333:user/" + userName;
|
||||
assertEquals(expectedArn, outputValue(stackXml, "UserArn"));
|
||||
|
||||
// Verify IAM user exists and Arn matches
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "GetUser")
|
||||
.formParam("UserName", userName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<UserName>" + userName + "</UserName>"))
|
||||
.body(containsString("<Arn>" + expectedArn + "</Arn>"));
|
||||
|
||||
// Delete the stack
|
||||
deleteStack(stackName);
|
||||
awaitStackStatus(stackId, "DELETE_COMPLETE");
|
||||
|
||||
// Verify IAM user is gone (NoSuchEntity / 404)
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "GetUser")
|
||||
.formParam("UserName", userName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body(containsString("NoSuchEntity"));
|
||||
|
||||
// Redeploying with the same explicit UserName succeeds rather than failing with EntityAlreadyExists
|
||||
String newStackName = "cfn-user-stack-recreate-" + suffix;
|
||||
String newStackId = createStack(newStackName, template);
|
||||
awaitStackStatus(newStackId, "CREATE_COMPLETE");
|
||||
|
||||
deleteStack(newStackName);
|
||||
awaitStackStatus(newStackId, "DELETE_COMPLETE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStackDeletesUserWithGeneratedName() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "cfn-genuser-stack-" + suffix;
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"GenUser": {
|
||||
"Type": "AWS::IAM::User"
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"UserRef": {"Value": {"Ref": "GenUser"}},
|
||||
"UserArn": {"Value": {"Fn::GetAtt": ["GenUser", "Arn"]}}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
String stackId = createStack(stackName, template);
|
||||
awaitStackStatus(stackId, "CREATE_COMPLETE");
|
||||
|
||||
String stackXml = describeStacks(stackId);
|
||||
String generatedUserName = outputValue(stackXml, "UserRef");
|
||||
assertNotNull(generatedUserName);
|
||||
assertEquals("arn:aws:iam::111122223333:user/" + generatedUserName, outputValue(stackXml, "UserArn"));
|
||||
|
||||
// Verify generated user exists
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "GetUser")
|
||||
.formParam("UserName", generatedUserName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<UserName>" + generatedUserName + "</UserName>"))
|
||||
.body(containsString("<Arn>arn:aws:iam::111122223333:user/" + generatedUserName + "</Arn>"));
|
||||
|
||||
deleteStack(stackName);
|
||||
awaitStackStatus(stackId, "DELETE_COMPLETE");
|
||||
|
||||
// Verify generated user is deleted
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "GetUser")
|
||||
.formParam("UserName", generatedUserName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body(containsString("NoSuchEntity"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStackReconcilesGroupsPoliciesAndPath() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String userName = "update-user-" + suffix;
|
||||
String stackName = "cfn-update-user-stack-" + suffix;
|
||||
|
||||
// Pre-create two groups
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "CreateGroup")
|
||||
.formParam("GroupName", "group-a-" + suffix)
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "CreateGroup")
|
||||
.formParam("GroupName", "group-b-" + suffix)
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
String template1 = """
|
||||
{
|
||||
"Resources": {
|
||||
"TestUser": {
|
||||
"Type": "AWS::IAM::User",
|
||||
"Properties": {
|
||||
"UserName": "%s",
|
||||
"Path": "/initial/",
|
||||
"Groups": ["group-a-%s", "group-b-%s"],
|
||||
"ManagedPolicyArns": [
|
||||
"arn:aws:iam::aws:policy/ReadOnlyAccess",
|
||||
"arn:aws:iam::aws:policy/PowerUserAccess"
|
||||
],
|
||||
"Policies": [
|
||||
{
|
||||
"PolicyName": "keep-policy",
|
||||
"PolicyDocument": {"Version": "2012-10-17", "Statement": []}
|
||||
},
|
||||
{
|
||||
"PolicyName": "drop-policy",
|
||||
"PolicyDocument": {"Version": "2012-10-17", "Statement": []}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(userName, suffix, suffix);
|
||||
|
||||
String stackId = createStack(stackName, template1);
|
||||
awaitStackStatus(stackId, "CREATE_COMPLETE");
|
||||
|
||||
// Verify initial state
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "GetUser")
|
||||
.formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<Path>/initial/</Path>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "ListAttachedUserPolicies")
|
||||
.formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("ReadOnlyAccess"))
|
||||
.body(containsString("PowerUserAccess"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "ListUserPolicies")
|
||||
.formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<member>keep-policy</member>"))
|
||||
.body(containsString("<member>drop-policy</member>"));
|
||||
|
||||
// Update stack: change path to /updated/, drop group-b, drop PowerUserAccess, drop drop-policy
|
||||
String template2 = """
|
||||
{
|
||||
"Resources": {
|
||||
"TestUser": {
|
||||
"Type": "AWS::IAM::User",
|
||||
"Properties": {
|
||||
"UserName": "%s",
|
||||
"Path": "/updated/",
|
||||
"Groups": ["group-a-%s"],
|
||||
"ManagedPolicyArns": [
|
||||
"arn:aws:iam::aws:policy/ReadOnlyAccess"
|
||||
],
|
||||
"Policies": [
|
||||
{
|
||||
"PolicyName": "keep-policy",
|
||||
"PolicyDocument": {"Version": "2012-10-17", "Statement": []}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(userName, suffix);
|
||||
|
||||
updateStack(stackName, template2);
|
||||
awaitStackStatus(stackId, "UPDATE_COMPLETE");
|
||||
|
||||
// Verify updated path
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "GetUser")
|
||||
.formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<Path>/updated/</Path>"));
|
||||
|
||||
// Verify managed policy PowerUserAccess was detached
|
||||
String attachedPolicies = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "ListAttachedUserPolicies")
|
||||
.formParam("UserName", userName)
|
||||
.when().post("/").then().statusCode(200).extract().asString();
|
||||
assertThat(attachedPolicies, containsString("ReadOnlyAccess"));
|
||||
assertThat(attachedPolicies, org.hamcrest.Matchers.not(containsString("PowerUserAccess")));
|
||||
|
||||
// Verify drop-policy was deleted
|
||||
String inlinePolicies = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "ListUserPolicies")
|
||||
.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>")));
|
||||
|
||||
// Verify group-b was removed
|
||||
String userGroups = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "ListGroupsForUser")
|
||||
.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)));
|
||||
|
||||
deleteStack(stackName);
|
||||
awaitStackStatus(stackId, "DELETE_COMPLETE");
|
||||
}
|
||||
|
||||
private static String createStack(String stackName, String template) {
|
||||
return cfnQuery("CreateStack", stackName, template)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract()
|
||||
.xmlPath()
|
||||
.getString("CreateStackResponse.CreateStackResult.StackId");
|
||||
}
|
||||
|
||||
private static void updateStack(String stackName, String template) {
|
||||
cfnQuery("UpdateStack", stackName, template)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static void deleteStack(String stackName) {
|
||||
cfnQuery("DeleteStack", stackName)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static void awaitStackStatus(String stackId, String status) throws InterruptedException {
|
||||
String xml = "";
|
||||
long deadline = System.currentTimeMillis() + 10_000;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
xml = describeStacks(stackId);
|
||||
if (xml.contains("<StackStatus>" + status + "</StackStatus>")) {
|
||||
return;
|
||||
}
|
||||
Thread.sleep(50);
|
||||
}
|
||||
fail("stack " + stackId + " never reached " + status + ": " + xml);
|
||||
}
|
||||
|
||||
private static String describeStacks(String stackId) {
|
||||
return cfnQuery("DescribeStacks", stackId).then().statusCode(200).extract().asString();
|
||||
}
|
||||
|
||||
private static Response cfnQuery(String action, String stackName) {
|
||||
return cfnQuery(action, stackName, null);
|
||||
}
|
||||
|
||||
private static Response cfnQuery(String action, String stackName, String template) {
|
||||
var req = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", action)
|
||||
.formParam("StackName", stackName);
|
||||
if (template != null) {
|
||||
req.formParam("TemplateBody", template);
|
||||
}
|
||||
return req.when().post("/");
|
||||
}
|
||||
|
||||
private static String outputValue(String xml, String key) {
|
||||
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
|
||||
}
|
||||
}
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.model.AccessKey;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamUser;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
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.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class IamUserCfnProvisionerTest {
|
||||
|
||||
private static final String ACCOUNT_ID = "000000000000";
|
||||
|
||||
private final IamService iam = mock(IamService.class);
|
||||
private final IamUserCfnProvisioner provisioner = new IamUserCfnProvisioner(iam);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private ProvisionContext ctx() {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null ? null : node.asText();
|
||||
});
|
||||
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
// resolveStringList delegates to the real engine method; for the literal arrays these
|
||||
// tests use it just walks the array and calls resolve(...) per element, stubbed above.
|
||||
when(engine.resolveStringList(any())).thenCallRealMethod();
|
||||
|
||||
when(engine.resolveJsonAttribute(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node != null && node.isTextual() ? node.asText() : node.toString();
|
||||
});
|
||||
|
||||
return new ProvisionContext(engine, "us-east-1", ACCOUNT_ID, "test-stack");
|
||||
}
|
||||
|
||||
private ProvisionContext updateCtx(String priorPhysicalId) {
|
||||
ProvisionContext base = ctx();
|
||||
return new ProvisionContext(base.engine(), base.region(), base.accountId(), base.stackName(), priorPhysicalId);
|
||||
}
|
||||
|
||||
private StackResource resource() {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("AppUser");
|
||||
r.setResourceType("AWS::IAM::User");
|
||||
r.setAttributes(new HashMap<>());
|
||||
return r;
|
||||
}
|
||||
|
||||
private JsonNode props(String json) {
|
||||
try {
|
||||
return mapper.readTree(json);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
return user;
|
||||
}
|
||||
|
||||
@Test
|
||||
void declaresIamUserResourceType() {
|
||||
assertEquals(java.util.Set.of("AWS::IAM::User"), provisioner.resourceTypes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionCreatesUserWithExplicitUserNameAndDefaultPath() {
|
||||
stubCreate("custom-user", "/");
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, props("""
|
||||
{
|
||||
"UserName": "custom-user"
|
||||
}
|
||||
"""), ctx());
|
||||
|
||||
assertEquals("custom-user", r.getPhysicalId());
|
||||
assertEquals("arn:aws:iam::" + ACCOUNT_ID + ":user/custom-user", r.getAttributes().get("Arn"));
|
||||
verify(iam).createUser("custom-user", "/");
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionCreatesUserWithCustomPath() {
|
||||
stubCreate("custom-user", "/engineering/");
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, props("""
|
||||
{
|
||||
"UserName": "custom-user",
|
||||
"Path": "/engineering/"
|
||||
}
|
||||
"""), ctx());
|
||||
|
||||
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/");
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionGeneratesPhysicalNameWhenUserNameIsOmitted() {
|
||||
when(iam.createUser(any(), eq("/"))).thenAnswer(inv -> {
|
||||
String name = inv.getArgument(0);
|
||||
return new IamUser("AIDA" + name, name, "/", "arn:aws:iam::" + ACCOUNT_ID + ":user/" + name);
|
||||
});
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode(), ctx());
|
||||
|
||||
assertNotNull(r.getPhysicalId());
|
||||
assertTrue(r.getPhysicalId().contains("test-stack"));
|
||||
assertEquals("arn:aws:iam::" + ACCOUNT_ID + ":user/" + r.getPhysicalId(), r.getAttributes().get("Arn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionAttachesManagedPoliciesAndInlinePoliciesAndGroups() {
|
||||
IamUser user = stubCreate("app-user", "/");
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, props("""
|
||||
{
|
||||
"UserName": "app-user",
|
||||
"Groups": ["developers", "qa"],
|
||||
"ManagedPolicyArns": [
|
||||
"arn:aws:iam::aws:policy/ReadOnlyAccess",
|
||||
"arn:aws:iam::aws:policy/PowerUserAccess"
|
||||
],
|
||||
"Policies": [
|
||||
{
|
||||
"PolicyName": "s3-access",
|
||||
"PolicyDocument": {"Version": "2012-10-17", "Statement": []}
|
||||
}
|
||||
]
|
||||
}
|
||||
"""), ctx());
|
||||
|
||||
verify(iam).addUserToGroup("developers", "app-user");
|
||||
verify(iam).addUserToGroup("qa", "app-user");
|
||||
verify(iam).attachUserPolicy("app-user", "arn:aws:iam::aws:policy/ReadOnlyAccess");
|
||||
verify(iam).attachUserPolicy("app-user", "arn:aws:iam::aws:policy/PowerUserAccess");
|
||||
verify(iam).putUserPolicy(eq("app-user"), eq("s3-access"), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatingUserNameRequiresReplacement() {
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("old-user");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () ->
|
||||
provisioner.provision(r, props("""
|
||||
{
|
||||
"UserName": "new-user"
|
||||
}
|
||||
"""), updateCtx("old-user")));
|
||||
|
||||
assertEquals("ValidationError", failure.getErrorCode());
|
||||
assertTrue(failure.getMessage().contains("resource replacement"));
|
||||
verify(iam, never()).createUser(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteDetachesPoliciesRemovesGroupsAndDeletesUser() {
|
||||
IamUser user = new IamUser("AIDAuser", "my-user", "/", "arn:aws:iam::" + ACCOUNT_ID + ":user/my-user");
|
||||
user.getAttachedPolicyArns().add("arn:aws:iam::aws:policy/ReadOnlyAccess");
|
||||
user.getInlinePolicies().put("inline-1", "{}");
|
||||
user.getGroupNames().add("dev-group");
|
||||
when(iam.getUser("my-user")).thenReturn(user);
|
||||
|
||||
AccessKey key = new AccessKey("AKIA123", "secret", "my-user");
|
||||
when(iam.listAccessKeys("my-user")).thenReturn(List.of(key));
|
||||
|
||||
provisioner.delete("AWS::IAM::User", "my-user", "us-east-1");
|
||||
|
||||
verify(iam).detachUserPolicy("my-user", "arn:aws:iam::aws:policy/ReadOnlyAccess");
|
||||
verify(iam).deleteUserPolicy("my-user", "inline-1");
|
||||
verify(iam).removeUserFromGroup("dev-group", "my-user");
|
||||
verify(iam).deleteAccessKey("my-user", "AKIA123");
|
||||
verify(iam).deleteUser("my-user");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteToleratesAlreadyDeletedUser() {
|
||||
when(iam.getUser("already-gone"))
|
||||
.thenThrow(new AwsException("NoSuchEntity", "User does not exist", 404));
|
||||
|
||||
provisioner.delete("AWS::IAM::User", "already-gone", "us-east-1");
|
||||
|
||||
verify(iam, never()).deleteUser(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateReconcilesRemovedGroupsManagedPoliciesAndInlinePolicies() {
|
||||
IamUser existing = new IamUser("AIDAuser", "my-user", "/", "arn:aws:iam::" + ACCOUNT_ID + ":user/my-user");
|
||||
existing.getGroupNames().add("keep-group");
|
||||
existing.getGroupNames().add("drop-group");
|
||||
existing.getAttachedPolicyArns().add("arn:aws:iam::aws:policy/Keep");
|
||||
existing.getAttachedPolicyArns().add("arn:aws:iam::aws:policy/Drop");
|
||||
existing.getInlinePolicies().put("keep-inline", "{}");
|
||||
existing.getInlinePolicies().put("drop-inline", "{}");
|
||||
|
||||
when(iam.createUser(eq("my-user"), eq("/"))).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");
|
||||
r.getAttributes().put("__FlociGroups", "keep-group\ndrop-group");
|
||||
r.getAttributes().put("__FlociManagedPolicyArns", "arn:aws:iam::aws:policy/Keep\narn:aws:iam::aws:policy/Drop");
|
||||
r.getAttributes().put("__FlociInlinePolicyNames", "keep-inline\ndrop-inline");
|
||||
|
||||
provisioner.provision(r, props("""
|
||||
{
|
||||
"UserName": "my-user",
|
||||
"Groups": ["keep-group"],
|
||||
"ManagedPolicyArns": ["arn:aws:iam::aws:policy/Keep"],
|
||||
"Policies": [
|
||||
{
|
||||
"PolicyName": "keep-inline",
|
||||
"PolicyDocument": {"Version": "2012-10-17", "Statement": []}
|
||||
}
|
||||
]
|
||||
}
|
||||
"""), updateCtx("my-user"));
|
||||
|
||||
verify(iam).removeUserFromGroup("drop-group", "my-user");
|
||||
verify(iam).detachUserPolicy("my-user", "arn:aws:iam::aws:policy/Drop");
|
||||
verify(iam).deleteUserPolicy("my-user", "drop-inline");
|
||||
verify(iam, never()).removeUserFromGroup("keep-group", "my-user");
|
||||
verify(iam, never()).detachUserPolicy("my-user", "arn:aws:iam::aws:policy/Keep");
|
||||
verify(iam, never()).deleteUserPolicy("my-user", "keep-inline");
|
||||
}
|
||||
|
||||
@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.getUser("my-user")).thenReturn(existing);
|
||||
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("my-user");
|
||||
r.getAttributes().put("__FlociUserId", "AIDAuser");
|
||||
|
||||
provisioner.provision(r, props("""
|
||||
{
|
||||
"UserName": "my-user",
|
||||
"Path": "/new-path/"
|
||||
}
|
||||
"""), updateCtx("my-user"));
|
||||
|
||||
verify(iam).updateUser("my-user", null, "/new-path/", "AIDAuser");
|
||||
}
|
||||
|
||||
@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.getUser("my-user")).thenReturn(replacement);
|
||||
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("my-user");
|
||||
r.getAttributes().put("__FlociUserId", "AIDAold-user");
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () ->
|
||||
provisioner.provision(r, props("""
|
||||
{
|
||||
"UserName": "my-user"
|
||||
}
|
||||
"""), updateCtx("my-user")));
|
||||
|
||||
assertEquals("EntityAlreadyExists", failure.getErrorCode());
|
||||
verify(iam, never()).addUserToGroup(any(), any());
|
||||
verify(iam, never()).attachUserPolicy(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedUpdateRestoresPriorInlinePolicyAndDetachesNewManagedPolicy() {
|
||||
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.getUser("my-user")).thenReturn(existing);
|
||||
doThrow(new AwsException("MalformedPolicyDocument", "bad policy", 400))
|
||||
.when(iam).putUserPolicy(eq("my-user"), eq("second"), any());
|
||||
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("my-user");
|
||||
r.getAttributes().put("__FlociUserId", "AIDAuser");
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
|
||||
{
|
||||
"UserName": "my-user",
|
||||
"ManagedPolicyArns": ["arn:aws:iam::aws:policy/NewPolicy"],
|
||||
"Policies": [
|
||||
{"PolicyName": "first", "PolicyDocument": {"Version": "2012-10-17", "Statement": []}},
|
||||
{"PolicyName": "second", "PolicyDocument": {"Version": "2012-10-17", "Statement": []}}
|
||||
]
|
||||
}
|
||||
"""), updateCtx("my-user")));
|
||||
|
||||
verify(iam).attachUserPolicy("my-user", "arn:aws:iam::aws:policy/NewPolicy");
|
||||
verify(iam).detachUserPolicy("my-user", "arn:aws:iam::aws:policy/NewPolicy");
|
||||
verify(iam).putUserPolicy("my-user", "first", priorDocument);
|
||||
verify(iam, never()).deleteUser("my-user");
|
||||
}
|
||||
}
|
||||
@@ -73,7 +73,7 @@ AWS::IAM::InstanceProfile LEGACY_SWITCH
|
||||
AWS::IAM::ManagedPolicy LEGACY_SWITCH
|
||||
AWS::IAM::Policy LEGACY_SWITCH
|
||||
AWS::IAM::Role IamRoleCfnProvisioner
|
||||
AWS::IAM::User LEGACY_SWITCH
|
||||
AWS::IAM::User IamUserCfnProvisioner
|
||||
AWS::IoT::DomainConfiguration IotDomainConfigurationCfnProvisioner
|
||||
AWS::IoT::Policy IotCfnProvisioner
|
||||
AWS::IoT::Thing IotCfnProvisioner
|
||||
|
||||
|
Reference in new issue
Block a user