fix(cloudformation): attach the template tags to AWS::IAM::Role (#9270)

This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-11-26 20:27:49 -04:00
1 parent febdf59f2d
commit 19162f3423
7 files changed
+415 -13

No files matched your search

+10
View File
@@ -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
<!-- floci:actions:start -->
@@ -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<String> managedKeys,
Map<String, String> current) {
ArrayNode tagKeys = snapshot.putArray("tagKeys");
SortedSet<String> 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<String, String> valuesOf(Map<String, String> current, Collection<String> keys) {
Map<String, String> 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<String, String> snapshotTags(JsonNode snapshot) {
Map<String, String> tags = new LinkedHashMap<>();
@@ -139,7 +139,7 @@ final class Ec2Tags {
Set<String> 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);
}
@@ -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<String, String> 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<String> ownedTagKeys = null;
Map<String, String> 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<String> ownedTags = ownedTagKeys;
Map<String, String> 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<String> managedTagKeys,
Map<String, String> 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<String, String> tags) {
if (tags.isEmpty()) {
return;
}
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("RoleName", roleName);
int index = 1;
for (Map.Entry<String, String> 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<String> managedKeys, Map<String, String> 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;
@@ -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<String, String> 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<String, String> 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<String, String> 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<String, String> roleTags() {
List<Tag> tags = iam.listRoleTags(request -> request.roleName(name)).tags();
Map<String, String> byKey = new LinkedHashMap<>();
tags.forEach(tag -> byKey.put(tag.key(), tag.value()));
return byKey;
}
private String template(Map<String, String> 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();
}
}
@@ -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<String, String> 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);
@@ -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
1 AWS::ApiGateway::ApiKey StageKeys accepted and ignored, as the ApiGatewayApiKeyCfnProvisioner javadoc records
363 AWS::IAM::ManagedPolicy Path accepted and ignored
364 AWS::IAM::ManagedPolicy PolicyDocument accepted and ignored
365 AWS::IAM::Policy PolicyDocument accepted and ignored
AWS::IAM::Role Tags accepted and ignored
366 AWS::IAM::User LoginProfile documented as ignored (docs/services/cloudformation.md, IAM)
367 AWS::KMS::Key BypassPolicyLockoutSafetyCheck accepted and ignored
368 AWS::KMS::Key PendingWindowInDays accepted and ignored