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
This commit is contained in:
XuJian authored and GitHub committed 2026-09-21 22:26:32 -05:00
1 parent a5254defb6
commit bd40c21982
3 files changed
+166

No files matched your search

@@ -64,6 +64,7 @@ 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");
IamUser user;
boolean createdUser = false;
@@ -103,6 +104,21 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
Set<String> originalGroups = new HashSet<>(user.getGroupNames());
Set<String> originalPolicyArns = new HashSet<>(user.getAttachedPolicyArns());
Map<String, String> originalInlinePolicies = new HashMap<>(user.getInlinePolicies());
Map<String, String> originalTags = new HashMap<>(user.getTags());
Map<String, String> tagUpdates = new HashMap<>();
for (Map.Entry<String, String> entry : tags.entrySet()) {
if (!originalTags.containsKey(entry.getKey())
|| !entry.getValue().equals(originalTags.get(entry.getKey()))) {
tagUpdates.put(entry.getKey(), entry.getValue());
}
}
List<String> tagRemovals = new ArrayList<>();
for (String key : originalTags.keySet()) {
if (!tags.containsKey(key)) {
tagRemovals.add(key);
}
}
LinkedHashSet<String> groupsAddedByThisAttempt = new LinkedHashSet<>();
LinkedHashSet<String> groupsRemovedByThisAttempt = new LinkedHashSet<>();
@@ -110,6 +126,7 @@ public class IamUserCfnProvisioner implements CfnResourceProvisioner {
LinkedHashSet<String> detachedByThisAttempt = new LinkedHashSet<>();
LinkedHashSet<String> inlineWrittenByThisAttempt = new LinkedHashSet<>();
LinkedHashSet<String> 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<String> 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,
@@ -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("<Key>Environment</Key>"));
assertThat(createdTags, containsString("<Value>test</Value>"));
assertThat(createdTags, containsString("<Key>Owner</Key>"));
assertThat(createdTags, containsString("<Value>platform</Value>"));
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("<Key>Environment</Key>"));
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>")));
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);
}
@@ -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