mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -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
@@ -355,7 +355,8 @@ public class AwsJsonCborController {
|
||||
return request;
|
||||
}
|
||||
|
||||
private boolean isGZipped(List<String> contentEncodingHeaders) {
|
||||
// Package-private: PassedRoles reads the same body before this controller runs.
|
||||
static boolean isGZipped(List<String> 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;
|
||||
|
||||
@@ -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> scpProvider;
|
||||
private final SessionAccountLookup sessionAccountLookup;
|
||||
private final Instance<ResourcePolicyProvider> resourcePolicyProviders;
|
||||
private final Instance<PassedRoleLookup> 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> scpProvider,
|
||||
SessionAccountLookup sessionAccountLookup,
|
||||
Instance<ResourcePolicyProvider> resourcePolicyProviders,
|
||||
Instance<PassedRoleLookup> 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<String, List<String>> 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<String> instanceProfileRoleArns(String profileName, String profileArn) {
|
||||
return IamEnforcementFilter.this.instanceProfileRoleArns(accountId, profileName, profileArn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> taskDefinitionRoles(String reference) {
|
||||
List<String> roles = new ArrayList<>();
|
||||
for (PassedRoleLookup lookup : roleLookups()) {
|
||||
roles.addAll(lookup.taskDefinitionRoles(reference, region));
|
||||
}
|
||||
return roles;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> stackSetPermissionModel(String stackSetName) {
|
||||
for (PassedRoleLookup lookup : roleLookups()) {
|
||||
Optional<String> 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<PassedRoleLookup> 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<String> instanceProfileRoleArns(String accountId, String name, String arn) {
|
||||
String profileName = arn != null ? arn.substring(arn.lastIndexOf('/') + 1) : name;
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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}.
|
||||
*
|
||||
* <p>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<String> 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<String> instanceProfileRoleArns(String profileName, String profileArn);
|
||||
|
||||
/** The task role and task execution role of the ECS task definition {@code reference} names. */
|
||||
List<String> taskDefinitionRoles(String reference);
|
||||
|
||||
/** The permission model of the StackSet named {@code stackSetName}; empty when there is none. */
|
||||
Optional<String> 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<PassedRole> of(String action, ContainerRequestContext ctx, InstanceProfileRoles profiles) {
|
||||
static List<PassedRole> 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<PassedRole> 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<PassedRole> ecsTaskDefinition(JsonNode body, Lookups lookups) {
|
||||
List<String> 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<PassedRole> ecsTask(JsonNode body, Lookups lookups) {
|
||||
List<String> taskRoles = new ArrayList<>(taskDefinitionRoles(body, lookups));
|
||||
taskRoles.addAll(values(body, "overrides", "taskRoleArn"));
|
||||
taskRoles.addAll(values(body, "overrides", "executionRoleArn"));
|
||||
List<PassedRole> 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<PassedRole> ecsService(JsonNode body, Lookups lookups) {
|
||||
List<String> 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<PassedRole> passed = new ArrayList<>(ecsTaskDefinitionRoles(body, lookups));
|
||||
passed.addAll(ecsRoles(infrastructure, ECS, lookups));
|
||||
return passed;
|
||||
}
|
||||
|
||||
private static List<PassedRole> 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<String> taskDefinitionRoles(JsonNode body, Lookups lookups) {
|
||||
List<String> 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<PassedRole> ecsRoles(List<String> roles, String service, Lookups lookups) {
|
||||
List<String> 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<PassedRole> stackSetAdministrationRole(ContainerRequestContext ctx, Lookups lookups,
|
||||
boolean update) {
|
||||
Map<String, String> 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<String> 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<PassedRole> 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<String> values(JsonNode node, String... path) {
|
||||
List<String> found = new ArrayList<>();
|
||||
collect(node, path, 0, found);
|
||||
return found;
|
||||
}
|
||||
|
||||
private static void collect(JsonNode node, String[] path, int step, List<String> 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<PassedRole> 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<PassedRole> fromInstanceProfile(ContainerRequestContext ctx, InstanceProfileRoles profiles,
|
||||
String prefix) {
|
||||
private static List<PassedRole> fromInstanceProfile(ContainerRequestContext ctx, Lookups lookups, String prefix) {
|
||||
Map<String, String> 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;
|
||||
}
|
||||
|
||||
+9
-1
@@ -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<String> stackSetPermissionModel(String stackSetName) {
|
||||
return stackSets.get(stackSetName).map(StackSet::getPermissionModel);
|
||||
}
|
||||
|
||||
public List<StackSet> listStackSets() {
|
||||
return stackSets.scan(k -> true);
|
||||
}
|
||||
|
||||
@@ -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<String> 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();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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<PassedRoleLookup>} so IAM never depends on them directly. Lookups are made in the
|
||||
* request's account.</p>
|
||||
*/
|
||||
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<String> taskDefinitionRoles(String reference, String region) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
/** The permission model of the StackSet named {@code stackSetName}; empty when there is none. */
|
||||
default Optional<String> stackSetPermissionModel(String stackSetName) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user