mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iam): check iam:PassRole for ECS, Step Functions, EventBridge and CloudFormation (#5971)
Under IAM enforcement, a request that handed one of these services a role needed no iam:PassRole on it. A user allowed only ecs:RegisterTaskDefinition and ecs:RunTask could start a task with any role in the account, and with ECS task-role credentials on, the task got that role's credentials. The IAM user guide requires the permission for every role passed to a service. AWS's Service Reference names the service each operation passes its role to, and the check now covers these operations as it already covers Lambda and EC2: - ECS: RegisterTaskDefinition passes its task and execution roles to ecs-tasks.amazonaws.com. RunTask and StartTask pass the task definition's roles and any role override, and CreateService, UpdateService and CreateTaskSet pass the roles of the task definition they name. The infrastructure roles go to ecs.amazonaws.com: a managed EBS volume's role, the service role, the load balancer, lifecycle hook, Service Connect TLS and VPC Lattice roles, and a Managed Instances provider's infrastructure role. A role given by name is the role of that name in the caller's account. - Step Functions: CreateStateMachine and UpdateStateMachine pass roleArn to states.amazonaws.com, in a JSON or a CBOR body, gzip-encoded or not, since the CBOR endpoint decompresses a body before running it. - EventBridge: PutRule passes RoleArn, and PutTargets each target's RoleArn, to events.amazonaws.com. - CloudFormation: CreateStack, UpdateStack, DeleteStack, CreateChangeSet and ContinueUpdateRollback pass RoleARN when the request names one. A later operation that names none reuses the stack's role without the check, as CloudFormation does. CreateStackSet and UpdateStackSet pass AdministrationRoleARN, or the default AWSCloudFormationStackSetAdministrationRole for a self-managed StackSet, as the CloudFormation user guide says. An update goes by the StackSet's own permission model, which Floci keeps whatever PermissionModel the request names. A role override on RunTask is checked as well as the task definition's roles, not instead of them, because Floci runs a task with the definition's task role. The task definition and the StackSet's permission model are looked up through a new PassedRoleLookup interface, which ECS and the StackSet service implement, so the filter does not depend on either service. Three services are left out. Floci authorizes Cloud Control as cloudcontrolapi:*, where AWS uses cloudformation:*, so its RoleArn waits until that namespace is fixed. EventBridge Scheduler and Pipes are REST services that no IAM route rule maps to an action yet, so enforcement does not check their requests at all, iam:PassRole included.
This commit is contained in:
1 parent
ee795d644c
commit
eba0f72255
10 files changed
+884
-41
No files matched your search
@@ -144,7 +144,7 @@ class IamEnforcementFilterTest {
|
||||
new AwsQueryServiceResolver(catalog), arnBuilder, requestContext,
|
||||
conditionContextResolver, mock(CloudTrailService.class),
|
||||
mock(CurrentVertxRequest.class),
|
||||
catalog, scpProvider, sessionAccountLookup, null, clock, resourceInfo);
|
||||
catalog, scpProvider, sessionAccountLookup, null, null, clock, resourceInfo);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
import io.github.hectorvent.floci.core.common.PassedRoles.PassedRole;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Where each operation carries the roles it passes, and the service each goes to. The enforcement
|
||||
* of the check is covered by {@code IamPassRoleEnforcementIntegrationTest}; this covers the table.
|
||||
*/
|
||||
class PassedRolesTest {
|
||||
|
||||
private static final String ROLES = "arn:aws:iam::111122223333:role/";
|
||||
private static final String ECS = "ecs.amazonaws.com";
|
||||
private static final String ECS_TASKS = "ecs-tasks.amazonaws.com";
|
||||
private static final String CLOUDFORMATION = "cloudformation.amazonaws.com";
|
||||
private static final String DEFAULT_ADMINISTRATION = ROLES + "AWSCloudFormationStackSetAdministrationRole";
|
||||
|
||||
/** A task definition {@code web:3} holding a task role by ARN and an execution role by name, and two StackSets. */
|
||||
private static final PassedRoles.Lookups LOOKUPS = new PassedRoles.Lookups() {
|
||||
@Override
|
||||
public List<String> instanceProfileRoleArns(String profileName, String profileArn) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> taskDefinitionRoles(String reference) {
|
||||
return "web:3".equals(reference) ? List.of(ROLES + "web-task", "web-execution") : List.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> stackSetPermissionModel(String stackSetName) {
|
||||
return switch (stackSetName) {
|
||||
case "own-set" -> Optional.of("SELF_MANAGED");
|
||||
case "org-set" -> Optional.of("SERVICE_MANAGED");
|
||||
default -> Optional.empty();
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public String roleArn(String roleName) {
|
||||
return ROLES + roleName;
|
||||
}
|
||||
};
|
||||
|
||||
@Test
|
||||
void aTaskDefinitionPassesItsTaskAndExecutionRolesToEcsTasksByNameOrArn() {
|
||||
assertEquals(List.of(passed("app", ECS_TASKS), passed("exec", ECS_TASKS)),
|
||||
PassedRoles.of("ecs:RegisterTaskDefinition",
|
||||
json("{\"taskRoleArn\":\"app\",\"executionRoleArn\":\"" + ROLES + "exec\"}"), LOOKUPS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTaskPassesItsDefinitionsRolesItsOverridesAndItsVolumesInfrastructureRole() {
|
||||
String body = """
|
||||
{"taskDefinition":"web:3","overrides":{"taskRoleArn":"%1$sover-task","executionRoleArn":"%1$sover-exec"},
|
||||
"volumeConfigurations":[{"name":"a","managedEBSVolume":{"roleArn":"%1$sebs"}}]}"""
|
||||
.formatted(ROLES);
|
||||
List<PassedRole> expected = List.of(passed("web-task", ECS_TASKS), passed("web-execution", ECS_TASKS),
|
||||
passed("over-task", ECS_TASKS), passed("over-exec", ECS_TASKS), passed("ebs", ECS));
|
||||
|
||||
assertEquals(expected, PassedRoles.of("ecs:RunTask", json(body), LOOKUPS));
|
||||
assertEquals(expected, PassedRoles.of("ecs:StartTask", json(body), LOOKUPS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTaskDefinitionThatDoesNotExistPassesNothing() {
|
||||
assertEquals(List.of(), PassedRoles.of("ecs:RunTask", json("{\"taskDefinition\":\"missing\"}"), LOOKUPS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServicePassesItsDefinitionsRolesAndEachInfrastructureRole() {
|
||||
String body = """
|
||||
{"taskDefinition":"web:3","role":"legacy",
|
||||
"loadBalancers":[{"advancedConfiguration":{"roleArn":"%1$slb"}}],
|
||||
"deploymentConfiguration":{"lifecycleHooks":[{"roleArn":"%1$shook"}]},
|
||||
"serviceConnectConfiguration":{"services":[{"tls":{"roleArn":"%1$stls"}}]},
|
||||
"volumeConfigurations":[{"managedEBSVolume":{"roleArn":"%1$sebs"}}],
|
||||
"vpcLatticeConfigurations":[{"roleArn":"%1$slattice"}]}"""
|
||||
.formatted(ROLES);
|
||||
List<PassedRole> expected = List.of(passed("web-task", ECS_TASKS), passed("web-execution", ECS_TASKS),
|
||||
passed("legacy", ECS), passed("lb", ECS), passed("hook", ECS), passed("tls", ECS),
|
||||
passed("ebs", ECS), passed("lattice", ECS));
|
||||
|
||||
assertEquals(expected, PassedRoles.of("ecs:CreateService", json(body), LOOKUPS));
|
||||
assertEquals(expected, PassedRoles.of("ecs:UpdateService", json(body), LOOKUPS));
|
||||
// An update that keeps its task definition passes only the roles it names.
|
||||
assertEquals(List.of(passed("lattice", ECS)), PassedRoles.of("ecs:UpdateService",
|
||||
json("{\"vpcLatticeConfigurations\":[{\"roleArn\":\"" + ROLES + "lattice\"}]}"), LOOKUPS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTaskSetPassesItsDefinitionsRolesOnly() {
|
||||
// The Service Reference gives CreateTaskSet ecs-tasks.amazonaws.com alone.
|
||||
String body = "{\"taskDefinition\":\"web:3\",\"loadBalancers\":[{\"advancedConfiguration\":{\"roleArn\":\""
|
||||
+ ROLES + "lb\"}}]}";
|
||||
assertEquals(List.of(passed("web-task", ECS_TASKS), passed("web-execution", ECS_TASKS)),
|
||||
PassedRoles.of("ecs:CreateTaskSet", json(body), LOOKUPS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aManagedInstancesProviderPassesItsInfrastructureRoleToEcs() {
|
||||
String body = "{\"managedInstancesProvider\":{\"infrastructureRoleArn\":\"" + ROLES + "infra\"}}";
|
||||
assertEquals(List.of(passed("infra", ECS)), PassedRoles.of("ecs:CreateCapacityProvider", json(body), LOOKUPS));
|
||||
assertEquals(List.of(passed("infra", ECS)), PassedRoles.of("ecs:UpdateCapacityProvider", json(body), LOOKUPS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stepFunctionsAndEventBridgePassTheRoleTheyName() throws IOException {
|
||||
String role = "{\"roleArn\":\"" + ROLES + "sm\"}";
|
||||
assertEquals(List.of(passed("sm", "states.amazonaws.com")),
|
||||
PassedRoles.of("states:CreateStateMachine", json(role), LOOKUPS));
|
||||
assertEquals(List.of(passed("sm", "states.amazonaws.com")),
|
||||
PassedRoles.of("states:UpdateStateMachine", cbor(role), LOOKUPS));
|
||||
assertEquals(List.of(passed("sm", "states.amazonaws.com")),
|
||||
PassedRoles.of("states:CreateStateMachine", gzippedCbor(role), LOOKUPS));
|
||||
assertEquals(List.of(passed("rule", "events.amazonaws.com")),
|
||||
PassedRoles.of("events:PutRule", json("{\"RoleArn\":\"" + ROLES + "rule\"}"), LOOKUPS));
|
||||
assertEquals(List.of(passed("one", "events.amazonaws.com"), passed("two", "events.amazonaws.com")),
|
||||
PassedRoles.of("events:PutTargets", json("{\"Targets\":[{\"RoleArn\":\"" + ROLES + "one\"},{},"
|
||||
+ "{\"RoleArn\":\"" + ROLES + "two\"}]}"), LOOKUPS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void outsideEcsOnlyARoleArnIsPassed() {
|
||||
assertEquals(List.of(), PassedRoles.of("states:CreateStateMachine", json("{\"roleArn\":\"sm\"}"), LOOKUPS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStackOperationPassesTheServiceRoleItNames() {
|
||||
for (String action : List.of("CreateStack", "UpdateStack", "DeleteStack", "CreateChangeSet",
|
||||
"ContinueUpdateRollback")) {
|
||||
assertEquals(List.of(passed("stack", CLOUDFORMATION)),
|
||||
PassedRoles.of("cloudformation:" + action, form("RoleARN=" + ROLES + "stack"), LOOKUPS), action);
|
||||
assertEquals(List.of(), PassedRoles.of("cloudformation:" + action, form("StackName=s"), LOOKUPS), action);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStackSetPassesTheAdministrationRoleItNamesOrTheDefaultOneWhenSelfManaged() {
|
||||
PassedRole defaultRole = new PassedRole(DEFAULT_ADMINISTRATION, CLOUDFORMATION);
|
||||
assertEquals(List.of(defaultRole), PassedRoles.of("cloudformation:CreateStackSet", form("StackSetName=new"), LOOKUPS));
|
||||
assertEquals(List.of(), PassedRoles.of("cloudformation:CreateStackSet",
|
||||
form("StackSetName=new&PermissionModel=SERVICE_MANAGED"), LOOKUPS));
|
||||
assertEquals(List.of(passed("admin", CLOUDFORMATION)), PassedRoles.of("cloudformation:CreateStackSet",
|
||||
form("StackSetName=new&AdministrationRoleARN=" + ROLES + "admin"), LOOKUPS));
|
||||
|
||||
// An update goes by the StackSet's own permission model, which a PermissionModel it names doesn't change.
|
||||
assertEquals(List.of(defaultRole), PassedRoles.of("cloudformation:UpdateStackSet", form("StackSetName=own-set"), LOOKUPS));
|
||||
assertEquals(List.of(defaultRole), PassedRoles.of("cloudformation:UpdateStackSet",
|
||||
form("StackSetName=own-set&PermissionModel=SERVICE_MANAGED"), LOOKUPS));
|
||||
assertEquals(List.of(), PassedRoles.of("cloudformation:UpdateStackSet", form("StackSetName=org-set"), LOOKUPS));
|
||||
assertEquals(List.of(), PassedRoles.of("cloudformation:UpdateStackSet",
|
||||
form("StackSetName=org-set&PermissionModel=SELF_MANAGED"), LOOKUPS));
|
||||
assertEquals(List.of(), PassedRoles.of("cloudformation:UpdateStackSet", form("StackSetName=missing"), LOOKUPS));
|
||||
assertEquals(List.of(passed("admin", CLOUDFORMATION)), PassedRoles.of("cloudformation:UpdateStackSet",
|
||||
form("StackSetName=org-set&AdministrationRoleARN=" + ROLES + "admin"), LOOKUPS));
|
||||
}
|
||||
|
||||
private static PassedRole passed(String roleName, String service) {
|
||||
return new PassedRole(ROLES + roleName, service);
|
||||
}
|
||||
|
||||
private static ContainerRequestContext json(String body) {
|
||||
return request("application/x-amz-json-1.1", body.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static ContainerRequestContext cbor(String body) throws IOException {
|
||||
return request("application/cbor",
|
||||
new ObjectMapper(new CBORFactory()).writeValueAsBytes(new ObjectMapper().readTree(body)));
|
||||
}
|
||||
|
||||
private static ContainerRequestContext gzippedCbor(String body) throws IOException {
|
||||
ByteArrayOutputStream compressed = new ByteArrayOutputStream();
|
||||
try (GZIPOutputStream out = new GZIPOutputStream(compressed)) {
|
||||
out.write(new ObjectMapper(new CBORFactory()).writeValueAsBytes(new ObjectMapper().readTree(body)));
|
||||
}
|
||||
ContainerRequestContext request = request("application/cbor", compressed.toByteArray());
|
||||
when(request.getHeaderString("Content-Encoding")).thenReturn("gzip");
|
||||
return request;
|
||||
}
|
||||
|
||||
private static ContainerRequestContext form(String body) {
|
||||
return request("application/x-www-form-urlencoded", body.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static ContainerRequestContext request(String mediaType, byte[] body) {
|
||||
ContainerRequestContext request = mock(ContainerRequestContext.class);
|
||||
when(request.getMediaType()).thenReturn(MediaType.valueOf(mediaType));
|
||||
when(request.getEntityStream()).thenAnswer(invocation -> new ByteArrayInputStream(body));
|
||||
return request;
|
||||
}
|
||||
}
|
||||
+340
-3
@@ -1,8 +1,12 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
@@ -10,23 +14,28 @@ import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* A request that passes a role to Lambda or EC2 also needs {@code iam:PassRole} on that role, with
|
||||
* A request that passes a role to a service also needs {@code iam:PassRole} on that role, with
|
||||
* {@code iam:PassedToService} naming the service, as the IAM user guide requires: "To pass a role
|
||||
* (and its permissions) to an AWS service, a user must have permissions to pass the role to the
|
||||
* service." Without it a user allowed only to create functions or launch instances could hand them
|
||||
* any role in the account and act with its permissions.
|
||||
* service." Without it a user allowed only to create functions, launch instances or run tasks could
|
||||
* hand them any role in the account and act with its permissions.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
@@ -35,6 +44,10 @@ class IamPassRoleEnforcementIntegrationTest {
|
||||
private static final String ADMIN = "test";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String IMAGE = "ami-0abcdef1234567890";
|
||||
private static final String ECS_TASKS = "ecs-tasks.amazonaws.com";
|
||||
private static final String ECS = "ecs.amazonaws.com";
|
||||
private static final String QUEUE_ARN = "arn:aws:sqs:us-east-1:" + ACCOUNT + ":passrole-queue";
|
||||
private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory());
|
||||
|
||||
@TestHTTPResource("/")
|
||||
static URI baseUri;
|
||||
@@ -42,6 +55,11 @@ class IamPassRoleEnforcementIntegrationTest {
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void creatingAFunctionNeedsPassRoleOnItsExecutionRoleForLambda() {
|
||||
String role = role("fn-exec");
|
||||
@@ -221,6 +239,212 @@ class IamPassRoleEnforcementIntegrationTest {
|
||||
.formParam("FlowLogId.1", flowLogId).post("/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTaskDefinitionNeedsPassRoleOnItsTaskAndExecutionRolesForEcsTasks() {
|
||||
String taskRole = role("ecs-task");
|
||||
String executionRole = role("ecs-execution");
|
||||
User user = user("passrole-ecs-register");
|
||||
String family = "passrole-family-" + suffix();
|
||||
String body = taskDefinition(family, taskRole, executionRole);
|
||||
|
||||
user.policy(allow("ecs:RegisterTaskDefinition", "*") + "," + passRole(taskRole, ECS_TASKS));
|
||||
deniedJson(user.ecs("RegisterTaskDefinition").body(body).post("/").then());
|
||||
|
||||
// Task roles go to ecs-tasks.amazonaws.com: a grant for ecs.amazonaws.com does not cover them.
|
||||
user.policy(allow("ecs:RegisterTaskDefinition", "*") + "," + passRole(taskRole, ECS_TASKS) + ","
|
||||
+ passRole(executionRole, ECS));
|
||||
deniedJson(user.ecs("RegisterTaskDefinition").body(body).post("/").then());
|
||||
|
||||
user.policy(allow("ecs:RegisterTaskDefinition", "*") + "," + passRole(taskRole, ECS_TASKS) + ","
|
||||
+ passRole(executionRole, ECS_TASKS));
|
||||
user.ecs("RegisterTaskDefinition").body(body).post("/").then().statusCode(200);
|
||||
deregisterLater(family + ":1");
|
||||
|
||||
// A task role given by its name is the role of that name in the caller's account.
|
||||
String named = taskDefinition(family, roleName(taskRole), null);
|
||||
user.policy(allow("ecs:RegisterTaskDefinition", "*"));
|
||||
deniedJson(user.ecs("RegisterTaskDefinition").body(named).post("/").then());
|
||||
user.policy(allow("ecs:RegisterTaskDefinition", "*") + "," + passRole(taskRole, ECS_TASKS));
|
||||
user.ecs("RegisterTaskDefinition").body(named).post("/").then().statusCode(200);
|
||||
deregisterLater(family + ":2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void runningATaskNeedsPassRoleOnItsTaskDefinitionsRolesAndOnAnyOverride() {
|
||||
String taskRole = role("ecs-run");
|
||||
String override = role("ecs-override");
|
||||
String family = registerTaskDefinition(taskRole);
|
||||
String cluster = cluster();
|
||||
User user = user("passrole-ecs-run");
|
||||
|
||||
// The caller names no role: the one it passes is the task definition's.
|
||||
user.policy(allow("ecs:RunTask", "*"));
|
||||
deniedJson(user.ecs("RunTask").body(runTask(cluster, family, null)).post("/").then());
|
||||
|
||||
user.policy(allow("ecs:RunTask", "*") + "," + passRole(taskRole, ECS_TASKS));
|
||||
stopLater(cluster, user.ecs("RunTask").body(runTask(cluster, family, null)).post("/").then()
|
||||
.statusCode(200).extract().path("tasks[0].taskArn"));
|
||||
|
||||
// An override is passed as well.
|
||||
deniedJson(user.ecs("RunTask").body(runTask(cluster, family, override)).post("/").then());
|
||||
user.policy(allow("ecs:RunTask", "*") + "," + passRole(taskRole, ECS_TASKS) + ","
|
||||
+ passRole(override, ECS_TASKS));
|
||||
stopLater(cluster, user.ecs("RunTask").body(runTask(cluster, family, override)).post("/").then()
|
||||
.statusCode(200).extract().path("tasks[0].taskArn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServiceNeedsPassRoleOnItsTaskDefinitionsRolesAndOnItsInfrastructureRoles() {
|
||||
String taskRole = role("ecs-service");
|
||||
String nextRole = role("ecs-service-next");
|
||||
String infrastructure = role("ecs-infrastructure");
|
||||
String family = registerTaskDefinition(taskRole);
|
||||
String next = registerTaskDefinition(nextRole);
|
||||
String cluster = cluster();
|
||||
String name = "passrole-svc-" + suffix();
|
||||
User user = user("passrole-ecs-service");
|
||||
|
||||
user.policy(allow("ecs:CreateService", "*"));
|
||||
deniedJson(user.ecs("CreateService").body(service(cluster, name, family)).post("/").then());
|
||||
user.policy(allow("ecs:CreateService", "*") + "," + passRole(taskRole, ECS_TASKS));
|
||||
user.ecs("CreateService").body(service(cluster, name, family)).post("/").then().statusCode(200);
|
||||
cleanup.register(() -> admin("ecs").contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.DeleteService")
|
||||
.body("{\"cluster\":\"" + cluster + "\",\"service\":\"" + name + "\",\"force\":true}").post("/"));
|
||||
|
||||
// Moving the service to another task definition passes that definition's roles.
|
||||
String update = "{\"cluster\":\"" + cluster + "\",\"service\":\"" + name + "\",\"taskDefinition\":\""
|
||||
+ next + "\"}";
|
||||
user.policy(allow("ecs:UpdateService", "*") + "," + passRole(taskRole, ECS_TASKS));
|
||||
deniedJson(user.ecs("UpdateService").body(update).post("/").then());
|
||||
user.policy(allow("ecs:UpdateService", "*") + "," + passRole(nextRole, ECS_TASKS));
|
||||
user.ecs("UpdateService").body(update).post("/").then().statusCode(200);
|
||||
|
||||
// An infrastructure role, here an EBS volume's, is passed to ECS itself.
|
||||
String volumes = "{\"cluster\":\"" + cluster + "\",\"service\":\"" + name + "\",\"volumeConfigurations\":"
|
||||
+ "[{\"name\":\"data\",\"managedEBSVolume\":{\"roleArn\":\"" + infrastructure + "\"}}]}";
|
||||
user.policy(allow("ecs:UpdateService", "*") + "," + passRole(infrastructure, ECS_TASKS));
|
||||
deniedJson(user.ecs("UpdateService").body(volumes).post("/").then());
|
||||
user.policy(allow("ecs:UpdateService", "*") + "," + passRole(infrastructure, ECS));
|
||||
// ECS answers the volume on its own terms; a JSON-protocol denial would be a 400 naming the action.
|
||||
user.ecs("UpdateService").body(volumes).post("/").then().body(not(containsString("iam:PassRole")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStateMachineNeedsPassRoleOnItsRoleForStepFunctions() throws IOException {
|
||||
String role = role("states");
|
||||
String other = role("states-other");
|
||||
User user = user("passrole-states");
|
||||
String body = """
|
||||
{"name":"passrole-sm-%s","roleArn":"%s",
|
||||
"definition":"{\\"StartAt\\":\\"Done\\",\\"States\\":{\\"Done\\":{\\"Type\\":\\"Pass\\",\\"End\\":true}}}"}"""
|
||||
.formatted(suffix(), role);
|
||||
|
||||
user.policy(allow("states:CreateStateMachine", "*"));
|
||||
deniedJson(user.states("CreateStateMachine").body(body).post("/").then());
|
||||
// A Smithy RPC v2 CBOR call names the role in the same member.
|
||||
byte[] cbor = CBOR_MAPPER.writeValueAsBytes(new ObjectMapper().readTree(body));
|
||||
assertPassRoleDenied(user.cbor("states").body(cbor)
|
||||
.post("/service/AWSStepFunctions/operation/CreateStateMachine"));
|
||||
// A gzip-encoded body, which the CBOR endpoint decompresses before it runs the request.
|
||||
assertPassRoleDenied(user.cbor("states").header("Content-Encoding", "gzip").body(gzip(cbor))
|
||||
.post("/service/AWSStepFunctions/operation/CreateStateMachine"));
|
||||
|
||||
user.policy(allow("states:CreateStateMachine", "*") + "," + passRole(role, "states.amazonaws.com"));
|
||||
String arn = user.states("CreateStateMachine").body(body).post("/").then()
|
||||
.statusCode(200).extract().path("stateMachineArn");
|
||||
cleanup.register(() -> admin("states").contentType("application/x-amz-json-1.0")
|
||||
.header("X-Amz-Target", "AWSStepFunctions.DeleteStateMachine")
|
||||
.body("{\"stateMachineArn\":\"" + arn + "\"}").post("/"));
|
||||
|
||||
String update = "{\"stateMachineArn\":\"" + arn + "\",\"roleArn\":\"" + other + "\"}";
|
||||
user.policy(allow("states:UpdateStateMachine", "*") + "," + passRole(role, "states.amazonaws.com"));
|
||||
deniedJson(user.states("UpdateStateMachine").body(update).post("/").then());
|
||||
user.policy(allow("states:UpdateStateMachine", "*") + "," + passRole(other, "states.amazonaws.com"));
|
||||
user.states("UpdateStateMachine").body(update).post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEventBridgeRuleAndEachOfItsTargetsNeedPassRoleOnTheirRoles() {
|
||||
String role = role("events");
|
||||
String targetRole = role("events-target");
|
||||
User user = user("passrole-events");
|
||||
String rule = "passrole-rule-" + suffix();
|
||||
String putRule = "{\"Name\":\"" + rule + "\",\"ScheduleExpression\":\"rate(1 hour)\",\"RoleArn\":\""
|
||||
+ role + "\"}";
|
||||
String rules = allow("events:PutRule", "*") + "," + allow("events:PutTargets", "*");
|
||||
|
||||
user.policy(rules);
|
||||
deniedJson(user.json("events", "AWSEvents.PutRule").body(putRule).post("/").then());
|
||||
user.policy(rules + "," + passRole(role, "events.amazonaws.com"));
|
||||
user.json("events", "AWSEvents.PutRule").body(putRule).post("/").then().statusCode(200);
|
||||
cleanup.register(() -> admin("events").contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "AWSEvents.DeleteRule").body("{\"Name\":\"" + rule + "\"}").post("/"));
|
||||
cleanup.register(() -> admin("events").contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "AWSEvents.RemoveTargets")
|
||||
.body("{\"Rule\":\"" + rule + "\",\"Ids\":[\"1\",\"2\"]}").post("/"));
|
||||
|
||||
// The second target names a role, the first does not.
|
||||
String putTargets = "{\"Rule\":\"" + rule + "\",\"Targets\":[{\"Id\":\"1\",\"Arn\":\"" + QUEUE_ARN + "\"},"
|
||||
+ "{\"Id\":\"2\",\"Arn\":\"" + QUEUE_ARN + "\",\"RoleArn\":\"" + targetRole + "\"}]}";
|
||||
deniedJson(user.json("events", "AWSEvents.PutTargets").body(putTargets).post("/").then());
|
||||
user.policy(rules + "," + passRole(targetRole, "events.amazonaws.com"));
|
||||
user.json("events", "AWSEvents.PutTargets").body(putTargets).post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStackNeedsPassRoleOnAServiceRoleTheRequestNames() {
|
||||
String role = role("cloudformation");
|
||||
User user = user("passrole-stack");
|
||||
String stack = "passrole-stack-" + suffix();
|
||||
String stacks = allow("cloudformation:CreateStack", "*") + "," + allow("cloudformation:DeleteStack", "*");
|
||||
|
||||
user.policy(stacks);
|
||||
denied(createStack(user, stack).formParam("RoleARN", role).post("/").then());
|
||||
user.policy(stacks + "," + passRole(role, "cloudformation.amazonaws.com"));
|
||||
createStack(user, stack).formParam("RoleARN", role).post("/").then().statusCode(200);
|
||||
cleanup.register(() -> admin("cloudformation").formParam("Action", "DeleteStack")
|
||||
.formParam("StackName", stack).post("/"));
|
||||
|
||||
// A later operation that names no role reuses the stack's own without passing it.
|
||||
user.policy(stacks);
|
||||
denied(user.cfn("DeleteStack").formParam("StackName", stack).formParam("RoleARN", role).post("/").then());
|
||||
user.cfn("DeleteStack").formParam("StackName", stack).post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSelfManagedStackSetPassesTheAdministrationRoleItNamesOrTheDefaultOne() {
|
||||
String defaultRole = "arn:aws:iam::" + ACCOUNT + ":role/AWSCloudFormationStackSetAdministrationRole";
|
||||
String custom = role("stackset-admin");
|
||||
User user = user("passrole-stackset");
|
||||
String name = "passrole-stackset-" + suffix();
|
||||
String stackSets = allow("cloudformation:CreateStackSet", "*") + ","
|
||||
+ allow("cloudformation:UpdateStackSet", "*");
|
||||
|
||||
user.policy(stackSets);
|
||||
denied(stackSet(user, "CreateStackSet", name).post("/").then());
|
||||
user.policy(stackSets + "," + passRole(defaultRole, "cloudformation.amazonaws.com"));
|
||||
stackSet(user, "CreateStackSet", name).post("/").then().statusCode(200);
|
||||
cleanup.register(() -> admin("cloudformation").formParam("Action", "DeleteStackSet")
|
||||
.formParam("StackSetName", name).post("/"));
|
||||
|
||||
// An update naming no administration role passes the default one too, and one naming a role passes it.
|
||||
user.policy(stackSets);
|
||||
denied(stackSet(user, "UpdateStackSet", name).post("/").then());
|
||||
user.policy(stackSets + "," + passRole(defaultRole, "cloudformation.amazonaws.com"));
|
||||
denied(stackSet(user, "UpdateStackSet", name).formParam("AdministrationRoleARN", custom).post("/").then());
|
||||
user.policy(stackSets + "," + passRole(custom, "cloudformation.amazonaws.com"));
|
||||
stackSet(user, "UpdateStackSet", name).formParam("AdministrationRoleARN", custom).post("/").then()
|
||||
.statusCode(200);
|
||||
|
||||
// A service-managed StackSet uses no administration role, so none is passed.
|
||||
user.policy(stackSets);
|
||||
cleanup.register(() -> admin("cloudformation").formParam("Action", "DeleteStackSet")
|
||||
.formParam("StackSetName", name + "-org").post("/"));
|
||||
stackSet(user, "CreateStackSet", name + "-org").formParam("PermissionModel", "SERVICE_MANAGED").post("/")
|
||||
.then().statusCode(not(403)).body(not(containsString("iam:PassRole")));
|
||||
}
|
||||
|
||||
/** Requests a Spot Instance, removes it afterwards, and returns the profile ARN it was launched with. */
|
||||
private String spotProfileArn(User user, String selector, String profile) {
|
||||
String item = "RequestSpotInstancesResponse.spotInstanceRequestSet.item.";
|
||||
@@ -245,10 +469,99 @@ class IamPassRoleEnforcementIntegrationTest {
|
||||
.formParam("DeliverLogsPermissionArn", role).post("/");
|
||||
}
|
||||
|
||||
private static String taskDefinition(String family, String taskRole, String executionRole) {
|
||||
return """
|
||||
{"family":"%s","requiresCompatibilities":["FARGATE"],"networkMode":"awsvpc","cpu":"256","memory":"512",
|
||||
"containerDefinitions":[{"name":"app","image":"nginx:latest","essential":true}]%s%s}"""
|
||||
.formatted(family, taskRole == null ? "" : ",\"taskRoleArn\":\"" + taskRole + "\"",
|
||||
executionRole == null ? "" : ",\"executionRoleArn\":\"" + executionRole + "\"");
|
||||
}
|
||||
|
||||
/** Registers a task definition with {@code taskRole}, removed afterwards, and returns its family. */
|
||||
private String registerTaskDefinition(String taskRole) {
|
||||
String family = "passrole-family-" + suffix();
|
||||
admin("ecs").contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.RegisterTaskDefinition")
|
||||
.body(taskDefinition(family, taskRole, null)).post("/").then().statusCode(200);
|
||||
deregisterLater(family + ":1");
|
||||
return family;
|
||||
}
|
||||
|
||||
private void deregisterLater(String taskDefinition) {
|
||||
cleanup.register(() -> admin("ecs").contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.DeregisterTaskDefinition")
|
||||
.body("{\"taskDefinition\":\"" + taskDefinition + "\"}").post("/"));
|
||||
}
|
||||
|
||||
/** Creates a cluster, removed afterwards, and returns its name. */
|
||||
private String cluster() {
|
||||
String name = "passrole-cluster-" + suffix();
|
||||
admin("ecs").contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.CreateCluster")
|
||||
.body("{\"clusterName\":\"" + name + "\"}").post("/").then().statusCode(200);
|
||||
cleanup.register(() -> admin("ecs").contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.DeleteCluster")
|
||||
.body("{\"cluster\":\"" + name + "\"}").post("/"));
|
||||
return name;
|
||||
}
|
||||
|
||||
private void stopLater(String cluster, String taskArn) {
|
||||
cleanup.register(() -> admin("ecs").contentType("application/x-amz-json-1.1")
|
||||
.header("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.StopTask")
|
||||
.body("{\"cluster\":\"" + cluster + "\",\"task\":\"" + taskArn + "\"}").post("/"));
|
||||
}
|
||||
|
||||
private static String runTask(String cluster, String family, String taskRoleOverride) {
|
||||
return """
|
||||
{"cluster":"%s","taskDefinition":"%s","launchType":"FARGATE","count":1,
|
||||
"networkConfiguration":{"awsvpcConfiguration":{"subnets":["subnet-default-us-east-1-a"]}}%s}"""
|
||||
.formatted(cluster, family, taskRoleOverride == null ? ""
|
||||
: ",\"overrides\":{\"taskRoleArn\":\"" + taskRoleOverride + "\"}");
|
||||
}
|
||||
|
||||
private static String service(String cluster, String name, String family) {
|
||||
return """
|
||||
{"cluster":"%s","serviceName":"%s","taskDefinition":"%s","desiredCount":0,"launchType":"FARGATE",
|
||||
"networkConfiguration":{"awsvpcConfiguration":{"subnets":["subnet-default-us-east-1-a"]}}}"""
|
||||
.formatted(cluster, name, family);
|
||||
}
|
||||
|
||||
private static RequestSpecification createStack(User user, String stack) {
|
||||
return user.cfn("CreateStack").formParam("StackName", stack).formParam("TemplateBody",
|
||||
"{\"Resources\":{\"Q\":{\"Type\":\"AWS::SQS::Queue\",\"Properties\":{\"QueueName\":\"" + stack + "\"}}}}");
|
||||
}
|
||||
|
||||
private static RequestSpecification stackSet(User user, String action, String name) {
|
||||
return user.cfn(action).formParam("StackSetName", name).formParam("TemplateBody",
|
||||
"{\"Resources\":{\"Q\":{\"Type\":\"AWS::SQS::Queue\"}}}");
|
||||
}
|
||||
|
||||
private static String roleName(String roleArn) {
|
||||
return roleArn.substring(roleArn.lastIndexOf('/') + 1);
|
||||
}
|
||||
|
||||
private static void assertPassRoleDenied(Response response) throws IOException {
|
||||
JsonNode error = CBOR_MAPPER.readTree(response.then().statusCode(403).extract().asByteArray());
|
||||
assertTrue(error.path("message").asText().contains("iam:PassRole"), error.toString());
|
||||
}
|
||||
|
||||
private static byte[] gzip(byte[] body) throws IOException {
|
||||
ByteArrayOutputStream compressed = new ByteArrayOutputStream();
|
||||
try (GZIPOutputStream out = new GZIPOutputStream(compressed)) {
|
||||
out.write(body);
|
||||
}
|
||||
return compressed.toByteArray();
|
||||
}
|
||||
|
||||
private static void denied(ValidatableResponse response) {
|
||||
response.statusCode(403).body(containsString("iam:PassRole"));
|
||||
}
|
||||
|
||||
/** A JSON-protocol service refuses with {@code AccessDeniedException}, which those protocols send as a 400. */
|
||||
private static void deniedJson(ValidatableResponse response) {
|
||||
response.statusCode(400).body(containsString("AccessDeniedException")).body(containsString("iam:PassRole"));
|
||||
}
|
||||
|
||||
private static String allow(String action, String resource) {
|
||||
return "{\"Effect\":\"Allow\",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}";
|
||||
}
|
||||
@@ -310,5 +623,29 @@ class IamPassRoleEnforcementIntegrationTest {
|
||||
RequestSpecification ec2(String action) {
|
||||
return given().header("Authorization", auth(accessKeyId, "ec2")).formParam("Action", action);
|
||||
}
|
||||
|
||||
RequestSpecification ecs(String action) {
|
||||
return json("ecs", "AmazonEC2ContainerServiceV20141113." + action);
|
||||
}
|
||||
|
||||
RequestSpecification json(String service, String target) {
|
||||
return given().header("Authorization", auth(accessKeyId, service)).header("X-Amz-Target", target)
|
||||
.contentType("application/x-amz-json-1.1");
|
||||
}
|
||||
|
||||
/** Step Functions speaks JSON 1.0. */
|
||||
RequestSpecification states(String operation) {
|
||||
return given().header("Authorization", auth(accessKeyId, "states"))
|
||||
.header("X-Amz-Target", "AWSStepFunctions." + operation).contentType("application/x-amz-json-1.0");
|
||||
}
|
||||
|
||||
RequestSpecification cbor(String service) {
|
||||
return given().header("Authorization", auth(accessKeyId, service)).header("smithy-protocol", "rpc-v2-cbor")
|
||||
.contentType("application/cbor").accept("application/cbor");
|
||||
}
|
||||
|
||||
RequestSpecification cfn(String action) {
|
||||
return given().header("Authorization", auth(accessKeyId, "cloudformation")).formParam("Action", action);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user