Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): reconcile and replace IAM leaf resources on update and delete (#3933)
Hector Ventura3a36b8c85c9c
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisioner.javaindex 3dc82199ef..2269ea9e09 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisioner.java@@ -1,27 +1,33 @@package io.github.hectorvent.floci.services.cloudformation.provisioners;import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.cloudformation.model.StackResource;import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.iam.model.AccessKey;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;+import java.util.HashMap;+import java.util.Map;import java.util.Set;/*** CloudFormation provisioning for {@code AWS::IAM::AccessKey}. {@code Ref} returns the access key- * id (the primary identifier), and {@code Fn::GetAtt} exposes the same id plus the one-time- * {@code SecretAccessKey}.+ * id, and {@code Fn::GetAtt} exposes the same id plus the one-time {@code SecretAccessKey}.*- * <p>No delete is overridden: removing an access key needs the owning user name, which the- * id-only delete path does not carry, so the legacy switch left it a no-op. Storing the user name- * and deleting the key is a follow-up.+ * <p>{@code UserName} and {@code Serial} are the only inputs and both are createOnly. An update that+ * changes neither reuses the existing key rather than minting another one, since a user is capped at+ * two keys and recreating on every update would fail with {@code LimitExceeded} and orphan the+ * earlier keys. A change to either replaces the key (AWS rotates a key by incrementing {@code+ * Serial}): a new key is created and the displaced one is deleted once the update commits, through+ * {@link ReplacementCleanup}.*/@ApplicationScopedpublic class IamAccessKeyCfnProvisioner implements CfnResourceProvisioner {private static final String TYPE = "AWS::IAM::AccessKey";+ private static final String SERIAL_ATTR = "__FlociAccessKeySerial";private final IamService iamService;@@ -38,11 +44,71 @@ public class IamAccessKeyCfnProvisioner implements CfnResourceProvisioner {@Overridepublic void provision(StackResource r, JsonNode props, ProvisionContext ctx) {String userName = ctx.resolveOptional(props, "UserName");- if (userName != null) {- AccessKey key = iamService.createAccessKey(userName);- r.setPhysicalId(key.getAccessKeyId());- r.getAttributes().put("Id", key.getAccessKeyId());- r.getAttributes().put("SecretAccessKey", key.getSecretAccessKey());+ if (userName == null || userName.isBlank()) {+ throw new AwsException("ValidationError", "AWS::IAM::AccessKey requires a UserName.", 400);}+ String serial = serialOf(props, ctx);++ Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());+ if (ctx.isUpdate() && !createOnlyChanged(r, ctx, userName, serial)) {+ // Neither UserName nor Serial changed: keep the existing key and its id and secret.+ ReplacementCleanup.record(r, ctx, attributesBefore);+ return;+ }++ AccessKey key = iamService.createAccessKey(userName);+ r.setPhysicalId(key.getAccessKeyId());+ r.getAttributes().put("Id", key.getAccessKeyId());+ r.getAttributes().put("SecretAccessKey", key.getSecretAccessKey());+ r.getAttributes().put(SERIAL_ATTR, serial);+ // On a createOnly change this new key replaced the prior one; record it so the displaced+ // key is deleted after the update commits, and rolled back to if a later resource fails.+ ReplacementCleanup.record(r, ctx, attributesBefore);+ }++ private String serialOf(JsonNode props, ProvisionContext ctx) {+ String serial = ctx.resolveOptional(props, "Serial");+ return serial == null ? "" : serial;+ }++ private boolean createOnlyChanged(StackResource r, ProvisionContext ctx, String userName, String serial) {+ String priorUser = iamService.findUserNameByAccessKeyId(ctx.priorPhysicalId()).orElse(null);+ String priorSerial = r.getAttributes().getOrDefault(SERIAL_ATTR, "");+ // A missing prior user means the old key is already gone, so a fresh one is created.+ return priorUser == null || !priorUser.equals(userName) || !priorSerial.equals(serial);+ }++ @Override+ public void delete(String resourceType, String physicalId, String region) {+ // The owning user is recovered from the key id so both the stack-delete and the+ // replacement-cleanup paths can delete by physical id alone.+ iamService.findUserNameByAccessKeyId(physicalId).ifPresent(userName ->+ CfnDeletes.safeDelete("IAM access key", physicalId,+ () -> iamService.deleteAccessKey(userName, physicalId), "NoSuchEntity"));+ }++ @Override+ public boolean hasReplacementUpdate(StackResource resource) {+ return ReplacementCleanup.hasReplacement(resource);+ }++ @Override+ public String updateCleanupPhysicalId(StackResource resource) {+ return ReplacementCleanup.cleanupPhysicalId(resource);+ }++ @Override+ public UpdateCleanupResult completeUpdate(StackResource resource) {+ return ReplacementCleanup.complete(resource, this::delete);+ }++ @Override+ public void clearUpdate(StackResource resource) {+ ReplacementCleanup.clear(resource);+ }++ @Override+ public boolean rollbackUpdate(StackResource resource) {+ return ReplacementCleanup.rollback(resource, this::delete);}}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamInstanceProfileCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamInstanceProfileCfnProvisioner.javaindex 2dfe769105..b2d61c8dce 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamInstanceProfileCfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamInstanceProfileCfnProvisioner.java@@ -1,25 +1,26 @@package io.github.hectorvent.floci.services.cloudformation.provisioners;import com.fasterxml.jackson.databind.JsonNode;-import io.github.hectorvent.floci.core.common.AwsArnUtils;+import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.cloudformation.model.StackResource;import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.iam.model.InstanceProfile;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;-import org.jboss.logging.Logger;+import java.util.ArrayList;+import java.util.List;import java.util.Set;/*** CloudFormation provisioning for {@code AWS::IAM::InstanceProfile}. {@code Ref} returns the- * instance profile name (the primary identifier) and {@code Fn::GetAtt Arn} its arn.+ * instance profile name (the primary identifier) and {@code Fn::GetAtt Arn} its arn. The declared+ * {@code Path} and {@code Roles} are applied, and the roles are detached before delete because IAM+ * refuses to delete a profile that still holds one.*/@ApplicationScopedpublic class IamInstanceProfileCfnProvisioner implements CfnResourceProvisioner {- private static final Logger LOG = Logger.getLogger(IamInstanceProfileCfnProvisioner.class);-private static final String TYPE = "AWS::IAM::InstanceProfile";private final IamService iamService;@@ -36,29 +37,82 @@ public class IamInstanceProfileCfnProvisioner implements CfnResourceProvisioner@Overridepublic void provision(StackResource r, JsonNode props, ProvisionContext ctx) {- String name = ctx.resolveOptional(props, "InstanceProfileName");- if (name == null || name.isBlank()) {- name = ctx.generatePhysicalName(r.getLogicalId(), 128, false);+ // A create-only name kept stable across updates: an unnamed profile keeps the name it was+ // given rather than getting a fresh random one each update, which would orphan the first.+ String name = ctx.stablePhysicalName(ctx.resolveOptional(props, "InstanceProfileName"),+ r.getLogicalId(), 128, false);+ if (ctx.isUpdate() && !name.equals(ctx.priorPhysicalId())) {+ throw new AwsException("ValidationError",+ "Updating InstanceProfileName requires resource replacement, which is not supported.", 400);+ }+ String path = ctx.resolveOptional(props, "Path");+ if (path == null || path.isBlank()) {+ path = "/";+ }+ List<String> roles = ctx.resolveStringList(props, "Roles");+ if (roles.isEmpty()) {+ throw new AwsException("ValidationError",+ "AWS::IAM::InstanceProfile requires at least one role in Roles.", 400);}r.setPhysicalId(name);++ InstanceProfile profile;try {- InstanceProfile profile = iamService.createInstanceProfile(name, "/");- r.getAttributes().put("Arn", profile.getArn());- } catch (RuntimeException e) {- // A create collision (the profile already exists) is tolerated as the legacy switch did:- // synthesize the arn so Fn::GetAtt Arn still resolves rather than failing the stack.- LOG.debugv("createInstanceProfile fell back to a synthesized arn for {0}: {1}",- name, e.getMessage());- r.getAttributes().put("Arn",- AwsArnUtils.Arn.of("iam", "", ctx.accountId(), "instance-profile/" + name).toString());+ profile = iamService.createInstanceProfile(name, path);+ } catch (AwsException e) {+ // Only re-provisioning the same profile on update is tolerated; any other failure,+ // including a name collision with a profile outside this stack, propagates.+ if (!ctx.reusesPriorEntity(name) || !"EntityAlreadyExists".equals(e.getErrorCode())) {+ throw e;+ }+ profile = iamService.getInstanceProfile(name);+ // Path is createOnly: a change would require replacement, which a same-named profile+ // cannot do, so it is rejected rather than silently ignored.+ if (!normalizePath(path).equals(profile.getPath())) {+ throw new AwsException("ValidationError",+ "Updating Path requires resource replacement, which is not supported.", 400);+ }+ }+ r.getAttributes().put("Arn", profile.getArn());+ reconcileRoles(name, profile.getRoleNames(), roles);+ }++ /**+ * Brings the profile's attached roles to the declared set: an instance profile holds one role,+ * so a swap has to remove the old one before adding the new, and a no-op adds and removes+ * nothing.+ */+ private void reconcileRoles(String name, List<String> current, List<String> desired) {+ for (String roleName : new ArrayList<>(current)) {+ if (!desired.contains(roleName)) {+ iamService.removeRoleFromInstanceProfile(name, roleName);+ }+ }+ for (String roleName : desired) {+ if (!current.contains(roleName)) {+ iamService.addRoleToInstanceProfile(name, roleName);+ }+ }+ }++ private static String normalizePath(String path) {+ if (path == null || path.isEmpty()) {+ return "/";}+ String withLeading = path.startsWith("/") ? path : "/" + path;+ return withLeading.endsWith("/") ? withLeading : withLeading + "/";}@Overridepublic void delete(String resourceType, String physicalId, String region) {- // deleteInstanceProfile still throws DeleteConflict when roles are attached, which must- // propagate so the stack reports DELETE_FAILED; only the already-gone case is tolerated.- CfnDeletes.safeDelete("IAM instance profile", physicalId,- () -> iamService.deleteInstanceProfile(physicalId), "NoSuchEntity");+ // Detach roles first: deleteInstanceProfile rejects a profile that still holds one with+ // DeleteConflict, which must otherwise propagate. The already-gone case is tolerated.+ CfnDeletes.safeDelete("IAM instance profile", physicalId, () -> {+ InstanceProfile profile = iamService.getInstanceProfile(physicalId);+ for (String roleName : new ArrayList<>(profile.getRoleNames())) {+ iamService.removeRoleFromInstanceProfile(physicalId, roleName);+ }+ iamService.deleteInstanceProfile(physicalId);+ }, "NoSuchEntity");}}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamLeafIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamLeafIntegrationTest.javaindex a6295971f3..c85357464c 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamLeafIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamLeafIntegrationTest.java@@ -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");diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisionerTest.javaindex afff2441c2..50b87f4e84 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamAccessKeyCfnProvisionerTest.java@@ -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 {@Testvoid 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());+ AwsException failure = assertThrows(AwsException.class,+ () -> provisioner.provision(r, props("{}"), ctx(null)));+ assertEquals("ValidationError", failure.getErrorCode());+ verify(iam, never()).createAccessKey(anyString());+ }++ @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");- verifyNoInteractions(iam);+ verify(iam, never()).deleteAccessKey(anyString(), anyString());}- 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");+ return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);}private JsonNode props(String json) throws Exception {diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamInstanceProfileCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamInstanceProfileCfnProvisionerTest.javaindex 635a1e4dbb..dd2f29f853 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamInstanceProfileCfnProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamInstanceProfileCfnProvisionerTest.java@@ -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");}@Testvoid 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();- provisioner.provision(r, props("{\"InstanceProfileName\": \"web\"}"), ctx());+ 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");+ }- assertEquals("web", r.getPhysicalId());- assertEquals("arn:aws:iam::000000000000:instance-profile/web", r.getAttributes().get("Arn"));+ @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 deleteRemovesTheProfile() {+ 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();+ AwsException failure = assertThrows(AwsException.class,+ () -> provisioner.provision(r, props("""+ {"InstanceProfileName": "web", "Roles": ["app-role"]}+ """), ctx(null)));+ assertEquals("EntityAlreadyExists", failure.getErrorCode());+ }++ @Test+ 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");}@Testvoid 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"));}@Testvoid 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");