From bd40c21982fcd5240219dc5e0d8684b0e373da75 Mon Sep 17 00:00:00 2001 From: XuJian <265865031+xujiantop-crypto@users.noreply.github.com> Date: Tue, 22 Sep 2026 12:26:32 +0900 Subject: [PATCH] fix(cloudformation): apply IAM user tags (#4010) AWS::IAM::User now applies its declared Tags on create and reconciles them on update (added, changed and removed keys against the prior set), restoring the prior tags through CfnRollback on failure. Closes #3998 --- .../provisioners/IamUserCfnProvisioner.java | 43 +++++++++++ .../CloudFormationIamUserIntegrationTest.java | 77 +++++++++++++++++++ .../IamUserCfnProvisionerTest.java | 46 +++++++++++ 3 files changed, 166 insertions(+) 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 2a39cd0847..091971270d 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 @@ -64,6 +64,7 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner { List managedPolicyArns = ctx.resolveStringList(props, "ManagedPolicyArns"); List groups = ctx.resolveStringList(props, "Groups"); + Map tags = ctx.resolveTags(props, "Tags"); IamUser user; boolean createdUser = false; @@ -103,6 +104,21 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner { Set originalGroups = new HashSet<>(user.getGroupNames()); Set originalPolicyArns = new HashSet<>(user.getAttachedPolicyArns()); Map originalInlinePolicies = new HashMap<>(user.getInlinePolicies()); + Map originalTags = new HashMap<>(user.getTags()); + + Map tagUpdates = new HashMap<>(); + for (Map.Entry entry : tags.entrySet()) { + if (!originalTags.containsKey(entry.getKey()) + || !entry.getValue().equals(originalTags.get(entry.getKey()))) { + tagUpdates.put(entry.getKey(), entry.getValue()); + } + } + List tagRemovals = new ArrayList<>(); + for (String key : originalTags.keySet()) { + if (!tags.containsKey(key)) { + tagRemovals.add(key); + } + } LinkedHashSet groupsAddedByThisAttempt = new LinkedHashSet<>(); LinkedHashSet groupsRemovedByThisAttempt = new LinkedHashSet<>(); @@ -110,6 +126,7 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner { LinkedHashSet detachedByThisAttempt = new LinkedHashSet<>(); LinkedHashSet inlineWrittenByThisAttempt = new LinkedHashSet<>(); LinkedHashSet inlineRemovedByThisAttempt = new LinkedHashSet<>(); + boolean tagMutationStarted = false; final String pathToRestore = priorPath; final String userIdToRestore = priorUserId; @@ -168,9 +185,35 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner { groupsRemovedByThisAttempt.add(stale); } } + if (!tagUpdates.isEmpty() || !tagRemovals.isEmpty()) { + tagMutationStarted = true; + if (!tagUpdates.isEmpty()) { + iamService.tagUser(resolvedUserName, tagUpdates); + } + if (!tagRemovals.isEmpty()) { + iamService.untagUser(resolvedUserName, tagRemovals); + } + } } catch (RuntimeException failure) { boolean cleanupSucceeded = true; + if (tagMutationStarted) { + List introducedTagKeys = new ArrayList<>(tags.keySet()); + introducedTagKeys.removeAll(originalTags.keySet()); + if (!introducedTagKeys.isEmpty() + && !CfnRollback.attemptIamCleanup(failure, + "remove newly applied tags from user " + resolvedUserName, + () -> iamService.untagUser(resolvedUserName, introducedTagKeys))) { + cleanupSucceeded = false; + } + if (!originalTags.isEmpty() + && !CfnRollback.attemptIamCleanup(failure, + "restore prior tags on user " + resolvedUserName, + () -> iamService.tagUser(resolvedUserName, originalTags))) { + cleanupSucceeded = false; + } + } + for (String groupName : groupsRemovedByThisAttempt) { if (!CfnRollback.attemptIamCleanup(failure, "re-add user " + resolvedUserName + " to group " + groupName, 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 880dd32a7a..5e0644c56f 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 @@ -349,6 +349,69 @@ class CloudFormationIamUserIntegrationTest { awaitStackStatus(stackId, "DELETE_COMPLETE"); } + @Test + void createAndUpdateStackReconcilesUserTags() throws InterruptedException { + String suffix = Long.toString(System.nanoTime(), 36); + String userName = "tagged-user-" + suffix; + String stackName = "cfn-tagged-user-stack-" + suffix; + + String createTemplate = """ + { + "Resources": { + "TaggedUser": { + "Type": "AWS::IAM::User", + "Properties": { + "UserName": "%s", + "Tags": [ + {"Key": "Environment", "Value": "test"}, + {"Key": "Owner", "Value": "platform"} + ] + } + } + } + } + """.formatted(userName); + + String stackId = createStack(stackName, createTemplate); + awaitStackStatus(stackId, "CREATE_COMPLETE"); + + String createdTags = listUserTags(userName); + assertThat(createdTags, containsString("Environment")); + assertThat(createdTags, containsString("test")); + assertThat(createdTags, containsString("Owner")); + assertThat(createdTags, containsString("platform")); + + String updateTemplate = """ + { + "Resources": { + "TaggedUser": { + "Type": "AWS::IAM::User", + "Properties": { + "UserName": "%s", + "Tags": [ + {"Key": "Environment", "Value": "production"}, + {"Key": "Team", "Value": "identity"} + ] + } + } + } + } + """.formatted(userName); + + updateStack(stackName, updateTemplate); + awaitStackStatus(stackId, "UPDATE_COMPLETE"); + + String updatedTags = listUserTags(userName); + assertThat(updatedTags, containsString("Environment")); + assertThat(updatedTags, containsString("production")); + assertThat(updatedTags, containsString("Team")); + assertThat(updatedTags, containsString("identity")); + assertThat(updatedTags, org.hamcrest.Matchers.not(containsString("Owner"))); + + deleteStack(stackName); + awaitStackStatus(stackId, "DELETE_COMPLETE"); + } + private static String createStack(String stackName, String template) { return cfnQuery("CreateStack", stackName, template) .then() @@ -387,6 +450,20 @@ class CloudFormationIamUserIntegrationTest { return cfnQuery("DescribeStacks", stackId).then().statusCode(200).extract().asString(); } + private static String listUserTags(String userName) { + return given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "ListUserTags") + .formParam("UserName", userName) + .when() + .post("/") + .then() + .statusCode(200) + .extract() + .asString(); + } + private static Response cfnQuery(String action, String stackName) { return cfnQuery(action, stackName, null); } 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 a1306b16b3..1472ee123e 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 @@ -148,6 +148,10 @@ class IamUserCfnProvisionerTest { { "UserName": "app-user", "Groups": ["developers", "qa"], + "Tags": [ + {"Key": "Environment", "Value": "test"}, + {"Key": "Owner", "Value": "platform"} + ], "ManagedPolicyArns": [ "arn:aws:iam::aws:policy/ReadOnlyAccess", "arn:aws:iam::aws:policy/PowerUserAccess" @@ -166,6 +170,7 @@ class IamUserCfnProvisionerTest { 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()); + verify(iam).tagUser("app-user", Map.of("Environment", "test", "Owner", "platform")); } @Test @@ -248,6 +253,9 @@ class IamUserCfnProvisionerTest { existing.getAttachedPolicyArns().add("arn:aws:iam::aws:policy/Drop"); existing.getInlinePolicies().put("keep-inline", "{}"); existing.getInlinePolicies().put("drop-inline", "{}"); + existing.getTags().put("keep-tag", "same"); + 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.getUser("my-user")).thenReturn(existing); @@ -264,6 +272,11 @@ class IamUserCfnProvisionerTest { "UserName": "my-user", "Groups": ["keep-group"], "ManagedPolicyArns": ["arn:aws:iam::aws:policy/Keep"], + "Tags": [ + {"Key": "keep-tag", "Value": "same"}, + {"Key": "update-tag", "Value": "new"}, + {"Key": "add-tag", "Value": "added"} + ], "Policies": [ { "PolicyName": "keep-inline", @@ -279,6 +292,39 @@ class IamUserCfnProvisionerTest { 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"); + verify(iam).tagUser("my-user", Map.of("update-tag", "new", "add-tag", "added")); + verify(iam).untagUser("my-user", List.of("drop-tag")); + } + + @Test + void failedTagReconciliationRestoresPriorTags() { + 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("/"))) + .thenThrow(new AwsException("EntityAlreadyExists", "exists", 409)); + when(iam.getUser("my-user")).thenReturn(existing); + doThrow(new AwsException("ServiceFailure", "tag removal failed", 500)) + .when(iam).untagUser("my-user", List.of("drop-tag")); + + StackResource r = resource(); + r.setPhysicalId("my-user"); + r.getAttributes().put("__FlociUserId", "AIDAuser"); + + assertThrows(AwsException.class, () -> provisioner.provision(r, props(""" + { + "UserName": "my-user", + "Tags": [ + {"Key": "keep-tag", "Value": "new"}, + {"Key": "add-tag", "Value": "added"} + ] + } + """), updateCtx("my-user"))); + + verify(iam).tagUser("my-user", Map.of("keep-tag", "new", "add-tag", "added")); + verify(iam).untagUser("my-user", List.of("drop-tag")); + verify(iam).untagUser("my-user", List.of("add-tag")); + verify(iam).tagUser("my-user", Map.of("keep-tag", "old", "drop-tag", "restore-me")); } @Test