mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): create AWS::IAM::Role inline Policies instead of silently dropping them (#1969)
* fix(cloudformation): create AWS::IAM::Role inline Policies instead of silently dropping them CreateStack now applies each entry of an IAM role's Policies array as an inline role policy (PutRolePolicy semantics), resolving intrinsics inside the policy document. Failures propagate so a policy that cannot be created fails the stack instead of reporting CREATE_COMPLETE without it. Fixes #1952 * refactor(cloudformation): move AWS::IAM::Role into its own provisioner Continues the per-service decomposition started with SQS (#1825) by taking the resource type this branch touches out of the CloudFormationResourceProvisioner switch, carrying the #1952 inline-Policies fix with it. - IamRoleCfnProvisioner owns provision and delete for AWS::IAM::Role: name resolution and same-stack adoption, managed-policy attachment with its rollback, the inline Policies of #1952, and the former deleteRoleSafe, whose only caller was the role delete arm. - CfnRollback holds what both halves of the migration need instead of duplicating it: the __FlociRollbackOwned attribute that CloudFormationService reads to decide rollback deletion, and attemptIamCleanup, still used by the AWS::IAM::Policy and AWS::IAM::ManagedPolicy arms. - ProvisionContext gains resolveStringList next to the resolveOptional and generatePhysicalName it already lifts from the monolith. - IamRoleCfnProvisionerTest covers the inline policies and the delete path with one mocked service; the existing role rollback tests keep running through the public provision entry point, now with the provisioner registered. Role provisioning behavior is otherwise unchanged. * fix(cloudformation): inline role policies fail loudly and unwind on failure Three review findings on the IAM role provisioner. A Policies entry with a null or absent PolicyDocument was skipped, so the stack reached CREATE_COMPLETE without the declared inline policy — the same silent drop this PR set out to fix, one level in. It is a ValidationError now. The inline-policy loop sat outside the block that unwinds a failed provision. When putRolePolicy failed after createRole succeeded, the resource went CREATE_FAILED, and because rollback only deletes resources that reached CREATE_COMPLETE, the role, its managed attachments and any inline policies already written were left behind. The loop now runs inside that block. A failed update that adopted an existing role kept whatever the half-applied attempt had granted. Inline writes are recorded with the value they replaced, so unwinding restores the previous document, or removes the policy when this attempt introduced the name. A role the stack did not create is not deleted. * fix(cloudformation): reconcile role policies an update stopped declaring An inline policy or managed attachment written by a previous execution and absent from the new template stayed on the role while the stack still reported UPDATE_COMPLETE. Both sets are now recorded on the resource and reconciled on the success path, so what the template drops is removed. Only names a previous execution recorded are touched, which leaves out-of-band policies alone. PolicyName is required on AWS::IAM::Role Policies. Generating one gave the same policy a fresh name on every execution, so an update accumulated copies instead of replacing it. A missing PolicyName is now a ValidationError, matching what this resource already does for a missing PolicyDocument. * fix(cloudformation): skip reconciliation of a role policy already removed deleteRolePolicy and detachRolePolicy both raise NoSuchEntity on an absent target, so a tracked policy removed out of band between executions failed an update whose desired end state already held. Reconciliation now skips what the role no longer carries.
This commit is contained in:
1 parent
6d829ff7a4
commit
8d2a5bdd46
8 files changed
+841
-136
No files matched your search
+6
-4
@@ -4,7 +4,9 @@ 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.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamRoleCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamPolicy;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
@@ -51,7 +53,7 @@ class CloudFormationIamAttachmentProvisionerTest {
|
||||
null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null,
|
||||
null,
|
||||
new CloudFormationResourceRegistry(List.of()));
|
||||
new CloudFormationResourceRegistry(List.of(new IamRoleCfnProvisioner(iamService))));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -131,11 +133,11 @@ class CloudFormationIamAttachmentProvisionerTest {
|
||||
"Role", "AWS::IAM::Role", """
|
||||
{"RoleName":"same-name","ManagedPolicyArns":["%s"]}
|
||||
""".formatted(NEW_POLICY), "same-name",
|
||||
Map.of("RoleId", "AROAOLD", CloudFormationResourceProvisioner.ROLLBACK_OWNED_ATTR, "true"));
|
||||
Map.of("RoleId", "AROAOLD", CfnRollback.ROLLBACK_OWNED_ATTR, "true"));
|
||||
|
||||
assertEquals("CREATE_FAILED", result.getStatus());
|
||||
assertEquals("already exists", result.getStatusReason());
|
||||
assertNull(result.getAttributes().get(CloudFormationResourceProvisioner.ROLLBACK_OWNED_ATTR));
|
||||
assertNull(result.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
|
||||
verify(iamService, never()).attachRolePolicy("same-name", NEW_POLICY);
|
||||
verify(iamService, never()).deleteRole("same-name");
|
||||
}
|
||||
@@ -247,7 +249,7 @@ class CloudFormationIamAttachmentProvisionerTest {
|
||||
assertEquals("CREATE_FAILED", result.getStatus());
|
||||
assertEquals("existing-role", result.getAttributes().get("InlineRoleTargets"));
|
||||
assertEquals("true", result.getAttributes().get(
|
||||
CloudFormationResourceProvisioner.ROLLBACK_OWNED_ATTR));
|
||||
CfnRollback.ROLLBACK_OWNED_ATTR));
|
||||
|
||||
provisioner.delete(result, "us-east-1");
|
||||
|
||||
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
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;
|
||||
|
||||
/**
|
||||
* End-to-end check that CloudFormation applies the inline {@code Policies} of an
|
||||
* AWS::IAM::Role (issue #1952): the policies must be visible through the IAM API,
|
||||
* intrinsics inside the policy documents must resolve, and DeleteStack must still
|
||||
* be able to remove the role.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationIamRoleInlinePoliciesIntegrationTest {
|
||||
|
||||
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";
|
||||
|
||||
@Test
|
||||
void createStackProvisionsInlineRolePoliciesAndDeleteStackRemovesRole() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String roleName = "cfn-inline-role-" + suffix;
|
||||
String bucketName = "cfn-inline-bucket-" + suffix;
|
||||
String stackName = "cfn-inline-stack-" + suffix;
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"DataBucket": {
|
||||
"Type": "AWS::S3::Bucket",
|
||||
"Properties": {"BucketName": "%s"}
|
||||
},
|
||||
"AppRole": {
|
||||
"Type": "AWS::IAM::Role",
|
||||
"Properties": {
|
||||
"RoleName": "%s",
|
||||
"AssumeRolePolicyDocument": {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Principal": {"Service": "lambda.amazonaws.com"},
|
||||
"Action": "sts:AssumeRole"
|
||||
}]
|
||||
},
|
||||
"Policies": [
|
||||
{
|
||||
"PolicyName": "bucket-read",
|
||||
"PolicyDocument": {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Action": "s3:GetObject",
|
||||
"Resource": {"Fn::GetAtt": ["DataBucket", "Arn"]}
|
||||
}]
|
||||
}
|
||||
},
|
||||
{
|
||||
"PolicyName": "log-write",
|
||||
"PolicyDocument": {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Action": "logs:PutLogEvents",
|
||||
"Resource": "*"
|
||||
}]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(bucketName, roleName);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.formParam("Capabilities.member.1", "CAPABILITY_NAMED_IAM")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
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>CREATE_COMPLETE</StackStatus>"));
|
||||
|
||||
// Both inline policies exist on the role.
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "ListRolePolicies")
|
||||
.formParam("RoleName", roleName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("bucket-read"))
|
||||
.body(containsString("log-write"));
|
||||
|
||||
// The stored document resolved Fn::GetAtt to the bucket ARN.
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "GetRolePolicy")
|
||||
.formParam("RoleName", roleName)
|
||||
.formParam("PolicyName", "bucket-read")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("s3:GetObject"))
|
||||
.body(containsString("arn:aws:s3:::" + bucketName))
|
||||
.body(not(containsString("Fn::GetAtt")));
|
||||
|
||||
// DeleteStack must remove the role despite its inline policies.
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DeleteStack")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", IAM_AUTH)
|
||||
.formParam("Action", "GetRole")
|
||||
.formParam("RoleName", roleName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404);
|
||||
}
|
||||
}
|
||||
+337
@@ -0,0 +1,337 @@
|
||||
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;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
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.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;
|
||||
|
||||
/**
|
||||
* The IAM role CFN provisioner in isolation, with the inline {@code Policies} behavior of #1952.
|
||||
* Rollback and role-adoption paths are covered end to end through the public provision entry point
|
||||
* in {@code CloudFormationIamAttachmentProvisionerTest}.
|
||||
*/
|
||||
class IamRoleCfnProvisionerTest {
|
||||
|
||||
private static final String ACCOUNT_ID = "000000000000";
|
||||
private static final String EMPTY_TRUST = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
|
||||
|
||||
private final IamService iam = mock(IamService.class);
|
||||
private final IamRoleCfnProvisioner provisioner = new IamRoleCfnProvisioner(iam);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private ProvisionContext ctx() {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
return new ProvisionContext(engine, "us-east-1", ACCOUNT_ID, "test-stack");
|
||||
}
|
||||
|
||||
private StackResource resource() {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("AppRole");
|
||||
r.setResourceType("AWS::IAM::Role");
|
||||
r.setAttributes(new HashMap<>());
|
||||
return r;
|
||||
}
|
||||
|
||||
private JsonNode props(String json) {
|
||||
try {
|
||||
return mapper.readTree(json);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private IamRole stubCreate(String roleName) {
|
||||
IamRole role = new IamRole("AROA" + roleName, roleName, "/",
|
||||
"arn:aws:iam::" + ACCOUNT_ID + ":role/" + roleName, EMPTY_TRUST);
|
||||
when(iam.createRole(eq(roleName), eq("/"), anyString(), any(), eq(3600), eq(Map.of())))
|
||||
.thenReturn(role);
|
||||
return role;
|
||||
}
|
||||
|
||||
@Test
|
||||
void inlinePoliciesArePutOnTheRoleWithResolvedDocuments() {
|
||||
stubCreate("app-role");
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, props("""
|
||||
{
|
||||
"RoleName": "app-role",
|
||||
"Policies": [
|
||||
{"PolicyName": "bucket-read",
|
||||
"PolicyDocument": {"Version": "2012-10-17", "Statement": []}},
|
||||
{"PolicyName": "log-write",
|
||||
"PolicyDocument": {"Version": "2012-10-17", "Statement": []}}
|
||||
]
|
||||
}
|
||||
"""), ctx());
|
||||
|
||||
assertEquals("app-role", r.getPhysicalId());
|
||||
InOrder order = inOrder(iam);
|
||||
order.verify(iam).putRolePolicy("app-role", "bucket-read", EMPTY_TRUST);
|
||||
order.verify(iam).putRolePolicy("app-role", "log-write", EMPTY_TRUST);
|
||||
}
|
||||
|
||||
@Test
|
||||
void inlinePolicyWithoutANameFailsTheResource() {
|
||||
// PolicyName is required on AWS::IAM::Role Policies. Generating one gave the same policy a
|
||||
// fresh name on every execution, so an update accumulated copies instead of replacing it.
|
||||
stubCreate("app-role");
|
||||
StackResource r = resource();
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
|
||||
{
|
||||
"RoleName": "app-role",
|
||||
"Policies": [{"PolicyDocument": {"Version": "2012-10-17", "Statement": []}}]
|
||||
}
|
||||
"""), ctx()));
|
||||
|
||||
assertEquals("ValidationError", failure.getErrorCode());
|
||||
verify(iam, never()).putRolePolicy(anyString(), anyString(), anyString());
|
||||
verify(iam).deleteRole("app-role");
|
||||
assertNull(r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inlinePolicyWithoutADocumentFailsTheResource() {
|
||||
// Skipping it reached CREATE_COMPLETE without the declared policy — the same class of
|
||||
// bug as the silent drop this PR is about.
|
||||
stubCreate("app-role");
|
||||
StackResource r = resource();
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
|
||||
{"RoleName": "app-role", "Policies": [{"PolicyName": "no-document"}]}
|
||||
"""), ctx()));
|
||||
|
||||
assertEquals("ValidationError", failure.getErrorCode());
|
||||
verify(iam, never()).putRolePolicy(anyString(), anyString(), anyString());
|
||||
// The role this attempt created is cleaned up rather than left behind.
|
||||
verify(iam).deleteRole("app-role");
|
||||
assertNull(r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inlinePolicyFailureRemovesTheRoleAndTheEarlierInlineWrites() {
|
||||
stubCreate("app-role");
|
||||
doThrow(new AwsException("MalformedPolicyDocument", "bad policy", 400))
|
||||
.when(iam).putRolePolicy(eq("app-role"), eq("second"), anyString());
|
||||
StackResource r = resource();
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
|
||||
{
|
||||
"RoleName": "app-role",
|
||||
"Policies": [
|
||||
{"PolicyName": "first", "PolicyDocument": {"Version": "2012-10-17", "Statement": []}},
|
||||
{"PolicyName": "second", "PolicyDocument": {"Version": "2012-10-17", "Statement": []}}
|
||||
]
|
||||
}
|
||||
"""), ctx()));
|
||||
|
||||
// "first" was written by this attempt and had no prior value, so it is removed, and the
|
||||
// role goes with it. Previously both survived a CREATE_FAILED.
|
||||
verify(iam).deleteRolePolicy("app-role", "first");
|
||||
verify(iam).deleteRole("app-role");
|
||||
assertNull(r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateRemovesTheInlinePoliciesAndAttachmentsTheTemplateDropped() {
|
||||
// A policy the previous execution wrote and the new template no longer declares used to
|
||||
// stay on the role while the stack still reported UPDATE_COMPLETE.
|
||||
IamRole existing = new IamRole("AROAapp-role", "app-role", "/",
|
||||
"arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST);
|
||||
existing.getInlinePolicies().put("keep", EMPTY_TRUST);
|
||||
existing.getInlinePolicies().put("drop", EMPTY_TRUST);
|
||||
existing.getAttachedPolicyArns().add("arn:aws:iam::aws:policy/Keep");
|
||||
existing.getAttachedPolicyArns().add("arn:aws:iam::aws:policy/Drop");
|
||||
when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), eq(Map.of())))
|
||||
.thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
|
||||
when(iam.getRole("app-role")).thenReturn(existing);
|
||||
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("app-role");
|
||||
r.getAttributes().put("RoleId", "AROAapp-role");
|
||||
r.getAttributes().put("__FlociInlinePolicyNames", "keep\ndrop");
|
||||
r.getAttributes().put("__FlociManagedPolicyArns",
|
||||
"arn:aws:iam::aws:policy/Keep\narn:aws:iam::aws:policy/Drop");
|
||||
|
||||
provisioner.provision(r, props("""
|
||||
{
|
||||
"RoleName": "app-role",
|
||||
"ManagedPolicyArns": ["arn:aws:iam::aws:policy/Keep"],
|
||||
"Policies": [
|
||||
{"PolicyName": "keep", "PolicyDocument": {"Version": "2012-10-17", "Statement": []}}
|
||||
]
|
||||
}
|
||||
"""), ctx());
|
||||
|
||||
verify(iam).deleteRolePolicy("app-role", "drop");
|
||||
verify(iam).detachRolePolicy("app-role", "arn:aws:iam::aws:policy/Drop");
|
||||
verify(iam, never()).deleteRolePolicy("app-role", "keep");
|
||||
verify(iam, never()).detachRolePolicy("app-role", "arn:aws:iam::aws:policy/Keep");
|
||||
assertEquals("keep", r.getAttributes().get("__FlociInlinePolicyNames"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateToleratesATrackedPolicyThatIsAlreadyGone() {
|
||||
// Removed out of band between executions. deleteRolePolicy and detachRolePolicy both raise
|
||||
// NoSuchEntity on an absent target, which would fail an update whose desired end state,
|
||||
// the policy not being on the role, already holds.
|
||||
IamRole existing = new IamRole("AROAapp-role", "app-role", "/",
|
||||
"arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST);
|
||||
when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), eq(Map.of())))
|
||||
.thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
|
||||
when(iam.getRole("app-role")).thenReturn(existing);
|
||||
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("app-role");
|
||||
r.getAttributes().put("RoleId", "AROAapp-role");
|
||||
r.getAttributes().put("__FlociInlinePolicyNames", "gone");
|
||||
r.getAttributes().put("__FlociManagedPolicyArns", "arn:aws:iam::aws:policy/Gone");
|
||||
|
||||
provisioner.provision(r, props("""
|
||||
{"RoleName": "app-role", "Policies": []}
|
||||
"""), ctx());
|
||||
|
||||
verify(iam, never()).deleteRolePolicy(anyString(), anyString());
|
||||
verify(iam, never()).detachRolePolicy(anyString(), anyString());
|
||||
assertNull(r.getAttributes().get("__FlociInlinePolicyNames"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateLeavesInlinePoliciesTheStackNeverWroteAlone() {
|
||||
// Only names a previous execution recorded are removed, so a policy added out of band
|
||||
// survives an update that does not declare it.
|
||||
IamRole existing = new IamRole("AROAapp-role", "app-role", "/",
|
||||
"arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST);
|
||||
existing.getInlinePolicies().put("added-out-of-band", EMPTY_TRUST);
|
||||
when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), eq(Map.of())))
|
||||
.thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
|
||||
when(iam.getRole("app-role")).thenReturn(existing);
|
||||
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("app-role");
|
||||
r.getAttributes().put("RoleId", "AROAapp-role");
|
||||
|
||||
provisioner.provision(r, props("""
|
||||
{"RoleName": "app-role", "Policies": []}
|
||||
"""), ctx());
|
||||
|
||||
verify(iam, never()).deleteRolePolicy(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedUpdateRestoresTheInlinePolicyItAlreadyOverwrote() {
|
||||
// An update that adopts an existing role must not keep the permissions a half-applied
|
||||
// attempt granted, and must not delete a role it did not create.
|
||||
String priorDocument = "{\"Version\":\"2012-10-17\",\"Statement\":[\"prior\"]}";
|
||||
IamRole existing = new IamRole("AROAapp-role", "app-role", "/",
|
||||
"arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST);
|
||||
existing.getInlinePolicies().put("first", priorDocument);
|
||||
when(iam.createRole(eq("app-role"), eq("/"), anyString(), any(), eq(3600), eq(Map.of())))
|
||||
.thenThrow(new AwsException("EntityAlreadyExists", "exists", 409));
|
||||
when(iam.getRole("app-role")).thenReturn(existing);
|
||||
doThrow(new AwsException("MalformedPolicyDocument", "bad policy", 400))
|
||||
.when(iam).putRolePolicy(eq("app-role"), eq("second"), anyString());
|
||||
|
||||
StackResource r = resource();
|
||||
r.setPhysicalId("app-role");
|
||||
r.getAttributes().put("RoleId", "AROAapp-role");
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
|
||||
{
|
||||
"RoleName": "app-role",
|
||||
"Policies": [
|
||||
{"PolicyName": "first", "PolicyDocument": {"Version": "2012-10-17", "Statement": []}},
|
||||
{"PolicyName": "second", "PolicyDocument": {"Version": "2012-10-17", "Statement": []}}
|
||||
]
|
||||
}
|
||||
"""), ctx()));
|
||||
|
||||
InOrder order = inOrder(iam);
|
||||
order.verify(iam).putRolePolicy("app-role", "first", EMPTY_TRUST);
|
||||
order.verify(iam).putRolePolicy("app-role", "first", priorDocument);
|
||||
verify(iam, never()).deleteRolePolicy(anyString(), anyString());
|
||||
verify(iam, never()).deleteRole(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void inlinePolicyFailureFailsTheResourceInsteadOfDroppingThePolicy() {
|
||||
stubCreate("app-role");
|
||||
doThrow(new AwsException("MalformedPolicyDocument", "bad policy", 400))
|
||||
.when(iam).putRolePolicy(eq("app-role"), eq("broken"), anyString());
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(resource(), props("""
|
||||
{
|
||||
"RoleName": "app-role",
|
||||
"Policies": [{"PolicyName": "broken",
|
||||
"PolicyDocument": {"Version": "2012-10-17", "Statement": []}}]
|
||||
}
|
||||
"""), ctx()));
|
||||
|
||||
assertEquals("MalformedPolicyDocument", failure.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRemovesAttachedAndInlinePoliciesBeforeTheRole() {
|
||||
IamRole role = new IamRole("AROAapp-role", "app-role", "/",
|
||||
"arn:aws:iam::" + ACCOUNT_ID + ":role/app-role", EMPTY_TRUST);
|
||||
role.getAttachedPolicyArns().add("arn:aws:iam::aws:policy/ReadOnlyAccess");
|
||||
role.getInlinePolicies().put("bucket-read", EMPTY_TRUST);
|
||||
when(iam.getRole("app-role")).thenReturn(role);
|
||||
|
||||
provisioner.delete("AWS::IAM::Role", "app-role", "us-east-1");
|
||||
|
||||
InOrder order = inOrder(iam);
|
||||
order.verify(iam).detachRolePolicy("app-role", "arn:aws:iam::aws:policy/ReadOnlyAccess");
|
||||
order.verify(iam).deleteRolePolicy("app-role", "bucket-read");
|
||||
order.verify(iam).deleteRole("app-role");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteTreatsAnAlreadyMissingRoleAsDeleted() {
|
||||
when(iam.getRole("gone-role")).thenThrow(new AwsException("NoSuchEntity", "gone", 404));
|
||||
|
||||
provisioner.delete("AWS::IAM::Role", "gone-role", "us-east-1");
|
||||
|
||||
verify(iam, never()).deleteRole("gone-role");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletePropagatesUnexpectedLookupFailures() {
|
||||
when(iam.getRole("denied-role")).thenThrow(new AwsException("AccessDenied", "denied", 403));
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> provisioner.delete("AWS::IAM::Role", "denied-role", "us-east-1"));
|
||||
|
||||
assertEquals("AccessDenied", failure.getErrorCode());
|
||||
verify(iam, never()).deleteRole("denied-role");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user