diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java index 0cae78d441..26a34d26ef 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java @@ -70,6 +70,13 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { IamRole role; boolean createdRole = false; + // 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 + // UPDATE_ROLLBACK_COMPLETE - and restore it onto the *same verified role*, not onto a + // replacement that took the name in the meantime. + String priorAssumeRolePolicyDocument = null; + String priorAssumeRoleId = null; try { role = iamService.createRole(resolvedRoleName, path, assumeDoc, description, 3600, Map.of()); createdRole = true; @@ -89,6 +96,22 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR); throw e; } + // createRole() only runs on first create; adopting an existing role on update must + // still apply this template's current AssumeRolePolicyDocument, or a changed trust + // policy is silently dropped while the stack still reports UPDATE_COMPLETE. + // + // Deliberately not re-fetching the role afterward: everything read from `role` below + // (Arn, RoleId, AttachedPolicyArns) is unaffected by a trust-policy update, and a + // failing re-fetch here would escape before the failure-cleanup block below can + // restore the trust policy, leaving the new document active despite a rolled-back + // update. + // Pass existingRoleId through so IamService re-verifies identity atomically with the + // 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. + priorAssumeRolePolicyDocument = role.getAssumeRolePolicyDocument(); + priorAssumeRoleId = existingRoleId; + iamService.updateAssumeRolePolicy(resolvedRoleName, assumeDoc, existingRoleId); } r.setPhysicalId(resolvedRoleName); @@ -110,6 +133,8 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { // name this attempt introduced there is no prior value and the policy is removed instead. Map originalInlinePolicies = new HashMap<>(role.getInlinePolicies()); LinkedHashSet inlineWrittenByThisAttempt = new LinkedHashSet<>(); + final String documentToRestore = priorAssumeRolePolicyDocument; + final String roleIdToRestore = priorAssumeRoleId; try { for (String policyArn : managedPolicyArns) { iamService.attachRolePolicy(resolvedRoleName, policyArn); @@ -215,6 +240,16 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { 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 + // onto the replacement. + if (!CfnRollback.attemptIamCleanup(failure, "restore prior trust policy on role " + resolvedRoleName, + () -> iamService.updateAssumeRolePolicy( + resolvedRoleName, documentToRestore, roleIdToRestore))) { + cleanupSucceeded = false; + } + } if (createdRole) { if (!CfnRollback.attemptIamCleanup(failure, "delete role " + resolvedRoleName, () -> iamService.deleteRole(resolvedRoleName))) { diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java index ac3ecd8ab6..cc9e96f2f9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java @@ -572,6 +572,24 @@ public class IamService implements SessionAccountLookup { roles.put(roleName, role); } + /** + * Same as {@link #updateAssumeRolePolicy(String, String)}, but verifies {@code expectedRoleId} + * against the resolved role's immutable ID before applying the update, atomically with the + * name-based lookup. For callers (e.g. CloudFormation role adoption) that already verified role + * identity by ID earlier: without this, a role deleted and recreated under the same name between + * that check and this call would silently receive the update meant for the original role. + */ + public void updateAssumeRolePolicy(String roleName, String policyDocument, String expectedRoleId) { + IamRole role = getRole(roleName); + if (expectedRoleId != null && !expectedRoleId.equals(role.getRoleId())) { + throw new AwsException("EntityAlreadyExists", + "Role " + roleName + " was replaced by a different role of the same name; " + + "refusing to apply an update meant for the original role.", 409); + } + role.setAssumeRolePolicyDocument(policyDocument); + roles.put(roleName, role); + } + public void tagRole(String roleName, Map newTags) { IamRole role = getRole(roleName); role.getTags().putAll(newTags); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java index ea7dc5b067..9c6436756a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamAttachmentProvisionerTest.java @@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.iam.model.IamPolicy; import io.github.hectorvent.floci.services.iam.model.IamRole; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import java.util.List; @@ -93,6 +94,76 @@ class CloudFormationIamAttachmentProvisionerTest { verify(iamService, never()).deleteRole("existing-role"); } + @Test + void sameStackRoleUpdateAppliesChangedTrustPolicy() throws Exception { + // github.com/floci-io/floci/issues/2084 — adopting an existing role on update must still + // apply this template's current AssumeRolePolicyDocument, or a changed trust policy is + // silently dropped while the stack still reports UPDATE_COMPLETE. + IamRole role = role("existing-role"); + String newTrustPolicyJson = + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}"; + when(iamService.createRole(eq("existing-role"), eq("/"), anyString(), eq(null), eq(3600), eq(Map.of()))) + .thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409)); + when(iamService.getRole("existing-role")).thenReturn(role); + + StackResource result = provision("Role", "AWS::IAM::Role", """ + {"RoleName":"existing-role","AssumeRolePolicyDocument":%s} + """.formatted(newTrustPolicyJson), "existing-role", Map.of("RoleId", role.getRoleId())); + + assertEquals("CREATE_COMPLETE", result.getStatus()); + ArgumentCaptor docCaptor = ArgumentCaptor.forClass(String.class); + verify(iamService).updateAssumeRolePolicy(eq("existing-role"), docCaptor.capture(), eq(role.getRoleId())); + assertEquals(mapper.readTree(newTrustPolicyJson), mapper.readTree(docCaptor.getValue())); + } + + @Test + void sameStackRoleUpdateFailureRestoresPriorTrustPolicy() throws Exception { + // Companion to sameStackRoleUpdateAppliesChangedTrustPolicy: if a later step in this same + // attempt fails (e.g. a bad ManagedPolicyArns entry), the whole resource update fails and + // CloudFormation reports UPDATE_ROLLBACK_COMPLETE. The trust policy must actually roll back + // too, not stay on the new value while the stack claims nothing changed. + IamRole role = role("existing-role"); + String priorTrustPolicy = role.getAssumeRolePolicyDocument(); + String newTrustPolicyJson = + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}"; + when(iamService.createRole(eq("existing-role"), eq("/"), anyString(), eq(null), eq(3600), eq(Map.of()))) + .thenThrow(new AwsException("EntityAlreadyExists", "already exists", 409)); + when(iamService.getRole("existing-role")).thenReturn(role); + doThrow(new AwsException("NoSuchEntity", "missing policy", 404)) + .when(iamService).attachRolePolicy("existing-role", MISSING_POLICY); + + StackResource result = provision("Role", "AWS::IAM::Role", """ + {"RoleName":"existing-role","AssumeRolePolicyDocument":%s,"ManagedPolicyArns":["%s"]} + """.formatted(newTrustPolicyJson, MISSING_POLICY), "existing-role", Map.of("RoleId", role.getRoleId())); + + assertEquals("CREATE_FAILED", result.getStatus()); + // Both the primary write and the failure-triggered restore use the ID-verified overload, + // guarding against a role replaced under the same name mid-attempt in either direction. + ArgumentCaptor docCaptor = ArgumentCaptor.forClass(String.class); + verify(iamService, times(2)).updateAssumeRolePolicy( + eq("existing-role"), docCaptor.capture(), eq(role.getRoleId())); + List calls = docCaptor.getAllValues(); + assertEquals(mapper.readTree(newTrustPolicyJson), mapper.readTree(calls.get(0)), + "first call applies the template's new trust policy"); + assertEquals(priorTrustPolicy, calls.get(1), + "second call restores the role's pre-update trust policy after the failure"); + verify(iamService, never()).updateAssumeRolePolicy(anyString(), anyString()); + } + + @Test + void freshRoleCreationDoesNotRedundantlyUpdateTrustPolicy() { + IamRole role = role("new-role"); + when(iamService.createRole("new-role", "/", emptyTrustPolicy(), null, 3600, Map.of())) + .thenReturn(role); + + provisionRole("new-role", List.of()); + + verify(iamService, never()).updateAssumeRolePolicy(anyString(), anyString()); + verify(iamService, never()).updateAssumeRolePolicy(anyString(), anyString(), anyString()); + } + @Test void freshRoleCollisionDoesNotAdoptUserOwnedRole() { when(iamService.createRole("external-role", "/", emptyTrustPolicy(), null, 3600, Map.of())) diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamRoleTrustPolicyUpdateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamRoleTrustPolicyUpdateIntegrationTest.java new file mode 100644 index 0000000000..d0bc12142c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIamRoleTrustPolicyUpdateIntegrationTest.java @@ -0,0 +1,124 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; + +/** + * Regression for github.com/floci-io/floci/issues/2084: updating a stack that changes an + * existing {@code AWS::IAM::Role}'s {@code AssumeRolePolicyDocument} silently dropped the new + * trust policy — the role-adoption path (triggered by {@code EntityAlreadyExists} on retry/update) + * never applied the template's current document, even though the stack reported UPDATE_COMPLETE. + * IAM/CloudFormation are pure JVM services (Query API, XML response); no containers, Docker-free. + */ +@QuarkusTest +class CloudFormationIamRoleTrustPolicyUpdateIntegrationTest { + + private static final String CFN_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request"; + private static final String IAM_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/iam/aws4_request"; + + private static String stackWithTrustPolicy(String roleName, String principalService) { + return """ + { + "Resources": { + "Role": { + "Type": "AWS::IAM::Role", + "Properties": { + "RoleName": "%s", + "AssumeRolePolicyDocument": { + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Allow", + "Principal": {"Service": "%s"}, + "Action": "sts:AssumeRole" + }] + } + } + } + } + } + """.formatted(roleName, principalService); + } + + private static void createStack(String stackName, String template) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + } + + private static void updateStack(String stackName, String template) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "UpdateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + } + + private static void assertStackStatus(String stackName, String status) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("" + status + "")); + } + + @Test + void updateStack_iamRoleTrustPolicyChangeIsApplied() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "trust-policy-update-" + suffix; + String roleName = "trust-policy-role-" + suffix; + + createStack(stackName, stackWithTrustPolicy(roleName, "lambda.amazonaws.com")); + assertStackStatus(stackName, "CREATE_COMPLETE"); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetRole") + .formParam("RoleName", roleName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("lambda.amazonaws.com")); + + // Update: trust policy's principal changes from lambda to ec2 — the role already exists, + // so this exercises the adoption path (EntityAlreadyExists) rather than a fresh create. + updateStack(stackName, stackWithTrustPolicy(roleName, "ec2.amazonaws.com")); + assertStackStatus(stackName, "UPDATE_COMPLETE"); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", IAM_AUTH) + .formParam("Action", "GetRole") + .formParam("RoleName", roleName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("ec2.amazonaws.com")) + .body(not(containsString("lambda.amazonaws.com"))); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java index ee64d3c8c8..0f0fdf8b17 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java @@ -205,6 +205,43 @@ class IamServiceTest { assertEquals("Lambda role", role.getDescription()); } + @Test + void updateAssumeRolePolicyWithMatchingExpectedIdApplies() { + IamRole role = iamService.createRole("LambdaExec", "/", "{}", null, 3600, null); + String newDoc = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"}]}"; + + iamService.updateAssumeRolePolicy("LambdaExec", newDoc, role.getRoleId()); + + assertEquals(newDoc, iamService.getRole("LambdaExec").getAssumeRolePolicyDocument()); + } + + @Test + void updateAssumeRolePolicyWithNullExpectedIdSkipsCheck() { + iamService.createRole("LambdaExec", "/", "{}", null, 3600, null); + String newDoc = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"}]}"; + + iamService.updateAssumeRolePolicy("LambdaExec", newDoc, null); + + assertEquals(newDoc, iamService.getRole("LambdaExec").getAssumeRolePolicyDocument()); + } + + @Test + void updateAssumeRolePolicyRejectsMismatchedExpectedId() { + // github.com/floci-io/floci/issues/2084 (Greptile follow-up) — if the role named here was + // deleted and recreated under the same name since the caller last verified its identity, + // the recreated role has a different RoleId. The update must be refused rather than + // silently applied to a role the caller never actually verified owning. + IamRole role = iamService.createRole("LambdaExec", "/", "{}", null, 3600, null); + String originalDoc = role.getAssumeRolePolicyDocument(); + String newDoc = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"}]}"; + + AwsException ex = assertThrows(AwsException.class, + () -> iamService.updateAssumeRolePolicy("LambdaExec", newDoc, "AROAWRONGID")); + assertEquals("EntityAlreadyExists", ex.getErrorCode()); + assertEquals(originalDoc, iamService.getRole("LambdaExec").getAssumeRolePolicyDocument(), + "rejected update must not have changed the role's trust policy"); + } + @Test void deleteRoleWithAttachedPolicyFails() { iamService.createRole("LambdaExec", "/", "{}", null, 0, null);