fix(cloudformation): reconcile and replace IAM leaf resources on update and delete (#3933)

Follow-up to #3913 addressing pgermosen's review of the IAM leaf provisioners.

AWS::IAM::AccessKey: UserName and Serial are both createOnly, so an update that changes neither reuses the existing key (a user is capped at two keys, so recreating on every update failed with LimitExceeded and orphaned the earlier keys), and a change to either rotates the key by replacement, creating a new one and deleting the displaced one after the update commits through ReplacementCleanup, matching how AWS rotates a key by incrementing Serial. A missing UserName is rejected. Delete recovers the owning user from the key id (findUserNameByAccessKeyId), so both the stack-delete and the replacement-cleanup paths delete by physical id alone.

AWS::IAM::InstanceProfile: Roles is a no-interruption update, so the declared roles are reconciled in place (undeclared roles removed, then declared roles added) instead of only ever added, which had made a role swap fail with LimitExceeded. A missing Roles is rejected (AWS requires it), and a Path change on an existing profile is rejected as an unsupported replacement rather than silently ignored, since Path is createOnly and a same-named profile cannot be replaced in place. Roles are detached before delete because IAM refuses to delete a profile that still holds one.

Known edge: ReplacementCleanup.rollback restores only non-internal attributes, so after a rolled-back key rotation the stored Serial can lag by one; the next update re-evaluates. Full InstanceProfile name-plus-path replacement and AccessKey Status handling remain follow-ups.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-19 22:03:28 -04:00
1 parent d9a4db0290
commit 3a36b8c85c
5 files changed
+371 -72

No files matched your search

@@ -29,6 +29,7 @@ class CloudFormationIamLeafIntegrationTest {
void createStackProvisionsAccessKeyAndInstanceProfile() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String userName = "leaf-user-" + suffix;
String roleName = "leaf-role-" + suffix;
String profileName = "leaf-profile-" + suffix;
String stackName = "cfn-iam-leaf-" + suffix;
@@ -43,9 +44,19 @@ class CloudFormationIamLeafIntegrationTest {
"Type": "AWS::IAM::AccessKey",
"Properties": {"UserName": {"Ref": "User"}}
},
"Role": {
"Type": "AWS::IAM::Role",
"Properties": {
"RoleName": "%s",
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Principal": {"Service": "ec2.amazonaws.com"}, "Action": "sts:AssumeRole"}]
}
}
},
"Profile": {
"Type": "AWS::IAM::InstanceProfile",
"Properties": {"InstanceProfileName": "%s"}
"Properties": {"InstanceProfileName": "%s", "Roles": [{"Ref": "Role"}]}
}
},
"Outputs": {
@@ -54,7 +65,7 @@ class CloudFormationIamLeafIntegrationTest {
"ProfileArn": {"Value": {"Fn::GetAtt": ["Profile", "Arn"]}}
}
}
""".formatted(userName, profileName);
""".formatted(userName, roleName, profileName);
String stackId = createStack(stackName, template);
awaitStackStatus(stackId, "CREATE_COMPLETE");
@@ -2,6 +2,7 @@ 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;
@@ -9,22 +10,29 @@ import io.github.hectorvent.floci.services.iam.model.AccessKey;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Set;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.anyString;
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.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* {@code AWS::IAM::AccessKey} in isolation: the id backs Ref and Fn::GetAtt, the secret is
* published, and an absent UserName creates nothing.
* {@code AWS::IAM::AccessKey} in isolation: the id backs Ref and Fn::GetAtt, an unchanged update
* reuses the key, a Serial bump rotates it by replacement, a missing UserName is rejected, and
* delete removes the key by recovering the owning user from the id.
*/
class IamAccessKeyCfnProvisionerTest {
private static final String TYPE = "AWS::IAM::AccessKey";
private static final String SERIAL_ATTR = "__FlociAccessKeySerial";
private final IamService iam = mock(IamService.class);
private final IamAccessKeyCfnProvisioner provisioner = new IamAccessKeyCfnProvisioner(iam);
@@ -33,35 +41,97 @@ class IamAccessKeyCfnProvisionerTest {
@Test
void publishesTheIdAndSecret() throws Exception {
AccessKey key = new AccessKey();
key.setAccessKeyId("AKIA123");
key.setSecretAccessKey("secret-xyz");
key.setAccessKeyId("AKIA1");
key.setSecretAccessKey("secret-1");
when(iam.createAccessKey("alice")).thenReturn(key);
StackResource r = resource();
provisioner.provision(r, props("{\"UserName\": \"alice\"}"), ctx());
provisioner.provision(r, props("{\"UserName\": \"alice\"}"), ctx(null));
assertEquals("AKIA123", r.getPhysicalId());
assertEquals(Set.of("Id", "SecretAccessKey"), r.getAttributes().keySet());
assertEquals("AKIA123", r.getAttributes().get("Id"));
assertEquals("secret-xyz", r.getAttributes().get("SecretAccessKey"));
assertEquals("AKIA1", r.getPhysicalId());
assertEquals("AKIA1", r.getAttributes().get("Id"));
assertEquals("secret-1", r.getAttributes().get("SecretAccessKey"));
verify(iam).createAccessKey("alice");
}
@Test
void absentUserNameCreatesNothing() throws Exception {
void missingUserNameIsRejected() {
StackResource r = resource();
provisioner.provision(r, props("{}"), ctx());
verifyNoInteractions(iam);
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.provision(r, props("{}"), ctx(null)));
assertEquals("ValidationError", failure.getErrorCode());
verify(iam, never()).createAccessKey(anyString());
}
private ProvisionContext ctx() {
@Test
void anUnchangedUpdateReusesTheExistingKey() throws Exception {
StackResource r = resource();
r.setPhysicalId("AKIA1");
r.getAttributes().put("Id", "AKIA1");
r.getAttributes().put("SecretAccessKey", "secret-1");
r.getAttributes().put(SERIAL_ATTR, "");
when(iam.findUserNameByAccessKeyId("AKIA1")).thenReturn(Optional.of("alice"));
provisioner.provision(r, props("{\"UserName\": \"alice\"}"), ctx("AKIA1"));
assertEquals("AKIA1", r.getPhysicalId());
verify(iam, never()).createAccessKey(anyString());
}
@Test
void bumpingSerialOnUpdateRotatesTheKey() throws Exception {
StackResource r = resource();
r.setPhysicalId("AKIA1");
r.getAttributes().put("Id", "AKIA1");
r.getAttributes().put(SERIAL_ATTR, "1");
when(iam.findUserNameByAccessKeyId("AKIA1")).thenReturn(Optional.of("alice"));
AccessKey rotated = new AccessKey();
rotated.setAccessKeyId("AKIA2");
rotated.setSecretAccessKey("secret-2");
when(iam.createAccessKey("alice")).thenReturn(rotated);
provisioner.provision(r, props("{\"UserName\": \"alice\", \"Serial\": 2}"), ctx("AKIA1"));
assertEquals("AKIA2", r.getPhysicalId());
verify(iam).createAccessKey("alice");
assertTrue(provisioner.hasReplacementUpdate(r));
assertEquals("AKIA1", provisioner.updateCleanupPhysicalId(r));
}
@Test
void deleteRemovesTheKeyRecoveringUserFromId() {
when(iam.findUserNameByAccessKeyId("AKIA1")).thenReturn(Optional.of("alice"));
provisioner.delete(TYPE, "AKIA1", "us-east-1");
verify(iam).deleteAccessKey("alice", "AKIA1");
}
@Test
void deleteToleratesAKeyAlreadyGone() {
when(iam.findUserNameByAccessKeyId("AKIA1")).thenReturn(Optional.of("alice"));
doThrow(new AwsException("NoSuchEntity", "gone", 404))
.when(iam).deleteAccessKey("alice", "AKIA1");
assertDoesNotThrow(() -> provisioner.delete(TYPE, "AKIA1", "us-east-1"));
}
@Test
void deleteSkipsWhenTheKeyIsUnknown() {
when(iam.findUserNameByAccessKeyId("AKIA1")).thenReturn(Optional.empty());
provisioner.delete(TYPE, "AKIA1", "us-east-1");
verify(iam, never()).deleteAccessKey(anyString(), anyString());
}
private ProvisionContext ctx(String priorPhysicalId) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null ? null : node.asText();
});
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);
}
private JsonNode props(String json) throws Exception {
@@ -9,7 +9,9 @@ import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
@@ -20,12 +22,16 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* {@code AWS::IAM::InstanceProfile} in isolation: Ref is the name, Fn::GetAtt Arn is the arn, the
* generated name, the synthesized-arn fallback on a create collision, and the delete tolerance.
* {@code AWS::IAM::InstanceProfile} in isolation: Ref is the name, Fn::GetAtt Arn is the arn, Path
* and Roles are applied, a role swap reconciles in place, a missing Roles or a createOnly change
* (name, path) is rejected, and delete detaches roles before removing the profile.
*/
class IamInstanceProfileCfnProvisionerTest {
@@ -36,60 +42,135 @@ class IamInstanceProfileCfnProvisionerTest {
private final ObjectMapper mapper = new ObjectMapper();
@Test
void publishesNameAndArn() throws Exception {
InstanceProfile profile = new InstanceProfile();
profile.setArn("arn:aws:iam::000000000000:instance-profile/web");
when(iam.createInstanceProfile("web", "/")).thenReturn(profile);
void publishesNameArnAndAttachesTheRole() throws Exception {
when(iam.createInstanceProfile("web", "/")).thenReturn(profile("web", "/"));
StackResource r = resource();
provisioner.provision(r, props("{\"InstanceProfileName\": \"web\"}"), ctx());
provisioner.provision(r, props("""
{"InstanceProfileName": "web", "Roles": ["app-role"]}
"""), ctx(null));
assertEquals("web", r.getPhysicalId());
assertEquals(Set.of("Arn"), r.getAttributes().keySet());
assertEquals("arn:aws:iam::000000000000:instance-profile/web", r.getAttributes().get("Arn"));
verify(iam).addRoleToInstanceProfile("web", "app-role");
}
@Test
void appliesTheDeclaredPath() throws Exception {
when(iam.createInstanceProfile("web", "/team/")).thenReturn(profile("web", "/team/"));
StackResource r = resource();
provisioner.provision(r, props("""
{"InstanceProfileName": "web", "Path": "/team/", "Roles": ["app-role"]}
"""), ctx(null));
verify(iam).createInstanceProfile("web", "/team/");
verify(iam).addRoleToInstanceProfile("web", "app-role");
}
@Test
void absentNameIsGeneratedFromStackAndLogicalId() throws Exception {
InstanceProfile profile = new InstanceProfile();
profile.setArn("arn:aws:iam::000000000000:instance-profile/generated");
when(iam.createInstanceProfile(anyString(), eq("/"))).thenReturn(profile);
when(iam.createInstanceProfile(anyString(), eq("/"))).thenReturn(profile("generated", "/"));
StackResource r = resource();
provisioner.provision(r, props("{}"), ctx());
provisioner.provision(r, props("{\"Roles\": [\"app-role\"]}"), ctx(null));
assertTrue(r.getPhysicalId().matches("my-stack-Profile-[0-9a-f]{12}"), r.getPhysicalId());
}
@Test
void aCreateCollisionFallsBackToASynthesizedArn() throws Exception {
void missingRolesIsRejected() {
StackResource r = resource();
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.provision(r, props("{\"InstanceProfileName\": \"web\"}"), ctx(null)));
assertEquals("ValidationError", failure.getErrorCode());
verify(iam, never()).createInstanceProfile(anyString(), anyString());
}
@Test
void changingTheRoleOnUpdateSwapsItInPlace() throws Exception {
InstanceProfile existing = profile("web", "/");
existing.getRoleNames().add("old-role");
when(iam.createInstanceProfile("web", "/"))
.thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
when(iam.getInstanceProfile("web")).thenReturn(existing);
StackResource r = resource();
r.setPhysicalId("web");
provisioner.provision(r, props("""
{"InstanceProfileName": "web", "Roles": ["new-role"]}
"""), ctx("web"));
org.mockito.InOrder order = inOrder(iam);
order.verify(iam).removeRoleFromInstanceProfile("web", "old-role");
order.verify(iam).addRoleToInstanceProfile("web", "new-role");
}
@Test
void changingThePathOnUpdateIsRejected() throws Exception {
when(iam.createInstanceProfile(eq("web"), anyString()))
.thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
when(iam.getInstanceProfile("web")).thenReturn(profile("web", "/"));
StackResource r = resource();
r.setPhysicalId("web");
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.provision(r, props("""
{"InstanceProfileName": "web", "Path": "/team/", "Roles": ["app-role"]}
"""), ctx("web")));
assertEquals("ValidationError", failure.getErrorCode());
assertTrue(failure.getMessage().contains("Path"), failure.getMessage());
}
@Test
void changingTheNameOnUpdateIsRejected() throws Exception {
StackResource r = resource();
r.setPhysicalId("old");
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.provision(r, props("""
{"InstanceProfileName": "new", "Roles": ["app-role"]}
"""), ctx("old")));
assertEquals("ValidationError", failure.getErrorCode());
}
@Test
void aCreateCollisionOutsideAnUpdatePropagates() throws Exception {
when(iam.createInstanceProfile("web", "/"))
.thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
StackResource r = resource();
provisioner.provision(r, props("{\"InstanceProfileName\": \"web\"}"), ctx());
assertEquals("web", r.getPhysicalId());
assertEquals("arn:aws:iam::000000000000:instance-profile/web", r.getAttributes().get("Arn"));
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.provision(r, props("""
{"InstanceProfileName": "web", "Roles": ["app-role"]}
"""), ctx(null)));
assertEquals("EntityAlreadyExists", failure.getErrorCode());
}
@Test
void deleteRemovesTheProfile() {
void deleteDetachesRolesThenRemovesTheProfile() {
InstanceProfile withRole = profile("web", "/");
withRole.getRoleNames().add("app-role");
when(iam.getInstanceProfile("web")).thenReturn(withRole);
provisioner.delete(TYPE, "web", "us-east-1");
org.mockito.Mockito.verify(iam).deleteInstanceProfile("web");
org.mockito.InOrder order = inOrder(iam);
order.verify(iam).removeRoleFromInstanceProfile("web", "app-role");
order.verify(iam).deleteInstanceProfile("web");
}
@Test
void deleteToleratesAProfileAlreadyGone() {
doThrow(new AwsException("NoSuchEntity", "gone", 404))
.when(iam).deleteInstanceProfile("web");
when(iam.getInstanceProfile("web")).thenThrow(new AwsException("NoSuchEntity", "gone", 404));
assertDoesNotThrow(() -> provisioner.delete(TYPE, "web", "us-east-1"));
}
@Test
void deletePropagatesADeleteConflict() {
when(iam.getInstanceProfile("web")).thenReturn(profile("web", "/"));
doThrow(new AwsException("DeleteConflict", "roles attached", 409))
.when(iam).deleteInstanceProfile("web");
@@ -98,19 +179,36 @@ class IamInstanceProfileCfnProvisionerTest {
assertEquals("DeleteConflict", failure.getErrorCode());
}
private ProvisionContext ctx() {
private ProvisionContext ctx(String priorPhysicalId) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null ? null : node.asText();
});
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
when(engine.resolveStringList(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
List<String> out = new ArrayList<>();
if (node != null && node.isArray()) {
node.forEach(element -> out.add(element.asText()));
}
return out;
});
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);
}
private JsonNode props(String json) throws Exception {
return mapper.readTree(json);
}
private static InstanceProfile profile(String name, String path) {
InstanceProfile profile = new InstanceProfile();
profile.setInstanceProfileName(name);
profile.setPath(path);
profile.setArn("arn:aws:iam::000000000000:instance-profile/" + name);
profile.setRoleNames(new ArrayList<>());
return profile;
}
private static StackResource resource() {
StackResource r = new StackResource();
r.setLogicalId("Profile");