diff --git a/docs/services/iam.md b/docs/services/iam.md index 1abd46f56b..51e5e85389 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -1331,11 +1331,33 @@ role each passes: pass the roles of the instance profile they name, to `ec2.amazonaws.com`. `CreateFlowLogs` passes `DeliverLogsPermissionArn` to `vpc-flow-logs.amazonaws.com`. A profile that does not exist passes nothing, and EC2 refuses it as without enforcement. +- **ECS:** `RegisterTaskDefinition` passes its `taskRoleArn` and `executionRoleArn` to + `ecs-tasks.amazonaws.com`. `RunTask` and `StartTask` pass the task definition's task and execution + roles and any role in `overrides` there too, 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 `roleArn` (`RunTask`, `StartTask`, `CreateService`, + `UpdateService`), the service's `role` and the load balancer, lifecycle hook, Service Connect TLS + and VPC Lattice roles (`CreateService`, `UpdateService`), and a Managed Instances provider's + `infrastructureRoleArn` (`CreateCapacityProvider`, `UpdateCapacityProvider`). A role given by its + name is the role of that name in the caller's account, and a task definition that does not exist + passes nothing. +- **Step Functions:** `CreateStateMachine` and `UpdateStateMachine` pass `roleArn` to + `states.amazonaws.com`, in a JSON or a CBOR body. +- **EventBridge:** `PutRule` passes `RoleArn`, and `PutTargets` each target's `RoleArn`, to + `events.amazonaws.com`. +- **CloudFormation:** `CreateStack`, `UpdateStack`, `DeleteStack`, `CreateChangeSet` and + `ContinueUpdateRollback` pass `RoleARN` to `cloudformation.amazonaws.com` when the request names + one. `CreateStackSet` and `UpdateStackSet` pass `AdministrationRoleARN`, or, for a self-managed + StackSet, the default `AWSCloudFormationStackSetAdministrationRole`. Launching from a launch template does not check the template's role, as on AWS: the EC2 user guide warns that a user who can create launch template versions "can potentially update a launch template -to pass an IAM role to an instance even if they don't have the iam:PassRole permission". The role -parameters of other services are not checked yet. +to pass an IAM role to an instance even if they don't have the iam:PassRole permission". A +CloudFormation operation that names no role uses the stack's own without checking it, as the +CloudFormation API reference says the service does "even if the users don't have permission to pass +it". The CloudFormation user guide has the default StackSet administration role checked "Even when +you don't specify the AdministrationRoleARN parameter". The role parameters of other services are +not checked yet. A request that names its operation, in a Query `Action`, an `X-Amz-Target` header or a Smithy RPC v2 path (`/service//operation/`), is authorized as the action AWS checks for that diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java index ce63d591d6..a914b9d156 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java @@ -355,7 +355,8 @@ public class AwsJsonCborController { return request; } - private boolean isGZipped(List contentEncodingHeaders) { + // Package-private: PassedRoles reads the same body before this controller runs. + static boolean isGZipped(List contentEncodingHeaders) { if (contentEncodingHeaders == null) { return false; } @@ -447,7 +448,7 @@ public class AwsJsonCborController { } } - private byte[] decodeBody(byte[] compressed) { + static byte[] decodeBody(byte[] compressed) { int buffSize = 64 * 1024; byte[] buffer = new byte[buffSize]; // 10 MB limit max over all aws services, to avoid OOM. AWS services should not send more than 10 MB in a single request. int totalRead = 0; diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java index daed584a48..44156f0557 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java @@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicy import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.services.iam.IamService.CallerArns; import io.github.hectorvent.floci.services.iam.IamService.PresignedScope; +import io.github.hectorvent.floci.services.iam.PassedRoleLookup; import io.github.hectorvent.floci.services.iam.RequestPrincipal; import io.github.hectorvent.floci.services.iam.ResourceArnBuilder; import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider; @@ -204,6 +205,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { private final Instance scpProvider; private final SessionAccountLookup sessionAccountLookup; private final Instance resourcePolicyProviders; + private final Instance passedRoleLookups; /** The clock {@link IamService} measures session expiry on, so both read the same time. */ private final Clock clock; private final ResourceInfo resourceInfo; @@ -224,6 +226,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { Instance scpProvider, SessionAccountLookup sessionAccountLookup, Instance resourcePolicyProviders, + Instance passedRoleLookups, Clock clock, @Context ResourceInfo resourceInfo) { this.config = config; @@ -241,6 +244,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { this.scpProvider = scpProvider; this.sessionAccountLookup = sessionAccountLookup; this.resourcePolicyProviders = resourcePolicyProviders; + this.passedRoleLookups = passedRoleLookups; this.clock = clock; this.resourceInfo = resourceInfo; } @@ -263,7 +267,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { this(config, accountResolver, iamService, evaluator, actionRegistry, new AwsQueryServiceResolver(catalog), arnBuilder, requestContext, conditionContextResolver, cloudTrailService, currentVertxRequest, catalog, - scpProvider, sessionAccountLookup, resourcePolicyProviders, Clock.systemUTC(), null); + scpProvider, sessionAccountLookup, resourcePolicyProviders, null, Clock.systemUTC(), null); } /** Package-private constructor for callers predating resourcePolicyProviders. */ @@ -283,7 +287,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { this(config, accountResolver, iamService, evaluator, actionRegistry, new AwsQueryServiceResolver(catalog), arnBuilder, requestContext, conditionContextResolver, cloudTrailService, currentVertxRequest, catalog, - scpProvider, sessionAccountLookup, null, Clock.systemUTC(), null); + scpProvider, sessionAccountLookup, null, null, Clock.systemUTC(), null); } @Override @@ -870,15 +874,14 @@ public class IamEnforcementFilter implements ContainerRequestFilter { * A request that passes a role to a service also needs {@code iam:PassRole} on that role (see * {@link PassedRoles}), checked as the caller with {@code iam:PassedToService} naming the * service and the keys that say who is calling, which {@code callerArns} writes when it is known. - * An instance profile is looked up in the request's account, as EC2 resolves it; one that does - * not exist passes nothing, and the operation reports it. Returns true when the request was - * aborted. + * What a request names that holds roles, an instance profile or a task definition, is looked up + * in the request's account, as the service resolves it; one that does not exist passes nothing, + * and the operation reports it. Returns true when the request was aborted. */ private boolean abortIfRolePassDenied(ContainerRequestContext ctx, CallerContext caller, RequestPrincipal principal, CallerArns callerArns, String action, String credentialScope, String region, String accountId, String akid) { - for (PassedRoles.PassedRole passed : PassedRoles.of(action, ctx, - (name, arn) -> instanceProfileRoleArns(accountId, name, arn))) { + for (PassedRoles.PassedRole passed : PassedRoles.of(action, ctx, lookupsFor(accountId, region))) { Map> context = new HashMap<>(); if (callerArns != null) { callerArns.putPrincipalKeys(context); @@ -892,6 +895,45 @@ public class IamEnforcementFilter implements ContainerRequestFilter { return false; } + /** What {@link PassedRoles} looks up, in the request's account and Region. */ + private PassedRoles.Lookups lookupsFor(String accountId, String region) { + return new PassedRoles.Lookups() { + @Override + public List instanceProfileRoleArns(String profileName, String profileArn) { + return IamEnforcementFilter.this.instanceProfileRoleArns(accountId, profileName, profileArn); + } + + @Override + public List taskDefinitionRoles(String reference) { + List roles = new ArrayList<>(); + for (PassedRoleLookup lookup : roleLookups()) { + roles.addAll(lookup.taskDefinitionRoles(reference, region)); + } + return roles; + } + + @Override + public Optional stackSetPermissionModel(String stackSetName) { + for (PassedRoleLookup lookup : roleLookups()) { + Optional model = lookup.stackSetPermissionModel(stackSetName); + if (model.isPresent()) { + return model; + } + } + return Optional.empty(); + } + + @Override + public String roleArn(String roleName) { + return AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "role/" + roleName).toString(); + } + }; + } + + private Iterable roleLookups() { + return passedRoleLookups == null || passedRoleLookups.isUnsatisfied() ? List.of() : passedRoleLookups; + } + /** The ARNs of the roles the instance profile, named by {@code name} or {@code arn}, holds. */ private List instanceProfileRoleArns(String accountId, String name, String arn) { String profileName = arn != null ? arn.substring(arn.lastIndexOf('/') + 1) : name; diff --git a/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java b/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java index 6d7437e5e8..ef0dc5ddd3 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java @@ -2,13 +2,17 @@ package io.github.hectorvent.floci.core.common; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.cbor.CBORFactory; import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; import org.jboss.logging.Logger; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.regex.Pattern; /** @@ -23,11 +27,28 @@ import java.util.regex.Pattern; * who can create launch template versions "can potentially update a launch template to pass an IAM * role to an instance even if they don't have the iam:PassRole permission", so the role is checked * where the template is created. + * + *

An ECS request that starts tasks from a task definition passes the definition's task role and + * task execution role: the ECS developer guide has the role EventBridge runs scheduled tasks with + * hold {@code iam:PassRole} "for each task execution role, task role, or task role override". A role + * override is checked as well, not instead, since Floci runs a task with its definition's task role. + * ECS infrastructure roles go to {@code ecs.amazonaws.com} ("To use an ECS infrastructure IAM role, + * you must grant your user permission to pass the role to Amazon ECS"), task roles to + * {@code ecs-tasks.amazonaws.com}. + * + *

A CloudFormation stack's service role is checked where a request names it, and not on later + * operations that reuse it: CloudFormation "uses this role even if the users don't have permission + * to pass it". A self-managed StackSet that names no administration role passes the default one: + * "Even when you don't specify the AdministrationRoleARN parameter, the IAM principal calling + * CreateStackSet or UpdateStackSet must have iam:PassRole permission for the + * AWSCloudFormationStackSetAdministrationRole role." */ final class PassedRoles { private static final Logger LOG = Logger.getLogger(PassedRoles.class); private static final ObjectMapper MAPPER = new ObjectMapper(); + /** Reads the CBOR bodies the RPC v2 path carries, which name the role in the same member JSON does. */ + private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory()); /** An IAM role ARN, the only resource {@code iam:PassRole} acts on. */ private static final Pattern ROLE_ARN = Pattern.compile("^arn:[a-z0-9-]+:iam::\\d{12}:role/.+"); @@ -35,44 +56,180 @@ final class PassedRoles { private static final String LAMBDA = ServicePrincipals.of("lambda"); private static final String EC2 = ServicePrincipals.of("ec2"); private static final String VPC_FLOW_LOGS = ServicePrincipals.of("vpc-flow-logs"); + private static final String ECS = ServicePrincipals.of("ecs"); + private static final String ECS_TASKS = ServicePrincipals.of("ecs-tasks"); + private static final String STATES = ServicePrincipals.of("states"); + private static final String EVENTS = ServicePrincipals.of("events"); + private static final String CLOUDFORMATION = ServicePrincipals.of("cloudformation"); + + private static final String STACK_SET_ADMINISTRATION_ROLE = "AWSCloudFormationStackSetAdministrationRole"; + private static final String SERVICE_MANAGED = "SERVICE_MANAGED"; /** A role a request passes, and the service principal it is passed to. */ record PassedRole(String roleArn, String passedToService) { } - /** The ARNs of the roles an EC2 instance profile holds, looked up by its name or its ARN. */ - @FunctionalInterface - interface InstanceProfileRoles { - List roleArns(String profileName, String profileArn); + /** What a request names that holds the roles it passes, looked up in the request's account and Region. */ + interface Lookups { + + /** The ARNs of the roles an EC2 instance profile holds, looked up by its name or its ARN. */ + List instanceProfileRoleArns(String profileName, String profileArn); + + /** The task role and task execution role of the ECS task definition {@code reference} names. */ + List taskDefinitionRoles(String reference); + + /** The permission model of the StackSet named {@code stackSetName}; empty when there is none. */ + Optional stackSetPermissionModel(String stackSetName); + + /** The ARN of the role {@code roleName}, a name with any path, names in the request's account. */ + String roleArn(String roleName); } private PassedRoles() { } /** The roles a request for {@code action} passes; empty when the operation passes none or the request names none. */ - static List of(String action, ContainerRequestContext ctx, InstanceProfileRoles profiles) { + static List of(String action, ContainerRequestContext ctx, Lookups lookups) { return switch (action) { case "lambda:CreateFunction", "lambda:UpdateFunctionConfiguration" -> fromJson(ctx, LAMBDA, "Role"); case "lambda:CreateWebFunction" -> fromJson(ctx, LAMBDA, "revisionConfig", "serviceConfig", "executionRoleArn"); case "lambda:CreateWebFunctionRevision" -> fromJson(ctx, LAMBDA, "serviceConfig", "executionRoleArn"); case "ec2:RunInstances", "ec2:AssociateIamInstanceProfile", "ec2:ReplaceIamInstanceProfileAssociation" -> - fromInstanceProfile(ctx, profiles, "IamInstanceProfile"); + fromInstanceProfile(ctx, lookups, "IamInstanceProfile"); case "ec2:RequestSpotInstances" -> - fromInstanceProfile(ctx, profiles, "LaunchSpecification.IamInstanceProfile"); + fromInstanceProfile(ctx, lookups, "LaunchSpecification.IamInstanceProfile"); case "ec2:CreateLaunchTemplate", "ec2:CreateLaunchTemplateVersion" -> - fromInstanceProfile(ctx, profiles, "LaunchTemplateData.IamInstanceProfile"); + fromInstanceProfile(ctx, lookups, "LaunchTemplateData.IamInstanceProfile"); case "ec2:CreateFlowLogs" -> fromForm(ctx, VPC_FLOW_LOGS, "DeliverLogsPermissionArn"); + case "ecs:RegisterTaskDefinition" -> ecsTaskDefinition(jsonBody(ctx), lookups); + case "ecs:RunTask", "ecs:StartTask" -> ecsTask(jsonBody(ctx), lookups); + case "ecs:CreateService", "ecs:UpdateService" -> ecsService(jsonBody(ctx), lookups); + case "ecs:CreateTaskSet" -> ecsTaskDefinitionRoles(jsonBody(ctx), lookups); + case "ecs:CreateCapacityProvider", "ecs:UpdateCapacityProvider" -> + ecsRoles(values(jsonBody(ctx), "managedInstancesProvider", "infrastructureRoleArn"), ECS, lookups); + case "states:CreateStateMachine", "states:UpdateStateMachine" -> fromJson(ctx, STATES, "roleArn"); + case "events:PutRule" -> fromJson(ctx, EVENTS, "RoleArn"); + case "events:PutTargets" -> fromJson(ctx, EVENTS, "Targets", "[]", "RoleArn"); + case "cloudformation:CreateStack", "cloudformation:UpdateStack", "cloudformation:DeleteStack", + "cloudformation:CreateChangeSet", "cloudformation:ContinueUpdateRollback" -> + fromForm(ctx, CLOUDFORMATION, "RoleARN"); + case "cloudformation:CreateStackSet", "cloudformation:UpdateStackSet" -> + stackSetAdministrationRole(ctx, lookups, "cloudformation:UpdateStackSet".equals(action)); default -> List.of(); }; } - private static List fromJson(ContainerRequestContext ctx, String service, String... path) { - JsonNode node = jsonBody(ctx); - for (String member : path) { - node = node == null ? null : node.get(member); + private static List ecsTaskDefinition(JsonNode body, Lookups lookups) { + List roles = new ArrayList<>(values(body, "taskRoleArn")); + roles.addAll(values(body, "executionRoleArn")); + return ecsRoles(roles, ECS_TASKS, lookups); + } + + /** RunTask and StartTask: the task definition's roles and its overrides to the task, and the volumes' infrastructure role. */ + private static List ecsTask(JsonNode body, Lookups lookups) { + List taskRoles = new ArrayList<>(taskDefinitionRoles(body, lookups)); + taskRoles.addAll(values(body, "overrides", "taskRoleArn")); + taskRoles.addAll(values(body, "overrides", "executionRoleArn")); + List passed = new ArrayList<>(ecsRoles(taskRoles, ECS_TASKS, lookups)); + passed.addAll(ecsRoles(values(body, "volumeConfigurations", "[]", "managedEBSVolume", "roleArn"), ECS, lookups)); + return passed; + } + + /** CreateService and UpdateService: the task definition's roles, and the infrastructure roles the service uses. */ + private static List ecsService(JsonNode body, Lookups lookups) { + List infrastructure = new ArrayList<>(values(body, "role")); + infrastructure.addAll(values(body, "loadBalancers", "[]", "advancedConfiguration", "roleArn")); + infrastructure.addAll(values(body, "deploymentConfiguration", "lifecycleHooks", "[]", "roleArn")); + infrastructure.addAll(values(body, "serviceConnectConfiguration", "services", "[]", "tls", "roleArn")); + infrastructure.addAll(values(body, "volumeConfigurations", "[]", "managedEBSVolume", "roleArn")); + infrastructure.addAll(values(body, "vpcLatticeConfigurations", "[]", "roleArn")); + List passed = new ArrayList<>(ecsTaskDefinitionRoles(body, lookups)); + passed.addAll(ecsRoles(infrastructure, ECS, lookups)); + return passed; + } + + private static List ecsTaskDefinitionRoles(JsonNode body, Lookups lookups) { + return ecsRoles(taskDefinitionRoles(body, lookups), ECS_TASKS, lookups); + } + + /** The roles of the task definition the request names; none when it names none. */ + private static List taskDefinitionRoles(JsonNode body, Lookups lookups) { + List reference = values(body, "taskDefinition"); + return reference.isEmpty() || reference.get(0).isBlank() + ? List.of() : lookups.taskDefinitionRoles(reference.get(0)); + } + + /** + * ECS takes a role by its name as well as by its ARN ({@code taskRoleArn} is "The short name or + * full Amazon Resource Name (ARN) of the IAM role"), and a name is the role in the request's account. + */ + private static List ecsRoles(List roles, String service, Lookups lookups) { + List arns = new ArrayList<>(); + for (String role : roles) { + if (!role.isBlank()) { + arns.add(role.startsWith("arn:") ? role : lookups.roleArn(role)); + } } - return node != null && node.isTextual() ? passed(List.of(node.asText()), service) : List.of(); + return passed(arns, service); + } + + /** + * The administration role a StackSet operation passes: the one it names, or else, unless the + * StackSet uses service-managed permissions, the default one. An update goes by the StackSet's + * own permission model, which Floci keeps whatever the request names, and one of a StackSet that + * does not exist passes nothing. + */ + private static List stackSetAdministrationRole(ContainerRequestContext ctx, Lookups lookups, + boolean update) { + Map form = IamConditionContextResolver.formParameters(ctx); + String named = blankToNull(form.get("AdministrationRoleARN")); + if (named != null) { + return passed(List.of(named), CLOUDFORMATION); + } + String model = blankToNull(form.get("PermissionModel")); + if (update) { + String name = blankToNull(form.get("StackSetName")); + Optional stored = name == null ? Optional.empty() : lookups.stackSetPermissionModel(name); + if (stored.isEmpty()) { + return List.of(); + } + model = stored.get(); + } + return SERVICE_MANAGED.equals(model) + ? List.of() : passed(List.of(lookups.roleArn(STACK_SET_ADMINISTRATION_ROLE)), CLOUDFORMATION); + } + + private static List fromJson(ContainerRequestContext ctx, String service, String... path) { + return passed(values(jsonBody(ctx), path), service); + } + + /** The strings at {@code path} in {@code node}, where a {@code []} step takes each element of an array. */ + private static List values(JsonNode node, String... path) { + List found = new ArrayList<>(); + collect(node, path, 0, found); + return found; + } + + private static void collect(JsonNode node, String[] path, int step, List found) { + if (node == null) { + return; + } + if (step == path.length) { + if (node.isTextual()) { + found.add(node.asText()); + } + return; + } + if ("[]".equals(path[step])) { + if (node.isArray()) { + for (JsonNode element : node) { + collect(element, path, step + 1, found); + } + } + return; + } + collect(node.get(path[step]), path, step + 1, found); } private static List fromForm(ContainerRequestContext ctx, String service, String parameter) { @@ -81,15 +238,14 @@ final class PassedRoles { } /** The roles of the instance profile named by {@code prefix}.Name or {@code prefix}.Arn. */ - private static List fromInstanceProfile(ContainerRequestContext ctx, InstanceProfileRoles profiles, - String prefix) { + private static List fromInstanceProfile(ContainerRequestContext ctx, Lookups lookups, String prefix) { Map form = IamConditionContextResolver.formParameters(ctx); String name = blankToNull(form.get(prefix + ".Name")); String arn = blankToNull(form.get(prefix + ".Arn")); if (name == null && arn == null) { return List.of(); } - return passed(profiles.roleArns(name, arn), EC2); + return passed(lookups.instanceProfileRoleArns(name, arn), EC2); } /** The roles that are IAM role ARNs; anything else is left for the operation to refuse. */ @@ -103,7 +259,11 @@ final class PassedRoles { return passed; } - /** The request's JSON body, read once and kept where the other request readers look for it. */ + /** + * The request's JSON or CBOR body, read once and kept where the other request readers look for it. + * A gzip-encoded body is decompressed first, as {@code AwsJsonCborController} decompresses it before + * running the request. + */ private static JsonNode jsonBody(ContainerRequestContext ctx) { if (ctx.getProperty(IamConditionContextResolver.BUFFERED_JSON_BODY) instanceof JsonNode cached) { return cached; @@ -113,16 +273,28 @@ final class PassedRoles { return null; } try { - JsonNode node = MAPPER.readTree(body); + String encoding = ctx.getHeaderString(HttpHeaders.CONTENT_ENCODING); + if (encoding != null && AwsJsonCborController.isGZipped(List.of(encoding))) { + body = AwsJsonCborController.decodeBody(body); + } + JsonNode node = (isCbor(ctx.getMediaType()) ? CBOR_MAPPER : MAPPER).readTree(body); ctx.setProperty(IamConditionContextResolver.BUFFERED_JSON_BODY, node); return node; - } catch (IOException e) { - // The operation answers a body it cannot parse itself; nothing here names a role. - LOG.debugv(e, "Request body is not JSON, so it passes no role"); + } catch (IOException | AwsException e) { + // The operation refuses a body it cannot decompress or parse itself; nothing here names a role. + LOG.debugv(e, "Request body cannot be read, so it passes no role"); return null; } } + /** Both CBOR content types arrive as {@code application/cbor}, as {@code ResourceArnBuilder} reads them. */ + private static boolean isCbor(MediaType mediaType) { + return mediaType != null + && "application".equalsIgnoreCase(mediaType.getType()) + && ("cbor".equalsIgnoreCase(mediaType.getSubtype()) + || "x-amz-cbor-1.1".equalsIgnoreCase(mediaType.getSubtype())); + } + private static String blankToNull(String value) { return value == null || value.isBlank() ? null : value; } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java index 4139c10a08..7bb8a230e9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java @@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.cloudformation.model.StackInstance; import io.github.hectorvent.floci.services.cloudformation.model.StackSet; import io.github.hectorvent.floci.services.cloudformation.model.StackSetAutoDeploymentTarget; import io.github.hectorvent.floci.services.cloudformation.model.StackSetOperation; +import io.github.hectorvent.floci.services.iam.PassedRoleLookup; import io.github.hectorvent.floci.services.organizations.OrganizationsService; import io.github.hectorvent.floci.services.organizations.model.Organization; import io.github.hectorvent.floci.services.organizations.model.OrganizationAccount; @@ -29,6 +30,7 @@ import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.Future; @@ -44,7 +46,7 @@ import java.util.regex.Pattern; * operation records themselves live in the administration (caller) account's namespace. */ @ApplicationScoped -public class StackSetService { +public class StackSetService implements PassedRoleLookup { private static final Logger LOG = Logger.getLogger(StackSetService.class); private static final String STACKSETS_SERVICE_PRINCIPAL = ServicePrincipals.of("stacksets.cloudformation"); @@ -181,6 +183,12 @@ public class StackSetService { return getStackSetOrThrow(name); } + /** The StackSet's permission model, which says whether an update naming no administration role passes the default one. */ + @Override + public Optional stackSetPermissionModel(String stackSetName) { + return stackSets.get(stackSetName).map(StackSet::getPermissionModel); + } + public List listStackSets() { return stackSets.scan(k -> true); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java index 8a1ff47548..a4b1309ee2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java @@ -69,6 +69,7 @@ import io.github.hectorvent.floci.services.ecs.model.TaskSet; import io.github.hectorvent.floci.services.ecs.model.TaskStatus; import io.github.hectorvent.floci.services.ecs.model.UpdateServiceRequest; import io.github.hectorvent.floci.services.ecs.model.Volume; +import io.github.hectorvent.floci.services.iam.PassedRoleLookup; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; @@ -109,7 +110,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; @ApplicationScoped -public class EcsService implements ContainerTeardown, ResourceProvider, Resettable { +public class EcsService implements ContainerTeardown, ResourceProvider, Resettable, PassedRoleLookup { private static final Logger LOG = Logger.getLogger(EcsService.class); private static final String DEFAULT_CLUSTER = "default"; @@ -5521,9 +5522,18 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab } private TaskDefinition resolveTaskDefinitionOrThrow(String ref, String region) { - if (ref == null || ref.isBlank()) { + TaskDefinition td = findTaskDefinition(ref, region); + if (td == null) { throw new AwsException("ClientException", "Unable to describe task definition: " + ref, 400); } + return td; + } + + /** The task definition {@code ref} names, a family, a {@code family:revision} or an ARN; null when there is none. */ + private TaskDefinition findTaskDefinition(String ref, String region) { + if (ref == null || ref.isBlank()) { + return null; + } TaskDefinition td = taskDefinitions.get(familyKey(region, ref)); if (td != null) { return td; } td = taskDefinitionsIn(region) @@ -5538,9 +5548,20 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab td = taskDefinitionsIn(region) .filter(d -> ref.equals(d.getFamily()) && d.getRevision() == latest) .findFirst().orElse(null); - if (td != null) { return td; } } - throw new AwsException("ClientException", "Unable to describe task definition: " + ref, 400); + return td; + } + + /** The roles a task started from the definition runs with, for the {@code iam:PassRole} check of RunTask and the rest. */ + @Override + public List taskDefinitionRoles(String reference, String region) { + TaskDefinition td = findTaskDefinition(reference, region); + if (td == null) { + return List.of(); + } + return Stream.of(td.getTaskRoleArn(), td.getExecutionRoleArn()) + .filter(Objects::nonNull) + .toList(); } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/PassedRoleLookup.java b/src/main/java/io/github/hectorvent/floci/services/iam/PassedRoleLookup.java new file mode 100644 index 0000000000..e4549f3f35 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/iam/PassedRoleLookup.java @@ -0,0 +1,32 @@ +package io.github.hectorvent.floci.services.iam; + +import java.util.List; +import java.util.Optional; + +/** + * Looks up what a stored resource holds that the {@code iam:PassRole} check of a request needs, for + * the operations that pass a role the request does not name itself: an ECS task started from a task + * definition runs with the definition's roles, and a self-managed StackSet that names no + * administration role uses the default one. + * + *

Implemented by the services that own those resources, each answering for its own and leaving + * the default for the rest; consumed lazily by {@code IamEnforcementFilter} via + * {@code Instance} so IAM never depends on them directly. Lookups are made in the + * request's account.

+ */ +public interface PassedRoleLookup { + + /** + * The task role and the task execution role of the ECS task definition {@code reference} names in + * {@code region}, a family, a {@code family:revision} or an ARN, as the definition stores them; + * empty when there is no such definition or it names neither. + */ + default List taskDefinitionRoles(String reference, String region) { + return List.of(); + } + + /** The permission model of the StackSet named {@code stackSetName}; empty when there is none. */ + default Optional stackSetPermissionModel(String stackSetName) { + return Optional.empty(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java index 070f56ba42..46420cbcd5 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java @@ -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 diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PassedRolesTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PassedRolesTest.java new file mode 100644 index 0000000000..1f3ffce0e1 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/PassedRolesTest.java @@ -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 instanceProfileRoleArns(String profileName, String profileArn) { + return List.of(); + } + + @Override + public List taskDefinitionRoles(String reference) { + return "web:3".equals(reference) ? List.of(ROLES + "web-task", "web-execution") : List.of(); + } + + @Override + public Optional 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 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 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; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java index 3b58184d14..8061114846 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java @@ -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); + } } }