From 19162f34231767b5df19c2e57e83fa683080acc0 Mon Sep 17 00:00:00 2001 From: Matheus Oliveira <99829531+omatheusmesmo@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:27:49 -0300 Subject: [PATCH] fix(cloudformation): attach the template tags to AWS::IAM::Role (#9270) --- docs/services/cloudformation.md | 10 + .../provisioners/CfnRollback.java | 27 ++- .../cloudformation/provisioners/Ec2Tags.java | 2 +- .../provisioners/IamRoleCfnProvisioner.java | 75 +++++++- ...udFormationIamRoleTagsIntegrationTest.java | 137 ++++++++++++++ .../IamRoleCfnProvisionerTest.java | 176 ++++++++++++++++++ .../cloudformation/writable-property-gaps.tsv | 1 - 7 files changed, 415 insertions(+), 13 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/cloudformation/CloudFormationIamRoleTagsIntegrationTest.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 7be0daa953..c133863a16 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -19,6 +19,16 @@ uses 3,600 seconds. Updates preserve the role's identity, and failed updates restore its previous duration. The limit controls new STS sessions without changing credentials already issued. +## IAM role tags + +`AWS::IAM::Role` attaches the template's `Tags` to the role on creation and +drives them to the template's set on update, which requires no interruption. A +tag a template declares that IAM refuses, such as a key or value outside +`TagRole`'s shape or more than 50 tags, fails the resource the way `CreateRole` +fails the whole request. An update takes out only the keys the stack applied, +so a tag added outside the stack stays, and a failed update puts the prior tags +of the touched keys back. + ## Supported Actions diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java index 311038d11d..ae537a4fe6 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java @@ -3,7 +3,6 @@ package io.floci.aws.services.cloudformation.provisioners; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.services.cloudformation.model.StackResource; import org.jboss.logging.Logger; @@ -13,6 +12,7 @@ import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.SortedSet; import java.util.TreeSet; import java.util.function.BiConsumer; import java.util.function.Consumer; @@ -638,14 +638,10 @@ public final class CfnRollback { */ public static void putTagSnapshot(ObjectNode snapshot, Collection managedKeys, Map current) { - ArrayNode tagKeys = snapshot.putArray("tagKeys"); + SortedSet keys = new TreeSet<>(managedKeys); + keys.forEach(snapshot.putArray("tagKeys")::add); ObjectNode tags = snapshot.putObject("tags"); - for (String key : new TreeSet<>(managedKeys)) { - tagKeys.add(key); - if (current.containsKey(key)) { - tags.put(key, current.get(key)); - } - } + valuesOf(current, keys).forEach(tags::put); } /** The tag keys {@link #putTagSnapshot} recorded as managed by the update. */ @@ -655,6 +651,21 @@ public final class CfnRollback { return keys; } + /** + * The values {@code current} holds for {@code keys}, in the keys' order: the one filter the tag + * snapshots and the IAM Role provisioner's failure cleanup all restore from, which keeps a + * key's null value as no value rather than the text "null". + */ + public static Map valuesOf(Map current, Collection keys) { + Map values = new LinkedHashMap<>(); + for (String key : keys) { + if (current.containsKey(key)) { + values.put(key, current.get(key)); + } + } + return values; + } + /** The tags {@link #putTagSnapshot} recorded, which are what the rollback puts back. */ public static Map snapshotTags(JsonNode snapshot) { Map tags = new LinkedHashMap<>(); diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/Ec2Tags.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/Ec2Tags.java index d953c7fa54..8d55839a54 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/Ec2Tags.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/Ec2Tags.java @@ -139,7 +139,7 @@ final class Ec2Tags { Set touched = touched(owned, desired); touched.forEach(snapshot.putArray("touched")::add); ObjectNode tags = snapshot.putObject("tags"); - touched.stream().filter(current::containsKey).forEach(key -> tags.put(key, current.get(key))); + CfnRollback.valuesOf(current, touched).forEach(tags::put); snapshot.put("tagKeys", priorRecord); } diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisioner.java index 16d7ab3a92..b7b013dae5 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisioner.java @@ -16,6 +16,7 @@ import jakarta.ws.rs.core.MultivaluedMap; 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; @@ -42,6 +43,7 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { private static final String INLINE_NAMES_ATTR = "__FlociInlinePolicyNames"; private static final String MANAGED_ARNS_ATTR = "__FlociManagedPolicyArns"; + private static final String TAG_KEYS_ATTR = "__FlociRoleTagKeys"; private final IamService iamService; @@ -94,9 +96,16 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { // same way it wins over one a CreateRole call names. String permissionsBoundary = ctx.delegatedRoleBoundaryArn() != null ? ctx.delegatedRoleBoundaryArn() : templateBoundary; + Map tags = ctx.resolveTags(props, "Tags"); + checkTemplateTags(resolvedRoleName, tags); IamRole role; boolean createdRole = false; + // Set only on the adoption path, to the tag state as it was before this attempt touched it: + // the keys the previous deployment recorded as the stack's, and the values the role held for + // them. Lets a later failure put them back, and drives the update to the template's tags. + Set ownedTagKeys = null; + Map priorRoleTags = null; // Set only on the adoption path, to the role's trust policy (and verified RoleId) as they // were before this attempt touched them. Lets a later failure (e.g. bad ManagedPolicyArns) // restore the trust policy below, so a rolled-back update doesn't leave it changed despite @@ -108,7 +117,7 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { String priorPermissionsBoundary = null; int priorMaxSessionDuration = 3600; try { - role = iamService.createRole(resolvedRoleName, path, assumeDoc, description, maxSessionDuration, Map.of(), + role = iamService.createRole(resolvedRoleName, path, assumeDoc, description, maxSessionDuration, tags, permissionsBoundary); createdRole = true; r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true"); @@ -140,7 +149,9 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { // write, closing the gap between the check above and this call: a role deleted and // recreated under the same name in between would otherwise silently receive an update // meant for the role this stack actually owns. - snapshotDuration(r, role); + ownedTagKeys = Ec2Tags.ownedKeys(r, TAG_KEYS_ATTR, ctx); + priorRoleTags = new LinkedHashMap<>(role.getTags()); + snapshotDuration(r, role, Ec2Tags.touched(ownedTagKeys, tags), priorRoleTags); priorAssumeRolePolicyDocument = role.getAssumeRolePolicyDocument(); priorAssumeRoleId = existingRoleId; priorPermissionsBoundary = role.getPermissionsBoundaryArn(); @@ -172,6 +183,9 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { final String roleIdToRestore = priorAssumeRoleId; final String boundaryToRestore = priorPermissionsBoundary; final int durationToRestore = priorMaxSessionDuration; + Set ownedTags = ownedTagKeys; + Map tagsToRestore = ownedTags == null + ? null : CfnRollback.valuesOf(priorRoleTags, Ec2Tags.touched(ownedTags, tags)); boolean boundaryChangedByThisAttempt = false; boolean durationChangedByThisAttempt = false; try { @@ -191,6 +205,13 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { boundaryChangedByThisAttempt = true; } + // Tags run inside the same protected block: on an update that adopts the role they are + // driven to what the template declares, untagging only the keys the previous execution + // recorded as the stack's, so a tag added outside the stack stays. + if (ownedTags != null) { + reconcileTags(resolvedRoleName, ownedTags, tags); + } + for (String policyArn : managedPolicyArns) { String canonicalArn = iamService.canonicalPolicyArn(policyArn); iamService.attachRolePolicy(resolvedRoleName, canonicalArn); @@ -312,6 +333,13 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { cleanupSucceeded = false; } } + if (ownedTags != null) { + if (!CfnRollback.attemptIamCleanup(failure, + "restore prior tags on role " + resolvedRoleName, + () -> reconcileTags(resolvedRoleName, Ec2Tags.touched(ownedTags, tags), tagsToRestore))) { + 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 @@ -337,9 +365,11 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { // What the next execution compares its template against. CfnTrackedSets.write(r, INLINE_NAMES_ATTR, inlineWrittenByThisAttempt); CfnTrackedSets.write(r, MANAGED_ARNS_ATTR, canonicalPolicyArns); + Ec2Tags.recordKeys(r, TAG_KEYS_ATTR, tags); } - private void snapshotDuration(StackResource resource, IamRole role) { + private void snapshotDuration(StackResource resource, IamRole role, Set managedTagKeys, + Map currentTags) { if (requiresUpdateRecovery(resource)) { return; } @@ -348,10 +378,45 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { snapshot.put("id", role.getRoleId()); snapshot.put("duration", role.getMaxSessionDuration()); snapshot.set("otherConfiguration", otherConfiguration(role)); + CfnRollback.putTagSnapshot(snapshot, managedTagKeys, currentTags); snapshot.set("attributes", MAPPER.valueToTree(resource.getAttributes())); resource.getAttributes().put(DURATION_SNAPSHOT_ATTR, snapshot.toString()); } + /** + * Holds the template's tags to the constraints IAM's {@code TagRole} request shape declares, the + * same reading a {@code TagRole} request gets: a key or value outside its pattern, or more tags + * than the 50 the list allows, fails the resource before anything exists, the way + * {@code CreateRole} fails the whole request when one tag is invalid. The per-role 50-tag quota + * itself stays with {@code createRole} and {@code tagRole}, which count the tags the role + * already carries. + */ + private void checkTemplateTags(String roleName, Map tags) { + if (tags.isEmpty()) { + return; + } + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("RoleName", roleName); + int index = 1; + for (Map.Entry tag : tags.entrySet()) { + String member = "Tags.member." + index; + params.putSingle(member + ".Key", tag.getKey()); + params.putSingle(member + ".Value", tag.getValue()); + index++; + } + IamRequestShapes.check("TagRole", params); + } + + /** + * Drives a role's tags to {@code desired} through the role's own {@code UntagRole} and + * {@code TagRole}: the one path an update and its rollback take. Only {@code managedKeys} + * absent from {@code desired} are removed, so a tag added outside the stack stays. + */ + private void reconcileTags(String roleName, Collection managedKeys, Map desired) { + CfnRollback.reconcileTags(managedKeys, desired, dropped -> iamService.untagRole(roleName, dropped), + added -> iamService.tagRole(roleName, added)); + } + private JsonNode otherConfiguration(IamRole role) { ObjectNode configuration = MAPPER.createObjectNode(); configuration.put("trust", role.getAssumeRolePolicyDocument()); @@ -375,6 +440,10 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { } IamRole role = iamService.updateRole(snapshot.path("name").asText(), null, snapshot.path("duration").asInt(), snapshot.path("id").asText()); + // Tags are put back from the snapshot the update took, like the duration: the touched keys + // that the role had get their prior value again, and one the update added is removed. + reconcileTags(snapshot.path("name").asText(), CfnRollback.snapshotTagKeys(snapshot), + CfnRollback.snapshotTags(snapshot)); // Duration rollback must not report success for trust or policy changes it did not undo. if (!snapshot.path("otherConfiguration").equals(otherConfiguration(role))) { return false; diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationIamRoleTagsIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationIamRoleTagsIntegrationTest.java new file mode 100644 index 0000000000..e69ddd4812 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationIamRoleTagsIntegrationTest.java @@ -0,0 +1,137 @@ +package io.floci.aws.services.cloudformation; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.CfnStackWaits; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.iam.IamClient; +import software.amazon.awssdk.services.iam.model.NoSuchEntityException; +import software.amazon.awssdk.services.iam.model.Tag; + +import java.net.URI; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * End-to-end check that CloudFormation attaches the {@code Tags} of an AWS::IAM::Role to the + * role (issue #9199): ListRoleTags returns them after a create, an update drives them to the + * template's set while keeping a tag added out of band, and a failed update puts the prior + * tags back. + */ +@QuarkusTest +class CloudFormationIamRoleTagsIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + private final String name = "cfn-role-tags-" + UUID.randomUUID(); + private final ObjectMapper mapper = new ObjectMapper(); + private CloudFormationClient cfn; + private IamClient iam; + private boolean stackCreated; + + @TestHTTPResource + URI endpoint; + + @BeforeEach + void clients() { + cfn = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.EU_WEST_1, endpoint); + iam = AwsTestClients.create(IamClient.builder(), "test", Region.EU_WEST_1, endpoint); + } + + @AfterEach + void removeThisTestsStack() { + try { + if (stackCreated) { + cfn.deleteStack(request -> request.stackName(name)); + await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> + assertThrows(NoSuchEntityException.class, + () -> iam.getRole(request -> request.roleName(name)))); + } + } finally { + iam.close(); + cfn.close(); + } + } + + @Test + void createAttachesTheTemplateTagsToTheRole() { + create(Map.of("team", "payments")); + assertEquals(Map.of("team", "payments"), roleTags()); + } + + @Test + void updateDrivesTheTagsToTheTemplateSetAndKeepsOneAddedOutOfBand() { + create(Map.of("team", "payments")); + update(Map.of("team", "new-value", "env", "prod"), false); + assertEquals(Map.of("team", "new-value", "env", "prod"), roleTags()); + + iam.tagRole(request -> request.roleName(name).tags( + Tag.builder().key("extra").value("mine").build())); + update(Map.of("team", "older"), false); + Map tags = roleTags(); + assertEquals("older", tags.get("team")); + assertEquals("mine", tags.get("extra")); + assertFalse(tags.containsKey("env")); + } + + @Test + void failedUpdateRestoresThePriorTags() { + create(Map.of("team", "prior")); + update(Map.of("team", "new"), true); + assertEquals(Map.of("team", "prior"), roleTags()); + } + + private void create(Map tags) { + cfn.createStack(request -> request.stackName(name).templateBody(template(tags, false)) + .capabilitiesWithStrings("CAPABILITY_NAMED_IAM")); + stackCreated = true; + CfnStackWaits.awaitStatus(cfn, name, "CREATE_COMPLETE"); + } + + private void update(Map tags, boolean missingManagedPolicy) { + cfn.updateStack(request -> request.stackName(name).templateBody(template(tags, missingManagedPolicy)) + .capabilitiesWithStrings("CAPABILITY_NAMED_IAM")); + CfnStackWaits.awaitStatus(cfn, name, missingManagedPolicy ? "UPDATE_ROLLBACK_COMPLETE" : "UPDATE_COMPLETE"); + } + + private Map roleTags() { + List tags = iam.listRoleTags(request -> request.roleName(name)).tags(); + Map byKey = new LinkedHashMap<>(); + tags.forEach(tag -> byKey.put(tag.key(), tag.value())); + return byKey; + } + + private String template(Map tags, boolean missingManagedPolicy) { + ObjectNode template = mapper.createObjectNode(); + ObjectNode properties = template.putObject("Resources").putObject("Role") + .put("Type", "AWS::IAM::Role").putObject("Properties"); + properties.put("RoleName", name); + ObjectNode trust = properties.putObject("AssumeRolePolicyDocument").put("Version", "2012-10-17"); + trust.putArray("Statement").addObject().put("Effect", "Allow").put("Action", "sts:AssumeRole") + .putObject("Principal").put("AWS", "arn:aws:iam::" + ACCOUNT + ":root"); + if (tags != null) { + ArrayNode declared = properties.putArray("Tags"); + tags.forEach((key, value) -> declared.addObject().put("Key", key).put("Value", value)); + } + if (missingManagedPolicy) { + properties.putArray("ManagedPolicyArns").add("arn:aws:iam::" + ACCOUNT + ":policy/missing-" + name); + } + return template.toString(); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java index 46768c727b..1d1783169d 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java @@ -16,6 +16,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import java.util.HashMap; +import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -26,6 +27,8 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.AdditionalAnswers.returnsFirstArg; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; @@ -522,6 +525,179 @@ class IamRoleCfnProvisionerTest { assertEquals("arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", r.getAttributes().get("Arn")); } + @Test + void createPassesTheTemplateTagsToTheRole() { + StackResource r = resource(); + when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), + eq(Map.of("team", "payments")), any())).thenReturn(new IamRole("AROAapp-role", "app-role", "/", + "arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST)); + + provisioner.provision(r, props(""" + {"RoleName": "app-role", "Tags": [{"Key": "team", "Value": "payments"}]} + """), ctx()); + + assertEquals("arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", r.getAttributes().get("Arn")); + assertEquals("[\"team\"]", r.getAttributes().get("__FlociRoleTagKeys")); + } + + @Test + void aTagTheTagRoleShapeRefusesFailsTheResourceBeforeTheRoleExists() { + // CreateRole fails the whole request when one tag is invalid, so the check runs before + // anything is created rather than after the role exists. + AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(resource(), + props(""" + {"RoleName": "app-role", + "Tags": [{"Key": "team", "Value": "payments"}, {"Key": "bad!key", "Value": "v"}]} + """), ctx())); + + assertEquals("ValidationError", failure.getErrorCode()); + verifyNoInteractions(iam); + } + + @Test + void moreTagsThanTheTagRoleShapeAllowsFailTheResourceBeforeTheRoleExists() { + StringBuilder tags = new StringBuilder("["); + for (int i = 0; i < 51; i++) { + if (i > 0) { + tags.append(','); + } + tags.append("{\"Key\":\"key-").append(i).append("\",\"Value\":\"v\"}"); + } + tags.append(']'); + + AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(resource(), + props("{\"RoleName\": \"app-role\", \"Tags\":" + tags + "}"), ctx())); + + assertEquals("ValidationError", failure.getErrorCode()); + verifyNoInteractions(iam); + } + + @Test + void updateDrivesTheTagsToWhatTheTemplateDeclares() { + // Tags is a no-interruption update: the template's set is applied, a key the template + // dropped is taken off the role, and a tag added out of band stays. + IamRole existing = new IamRole("AROAapp-role", "app-role", "/", + "arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST); + existing.getTags().put("team", "old-value"); + existing.getTags().put("drop", "goes"); + existing.getTags().put("extra", "mine"); + when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), + eq(Map.of("team", "payments", "keep", "stays")), 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"); + r.getAttributes().put("__FlociRoleTagKeys", "[\"team\",\"drop\"]"); + + provisioner.provision(r, props(""" + {"RoleName": "app-role", + "Tags": [{"Key": "team", "Value": "payments"}, {"Key": "keep", "Value": "stays"}]} + """), ctx()); + + verify(iam).untagRole("app-role", List.of("drop")); + verify(iam, never()).untagRole("app-role", List.of("extra")); + verify(iam).tagRole("app-role", Map.of("team", "payments", "keep", "stays")); + assertEquals("[\"team\",\"keep\"]", r.getAttributes().get("__FlociRoleTagKeys")); + } + + @Test + void updateLeavesTagsTheStackNeverWroteAlone() { + IamRole existing = new IamRole("AROAapp-role", "app-role", "/", + "arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST); + existing.getTags().put("extra", "mine"); + 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"); + + provisioner.provision(r, props(""" + {"RoleName": "app-role"} + """), ctx()); + + verify(iam, never()).untagRole(anyString(), anyList()); + verify(iam, never()).tagRole(anyString(), anyMap()); + } + + @Test + void failedUpdateRestoresThePriorTags() { + IamRole existing = new IamRole("AROAapp-role", "app-role", "/", + "arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST); + existing.getTags().put("team", "prior"); + when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), eq(Map.of("team", "new")), any())) + .thenThrow(new AwsException("EntityAlreadyExists", "exists", 409)); + when(iam.getRole("app-role")).thenReturn(existing); + doThrow(new AwsException("NoSuchEntity", "missing policy", 404)) + .when(iam).attachRolePolicy("app-role", "arn:aws:iam::aws:policy/Missing"); + + StackResource r = resource(); + r.setPhysicalId("app-role"); + r.getAttributes().put("RoleId", "AROAapp-role"); + + assertThrows(AwsException.class, () -> provisioner.provision(r, props(""" + {"RoleName": "app-role", "Tags": [{"Key": "team", "Value": "new"}], + "ManagedPolicyArns": ["arn:aws:iam::aws:policy/Missing"]} + """), ctx())); + + InOrder order = inOrder(iam); + order.verify(iam).tagRole("app-role", Map.of("team", "new")); + order.verify(iam).tagRole("app-role", Map.of("team", "prior")); + verify(iam, never()).untagRole(anyString(), anyList()); + verify(iam, never()).deleteRole(anyString()); + } + + @Test + void failedUpdateReconcilesOffTheKeysThisUpdateAdded() { + IamRole existing = new IamRole("AROAapp-role", "app-role", "/", + "arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST); + existing.getTags().put("team", "prior"); + existing.getTags().put("out-of-band", "theirs"); + when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), + eq(Map.of("team", "new", "env", "prod")), any())) + .thenThrow(new AwsException("EntityAlreadyExists", "exists", 409)); + when(iam.getRole("app-role")).thenReturn(existing); + doThrow(new AwsException("NoSuchEntity", "missing policy", 404)) + .when(iam).attachRolePolicy("app-role", "arn:aws:iam::aws:policy/Missing"); + + StackResource r = resource(); + r.setPhysicalId("app-role"); + r.getAttributes().put("RoleId", "AROAapp-role"); + + assertThrows(AwsException.class, () -> provisioner.provision(r, props(""" + {"RoleName": "app-role", "Tags": [{"Key": "team", "Value": "new"}, + {"Key": "env", "Value": "prod"}], + "ManagedPolicyArns": ["arn:aws:iam::aws:policy/Missing"]} + """), ctx())); + + verify(iam).untagRole("app-role", List.of("env")); + verify(iam).tagRole("app-role", Map.of("team", "prior")); + verify(iam, never()).untagRole("app-role", List.of("out-of-band")); + } + + @Test + void stackRollbackRestoresThePriorTags() throws Exception { + IamService realIam = IamServiceTestHelper.iamServiceWithUserPolicy("test", "secret", "user", EMPTY_TRUST); + IamRoleCfnProvisioner owner = new IamRoleCfnProvisioner(realIam); + StackResource r = resource(); + owner.provision(r, props( + "{\"RoleName\":\"app-role\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"prior\"}]}"), ctx()); + Map originalAttributes = new HashMap<>(r.getAttributes()); + owner.provision(r, props("{\"RoleName\":\"app-role\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"new\"}," + + "{\"Key\":\"env\",\"Value\":\"prod\"}]}"), ctx()); + assertEquals(Map.of("team", "new", "env", "prod"), realIam.listRoleTags("app-role")); + + ObjectMapper storageMapper = new ObjectMapper().findAndRegisterModules(); + StackResource restored = storageMapper.readValue(storageMapper.writeValueAsString(r), StackResource.class); + assertTrue(owner.rollbackUpdate(restored)); + assertEquals(Map.of("team", "prior"), realIam.listRoleTags("app-role")); + assertEquals(originalAttributes, restored.getAttributes()); + assertFalse(owner.rollbackUpdate(restored)); + } + @Test void updateAppliesAChangedPermissionsBoundary() { StackResource r = adoptExistingRole(BOUNDARY_OLD); diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index dad56351e7..3fa8deac97 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -363,7 +363,6 @@ AWS::IAM::ManagedPolicy Description accepted and ignored AWS::IAM::ManagedPolicy Path accepted and ignored AWS::IAM::ManagedPolicy PolicyDocument accepted and ignored AWS::IAM::Policy PolicyDocument accepted and ignored -AWS::IAM::Role Tags accepted and ignored AWS::IAM::User LoginProfile documented as ignored (docs/services/cloudformation.md, IAM) AWS::KMS::Key BypassPolicyLockoutSafetyCheck accepted and ignored AWS::KMS::Key PendingWindowInDays accepted and ignored