Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): replace IAM InstanceProfile on a createOnly change (#4133)
Hector Ventura03a2d969f2e8
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 b2d61c8dce..5b537716ed 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@@ -9,7 +9,9 @@ import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import java.util.ArrayList;+import java.util.HashMap;import java.util.List;+import java.util.Map;import java.util.Set;/**@@ -17,11 +19,29 @@ import java.util.Set;* 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.+ *+ * <p>{@code InstanceProfileName} and {@code Path} are both createOnly, so an update that changes+ * either, or drops an explicit name, replaces the profile: the new one is created and the displaced+ * one is deleted once the update commits (or restored on rollback), via {@link ReplacementCleanup}.+ * A rename creates the new name outright, and dropping the name (whether the profile was created+ * under an explicit one is recorded at create time) mints a generated one. A {@code Path}+ * change that keeps an explicit name is attempted with that same name, so {@code CreateInstanceProfile}+ * collides and IAM answers {@code EntityAlreadyExists}, exactly as CloudFormation surfaces that update.*/@ApplicationScopedpublic class IamInstanceProfileCfnProvisioner implements CfnResourceProvisioner {private static final String TYPE = "AWS::IAM::InstanceProfile";+ /**+ * Whether the profile was created under an explicit {@code InstanceProfileName}, recorded at+ * create time so that dropping the name later reads as the createOnly change it is. Filtered+ * out of the published attributes by the {@code __Floci} prefix, as the other provisioners do.+ * Recorded rather than inferred from the id's shape: a generated name loses its+ * {@code <stack>-<logicalId>-} prefix once that would push the name past 128 characters, so a+ * shape check misreads every long-named stack as explicitly named and churns the profile on+ * every update.+ */+ private static final String EXPLICIT_NAME_ATTR = "__FlociIamInstanceProfileExplicitName";private final IamService iamService;@@ -37,14 +57,8 @@ public class IamInstanceProfileCfnProvisioner implements CfnResourceProvisioner@Overridepublic void provision(StackResource r, JsonNode props, ProvisionContext ctx) {- // 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);- }+ Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());+ String explicitName = ctx.resolveOptional(props, "InstanceProfileName");String path = ctx.resolveOptional(props, "Path");if (path == null || path.isBlank()) {path = "/";@@ -54,6 +68,25 @@ public class IamInstanceProfileCfnProvisioner implements CfnResourceProvisionerthrow new AwsException("ValidationError","AWS::IAM::InstanceProfile requires at least one role in Roles.", 400);}++ InstanceProfile prior = ctx.isUpdate() ? findProfile(ctx.priorPhysicalId()) : null;+ boolean named = explicitName != null && !explicitName.isBlank();+ boolean nameChanged = named && !explicitName.equals(ctx.priorPhysicalId());+ // Dropping InstanceProfileName is a createOnly change too: a profile created under an explicit+ // name (recorded at create time) that now declares none must be replaced with a generated+ // name, not left standing under the old explicit one. A prior profile with no record (created+ // before the record existed) is treated as unnamed: keeping it is the conservative outcome.+ boolean nameDropped = !named && ctx.isUpdate()+ && Boolean.parseBoolean(attributesBefore.get(EXPLICIT_NAME_ATTR));+ boolean pathChanged = prior != null && !normalizePath(path).equals(prior.getPath());+ if (prior != null && (nameChanged || nameDropped || pathChanged)) {+ replaceProfile(r, ctx, explicitName, path, roles, attributesBefore);+ return;+ }++ // 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(explicitName, r.getLogicalId(), 128, false);r.setPhysicalId(name);InstanceProfile profile;@@ -66,15 +99,44 @@ public class IamInstanceProfileCfnProvisioner implements CfnResourceProvisionerthrow 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());+ r.getAttributes().put(EXPLICIT_NAME_ATTR, String.valueOf(named));reconcileRoles(name, profile.getRoleNames(), roles);+ // Nothing was displaced here, so this only carries forward any delete an earlier failed+ // rollback still owed; a genuine replacement is recorded in replaceProfile.+ ReplacementCleanup.record(r, ctx, attributesBefore);+ }++ /**+ * Replaces the profile a createOnly change displaced: creates the new one and leaves the old for+ * cleanup once the update commits. A rename uses the new explicit name; a dropped name or a Path+ * change on an auto-named profile mints a fresh name. A Path change that keeps an explicit name+ * is attempted with that same name, so {@code CreateInstanceProfile} collides and IAM answers+ * {@code EntityAlreadyExists}, exactly as CloudFormation surfaces that update.+ */+ private void replaceProfile(StackResource r, ProvisionContext ctx, String explicitName,+ String path, List<String> roles, Map<String, String> attributesBefore) {+ boolean named = explicitName != null && !explicitName.isBlank();+ String replacementName = named ? explicitName : ctx.generatePhysicalName(r.getLogicalId(), 128, false);+ r.setPhysicalId(replacementName);+ InstanceProfile replacement = iamService.createInstanceProfile(replacementName, path);+ r.getAttributes().put("Arn", replacement.getArn());+ r.getAttributes().put(EXPLICIT_NAME_ATTR, String.valueOf(named));+ reconcileRoles(replacementName, replacement.getRoleNames(), roles);+ ReplacementCleanup.record(r, ctx, attributesBefore);+ }++ /** The prior profile, or null when it was deleted out of band so the update recreates it. */+ private InstanceProfile findProfile(String name) {+ try {+ return iamService.getInstanceProfile(name);+ } catch (AwsException e) {+ if ("NoSuchEntity".equals(e.getErrorCode())) {+ return null;+ }+ throw e;+ }}/**@@ -103,6 +165,31 @@ public class IamInstanceProfileCfnProvisioner implements CfnResourceProvisionerreturn withLeading.endsWith("/") ? withLeading : withLeading + "/";}+ @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);+ }+@Overridepublic void delete(String resourceType, String physicalId, String region) {// Detach roles first: deleteInstanceProfile rejects a profile that still holds one withdiff --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 c85357464c..6d053fe452 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@@ -107,6 +107,69 @@ class CloudFormationIamLeafIntegrationTest {.body(containsString("NoSuchEntity"));}+ @Test+ void updateStackRenamingTheInstanceProfileReplacesItAndDeletesTheOldProfile() throws InterruptedException {+ String suffix = Long.toString(System.nanoTime(), 36);+ String roleName = "rename-role-" + suffix;+ String firstName = "rename-profile-a-" + suffix;+ String secondName = "rename-profile-b-" + suffix;+ String stackName = "cfn-iam-profile-rename-" + suffix;++ String template = """+ {+ "Resources": {+ "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", "Roles": [{"Ref": "Role"}]}+ }+ },+ "Outputs": {+ "ProfileRef": {"Value": {"Ref": "Profile"}}+ }+ }+ """;++ String stackId = createStack(stackName, template.formatted(roleName, firstName));+ awaitStackStatus(stackId, "CREATE_COMPLETE");+ assertEquals(firstName, outputValue(describeStacks(stackId), "ProfileRef"));++ // InstanceProfileName is createOnly, so renaming it replaces the profile.+ updateStack(stackName, template.formatted(roleName, secondName));+ awaitStackStatus(stackId, "UPDATE_COMPLETE");++ // Ref now resolves to the replacement profile, which really exists in IAM.+ assertEquals(secondName, outputValue(describeStacks(stackId), "ProfileRef"));+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", IAM_AUTH)+ .formParam("Action", "GetInstanceProfile")+ .formParam("InstanceProfileName", secondName)+ .when().post("/").then().statusCode(200)+ .body(containsString("<InstanceProfileName>" + secondName + "</InstanceProfileName>"));++ // The profile it displaced was cleaned up once the update committed.+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", IAM_AUTH)+ .formParam("Action", "GetInstanceProfile")+ .formParam("InstanceProfileName", firstName)+ .when().post("/").then().statusCode(404)+ .body(containsString("NoSuchEntity"));++ deleteStack(stackName);+ awaitStackStatus(stackId, "DELETE_COMPLETE");+ }+private static String createStack(String stackName, String template) {return cfnQuery("CreateStack", stackName, template).then()@@ -116,6 +179,10 @@ class CloudFormationIamLeafIntegrationTest {.getString("CreateStackResponse.CreateStackResult.StackId");}+ private static void updateStack(String stackName, String template) {+ cfnQuery("UpdateStack", stackName, template).then().statusCode(200);+ }+private static void deleteStack(String stackName) {cfnQuery("DeleteStack", stackName, null).then().statusCode(200);}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 dd2f29f853..67e80bef78 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@@ -16,6 +16,7 @@ import java.util.Set;import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotEquals;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;@@ -30,8 +31,10 @@ import static org.mockito.Mockito.when;/*** {@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.+ * and Roles are applied, a role swap reconciles in place, a createOnly change (name, or path on an+ * auto-named profile, or a dropped name) replaces the profile and marks the old one for cleanup, a+ * path change that keeps an explicit name collides with EntityAlreadyExists, a missing Roles is+ * rejected, and delete detaches roles before removing the profile.*/class IamInstanceProfileCfnProvisionerTest {@@ -51,7 +54,8 @@ class IamInstanceProfileCfnProvisionerTest {"""), ctx(null));assertEquals("web", r.getPhysicalId());- assertEquals(Set.of("Arn"), r.getAttributes().keySet());+ // Arn is the published attribute; the __Floci record is internal and filtered before publishing.+ assertEquals(Set.of("Arn", "__FlociIamInstanceProfileExplicitName"), r.getAttributes().keySet());assertEquals("arn:aws:iam::000000000000:instance-profile/web", r.getAttributes().get("Arn"));verify(iam).addRoleToInstanceProfile("web", "app-role");}@@ -108,10 +112,12 @@ class IamInstanceProfileCfnProvisionerTest {}@Test- void changingThePathOnUpdateIsRejected() throws Exception {- when(iam.createInstanceProfile(eq("web"), anyString()))- .thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));+ void changingThePathOnANamedProfileCollidesWithEntityAlreadyExists() throws Exception {+ // A Path change needs replacement, but the replacement keeps the explicit name, so+ // CreateInstanceProfile collides and IAM answers EntityAlreadyExists, as CloudFormation does.when(iam.getInstanceProfile("web")).thenReturn(profile("web", "/"));+ when(iam.createInstanceProfile("web", "/team/"))+ .thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));StackResource r = resource();r.setPhysicalId("web");@@ -119,20 +125,121 @@ class IamInstanceProfileCfnProvisionerTest {() -> provisioner.provision(r, props("""{"InstanceProfileName": "web", "Path": "/team/", "Roles": ["app-role"]}"""), ctx("web")));- assertEquals("ValidationError", failure.getErrorCode());- assertTrue(failure.getMessage().contains("Path"), failure.getMessage());+ assertEquals("EntityAlreadyExists", failure.getErrorCode());+ }++ @Test+ void droppingTheExplicitNameReplacesWithAGeneratedName() throws Exception {+ // Created under an explicit name ("web"), which the create records; removing+ // InstanceProfileName afterwards is a createOnly change that replaces it.+ when(iam.getInstanceProfile("web")).thenReturn(profile("web", "/"));+ when(iam.createInstanceProfile(anyString(), eq("/")))+ .thenAnswer(inv -> profile(inv.getArgument(0), "/"));+ StackResource r = resource();+ provisioner.provision(r, props("{\"InstanceProfileName\": \"web\", \"Roles\": [\"app-role\"]}"), ctx(null));+ assertEquals("web", r.getPhysicalId());+ assertEquals("true", r.getAttributes().get("__FlociIamInstanceProfileExplicitName"));++ provisioner.provision(r, props("{\"Roles\": [\"app-role\"]}"), ctx("web"));++ assertTrue(r.getPhysicalId().matches("my-stack-Profile-[0-9a-f]{12}"), r.getPhysicalId());+ assertEquals("false", r.getAttributes().get("__FlociIamInstanceProfileExplicitName"));+ assertTrue(provisioner.hasReplacementUpdate(r));+ assertEquals("web", provisioner.updateCleanupPhysicalId(r));+ }++ /**+ * The generated-name shape is not a reliable "was it explicit" signal: past 128 characters the+ * {@code <stack>-<logicalId>-} prefix is truncated and only the suffix survives, so an+ * auto-named profile in a long-named stack must still read as auto-named on a no-op update, or+ * every UpdateStack would replace it.+ */+ @Test+ void anAutoNamedProfileInALongNamedStackIsNotReplacedOnANoOpUpdate() throws Exception {+ String stackName = "a".repeat(120);+ when(iam.createInstanceProfile(anyString(), eq("/")))+ .thenAnswer(inv -> profile(inv.getArgument(0), "/"));+ StackResource r = resource();+ provisioner.provision(r, props("{\"Roles\": [\"app-role\"]}"), ctx(stackName, null));+ String generated = r.getPhysicalId();+ assertEquals(128, generated.length());+ assertTrue(generated.matches("a{115}-[0-9a-f]{12}"), generated);+ when(iam.getInstanceProfile(generated)).thenReturn(profile(generated, "/"));++ provisioner.provision(r, props("{\"Roles\": [\"app-role\"]}"), ctx(stackName, generated));++ assertEquals(generated, r.getPhysicalId());+ assertTrue(!provisioner.hasReplacementUpdate(r), "a no-op update must not replace the profile");+ verify(iam, never()).deleteInstanceProfile(anyString());+ }++ /** A prior profile with no create-time record (state from before the record) is kept, not churned. */+ @Test+ void anUnrecordedPriorProfileIsNotReplacedWhenTheTemplateNamesNone() throws Exception {+ when(iam.getInstanceProfile("web")).thenReturn(profile("web", "/"));+ when(iam.createInstanceProfile("web", "/")).thenReturn(profile("web", "/"));+ StackResource r = resource();+ r.setPhysicalId("web");++ provisioner.provision(r, props("{\"Roles\": [\"app-role\"]}"), ctx("web"));++ assertEquals("web", r.getPhysicalId());+ assertTrue(!provisioner.hasReplacementUpdate(r));+ verify(iam, never()).deleteInstanceProfile(anyString());}@Test- void changingTheNameOnUpdateIsRejected() throws Exception {+ void changingTheNameOnUpdateReplacesTheProfileAndMarksTheOldForCleanup() throws Exception {+ when(iam.getInstanceProfile("old")).thenReturn(profile("old", "/"));+ when(iam.createInstanceProfile("new", "/")).thenReturn(profile("new", "/"));+StackResource r = resource();r.setPhysicalId("old");+ r.getAttributes().put("Arn", "arn:aws:iam::000000000000:instance-profile/old");+ provisioner.provision(r, props("""+ {"InstanceProfileName": "new", "Roles": ["app-role"]}+ """), ctx("old"));++ assertEquals("new", r.getPhysicalId());+ assertEquals("arn:aws:iam::000000000000:instance-profile/new", r.getAttributes().get("Arn"));+ verify(iam).createInstanceProfile("new", "/");+ verify(iam).addRoleToInstanceProfile("new", "app-role");+ assertTrue(provisioner.hasReplacementUpdate(r));+ assertEquals("old", provisioner.updateCleanupPhysicalId(r));+ }- AwsException failure = assertThrows(AwsException.class,- () -> provisioner.provision(r, props("""- {"InstanceProfileName": "new", "Roles": ["app-role"]}- """), ctx("old")));- assertEquals("ValidationError", failure.getErrorCode());+ @Test+ void changingThePathOnAnAutoNamedProfileReplacesWithAFreshName() throws Exception {+ String priorName = "my-stack-Profile-0123456789ab";+ when(iam.getInstanceProfile(priorName)).thenReturn(profile(priorName, "/"));+ when(iam.createInstanceProfile(anyString(), eq("/team/")))+ .thenAnswer(inv -> profile(inv.getArgument(0), "/team/"));++ StackResource r = resource();+ r.setPhysicalId(priorName);+ provisioner.provision(r, props("{\"Path\": \"/team/\", \"Roles\": [\"app-role\"]}"), ctx(priorName));++ assertTrue(r.getPhysicalId().matches("my-stack-Profile-[0-9a-f]{12}"), r.getPhysicalId());+ assertNotEquals(priorName, r.getPhysicalId());+ verify(iam).createInstanceProfile(r.getPhysicalId(), "/team/");+ assertTrue(provisioner.hasReplacementUpdate(r));+ assertEquals(priorName, provisioner.updateCleanupPhysicalId(r));+ }++ @Test+ void completingAReplacingUpdateDeletesTheDisplacedProfile() throws Exception {+ when(iam.getInstanceProfile("old")).thenReturn(profile("old", "/"));+ when(iam.createInstanceProfile("new", "/")).thenReturn(profile("new", "/"));+ StackResource r = resource();+ r.setPhysicalId("old");+ provisioner.provision(r, props("""+ {"InstanceProfileName": "new", "Roles": ["app-role"]}+ """), ctx("old"));++ UpdateCleanupResult result = provisioner.completeUpdate(r);++ assertTrue(result.applicable() && result.complete());+ verify(iam).deleteInstanceProfile("old");}@Test@@ -180,6 +287,10 @@ class IamInstanceProfileCfnProvisionerTest {}private ProvisionContext ctx(String priorPhysicalId) {+ return ctx("my-stack", priorPhysicalId);+ }++ private ProvisionContext ctx(String stackName, String priorPhysicalId) {CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);when(engine.resolve(any())).thenAnswer(inv -> {JsonNode node = inv.getArgument(0);@@ -193,7 +304,7 @@ class IamInstanceProfileCfnProvisionerTest {}return out;});- return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);+ return new ProvisionContext(engine, "us-east-1", "000000000000", stackName, priorPhysicalId);}private JsonNode props(String json) throws Exception {