mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): apply AssumeRolePolicyDocument when adopting an existing IAM role on update (#2143)
provisionIamRole's adoption path (triggered by EntityAlreadyExists when a same-stack UpdateStack retries against a role that already exists) fetched the existing role via getRole() but never applied the template's current AssumeRolePolicyDocument. A changed trust policy was silently dropped while the stack still reported UPDATE_COMPLETE. Routes the adoption path through the existing IamService.updateAssumeRolePolicy helper, mirroring how createRole() already applies the document on first create. If a later step in the 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. Captures the role's prior trust policy before applying the update and restores it in the existing failure-cleanup path alongside policy detachment. Does not re-fetch the role after applying the trust policy: nothing downstream reads anything affected by that update (Arn, RoleId, AttachedPolicyArns are unchanged by it), and a failing re-fetch there would escape before the restoration catch block, leaving the new trust policy active despite a rolled-back update. Adds an ID-verified updateAssumeRolePolicy(name, doc, expectedRoleId) overload in IamService: a role deleted and recreated under the same name between the earlier identity check and this write would otherwise silently receive an update meant for the role this stack actually owns. Both the primary write and the failure-triggered restore use this overload - restoring a trust policy is just as consequential as applying one, so both directions get the same identity guarantee. Fixes #2084.
This commit is contained in:
1 parent
a2b20cc085
commit
4a5fae4dcd
5 files changed
+285
No files matched your search
+71
@@ -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<String> 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<String> docCaptor = ArgumentCaptor.forClass(String.class);
|
||||
verify(iamService, times(2)).updateAssumeRolePolicy(
|
||||
eq("existing-role"), docCaptor.capture(), eq(role.getRoleId()));
|
||||
List<String> 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()))
|
||||
|
||||
+124
@@ -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("<StackStatus>" + status + "</StackStatus>"));
|
||||
}
|
||||
|
||||
@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")));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user