fix(stepfunctions): check the tags Scheduler, ECS, EMR, CloudFormation and DynamoDB tasks create resources with (#10022)

A Step Functions task calling Scheduler, ECS, EMR, CloudFormation or
DynamoDB createTable was checked for its action and the roles it passes
but never for the tags it sends. Every arm now goes through
RequestChecks, so a runTask, createCluster, createStack family call or
createTable with tags needs the tag-on-create and tagging permissions
the generated tables give a direct call, and a request without tags is
checked exactly as before.

An ecs:runTask task now launches its tasks with the tags it is checked
for, building its request through the new EcsService.runTaskRequest
that the EventBridge and Scheduler targets share. RunTask with
propagateTags TASK_DEFINITION now gives a task the task definition's
tags beside the request's own, the request's value winning on a shared
key, instead of dropping the request's tags, and RunTask and StartTask
refuse a request whose merged tags would exceed 50 before any task
launches.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-12-02 22:05:47 -04:00
1 parent 6ae5ab98e3
commit 1fcfedf08e
12 files changed
+595 -90

No files matched your search

+4 -1
View File
@@ -329,7 +329,10 @@ converging reports none. Each `deployments` entry carries the placement it runs
`networkConfiguration`, not only its id and counts.
`RunTask` places at most 10 tasks per call and rejects `propagateTags: SERVICE`, which is a
service-only option; `TASK_DEFINITION` copies the task definition's tags onto each task.
service-only option; `TASK_DEFINITION` copies the task definition's tags onto each task beside the
request's own `tags`, the request's value winning on a key in both; a request whose tasks would carry more than
50 tags that way is refused with `InvalidParameterException` before any task is launched. Under IAM enforcement only the request's
`tags` are checked (`aws:RequestTag`, `aws:TagKeys` and `ecs:TagResource`), not the propagated ones.
`StartTask` requires the `containerInstances` it places onto, at most 10 of them.
`RunTask` and `StartTask` answer before the task's images are pulled, as AWS does. An `awsvpc` task
+32 -7
View File
@@ -701,6 +701,9 @@ The `aws-sdk:dynamodb` form is checked as a direct DynamoDB request under enforc
`dynamodb:EnclosingOperation` available to the policy. A table named by ARN counts for its name, as
execution reads it in the state machine's account.
- **`listTables`:** its action on the Region's `table/*` collection.
- **`createTable` with `Tags`:** `dynamodb:TagResource` on the table as well, and `dynamodb:CreateTable` with
each tag as `aws:RequestTag/<key>` and the keys as `aws:TagKeys`, beside its DynamoDB condition keys, as the
generated tag-on-create table gives a direct `CreateTable`.
- **`executeStatement`:** `dynamodb:PartiQLSelect`, `PartiQLInsert`, `PartiQLUpdate` or `PartiQLDelete`,
by what the statement does. `batchExecuteStatement` and `executeTransaction` are checked under their
own names on each table a statement names, as a direct request is.
@@ -784,8 +787,19 @@ calls, and it is what the CDK's policies for these two tasks grant.
`.sync` authorizes the starting call only: a job cannot fail midway through its wait for lack of a
Describe permission, and the best-effort cancel of an abandoned job is not evaluated either. What the
CDK grants a `.sync` task beyond that, such as `elasticmapreduce:DescribeStep` or `ecs:DescribeTasks`,
is accepted but not needed here. `iam:PassRole` is not evaluated for the roles `runTask` or `createCluster`
pass, nor a tagging action such as `elasticmapreduce:AddTags` for what they tag.
is accepted but not needed here.
The roles and tags an ECS or EMR API sends are checked from the same generated tables a direct request is.
`runTask` needs `iam:PassRole`, passed to `ecs-tasks.amazonaws.com`, on its task definition's task role and
execution role and on a `TaskRoleArn` or `ExecutionRoleArn` override. `createCluster` needs it on its
`ServiceRole`, the role of its `JobFlowRole` instance profile and its `AutoScalingRole`, each passed to the
service the generated data names. The `Tags` of a `runTask` need `ecs:TagResource`, with `ecs:CreateAction`
set to `RunTask`, on the task definition the call is checked on, and the `Tags` of a `createCluster` need
`elasticmapreduce:AddTags` on `*`, since `RunJobFlow` has no resource type. Both calls are checked with each tag as
`aws:RequestTag/<key>` and the keys as `aws:TagKeys` too. The tags checked are the ones the resource gets:
`runTask` passes its `Tags`, `PropagateTags` and `EnableECSManagedTags` to ECS as a direct `RunTask` does, and
`createCluster` its `Tags` to `RunJobFlow`. The generated data gives `AddJobFlowSteps` no role, so `addStep`
needs no `iam:PassRole`.
An EMR Serverless API is checked as the same request made directly is, from the generated tables, on the
request the integration sends: `startJobRun` also needs `iam:PassRole` on its `ExecutionRoleArn`, passed to
@@ -801,9 +815,10 @@ its answer: `.waitForTaskToken` on EMR and EMR Serverless and `.sync` on an EMR
`<prefix>.AccessDeniedException` is Floci's reading for these too and has not been verified against
AWS; the prefix is the one each integration's other errors carry. EMR's own errors reach a task as
`EMR.AmazonElasticMapReduceException` unless EMR models them, so AWS may word this one that way. Only
global condition keys are available to the policies: `ecs:cluster` and the like are absent, so an Allow
conditioned on them does not apply. With enforcement off nothing here is evaluated.
`EMR.AmazonElasticMapReduceException` unless EMR models them, so AWS may word this one that way. Apart from
`iam:PassedToService`, the tag keys and `ecs:CreateAction` above, only global condition keys are available to the
policies: `ecs:cluster` and the like are absent, so an Allow conditioned on them does not apply. With
enforcement off nothing here is evaluated.
## Control tasks under IAM enforcement
@@ -835,6 +850,17 @@ none) is on `*`, as are `validateTemplate`, `listStacks`, `listExports`, `create
`describeOrganizationsAccess` and `activateOrganizationsAccess`, which have no resource type. An API the handler
does not serve is evaluated the same way, and CloudFormation then answers it with `UnknownAction`.
The roles and tags a Scheduler or CloudFormation API sends are checked from the same generated tables a direct
request is. `createSchedule` and `updateSchedule` need `iam:PassRole` on their `Target`'s `RoleArn`, passed to
`scheduler.amazonaws.com`. A stack operation needs it on the `RoleARN` it names, and `createStackSet` and
`updateStackSet` on the administration role, the default `AWSCloudFormationStackSetAdministrationRole` of a
self-managed StackSet naming none among them, each passed to `cloudformation.amazonaws.com`. The `Tags` of
`createStack`, `updateStack`, `createChangeSet`, `createStackSet` and `updateStackSet` need
`cloudformation:TagResource`, with `cloudformation:CreateAction` set to the operation, on the stack or stack set
it acts on or the one it makes: the stack a `createStack` makes, `stack/<StackName>/*`, the stack set a
`createStackSet` makes or the change set a `createChangeSet` makes. The operation
itself is checked with each tag as `aws:RequestTag/<key>` and the keys as `aws:TagKeys`. A schedule takes no tags.
`states:InvokeHTTPEndpoint` has no resource type in the Service Authorization Reference, and the CDK grants
it on `*`, while the Developer Guide's example scopes it to the state machine, so the state machine is what is
evaluated: both policies allow it. The task gives `states:HTTPEndpoint` and `states:HTTPMethod`, both of which
@@ -867,8 +893,7 @@ An activity task is not evaluated: the CDK's own task needs no permission for it
`<prefix>.AccessDeniedException` and `States.Http.AccessDeniedException` are Floci's reading and have not
been verified against AWS; a nested task with `Credentials` reports a refused action as
`StepFunctions.AWSStepFunctionsException` or `Sfn.SfnException` instead, so a state machine catching this should
name both. `iam:PassRole` is not evaluated for the roles a schedule or a stack names, and only
the condition keys above and global ones are available to the policies. With enforcement off nothing here is
name both. Only the condition keys above, `iam:PassedToService` and global ones are available to the policies. With enforcement off nothing here is
evaluated.
## Distributed Map S3 calls under IAM enforcement
@@ -433,11 +433,20 @@ public class EcsJsonHandler {
request.setPlatformVersion(req.hasNonNull("platformVersion")
? JsonNodes.asText(req.path("platformVersion")) : null);
request.setEnableExecuteCommand(JsonNodes.asBoolean(req.path("enableExecuteCommand"), false));
request.setReferenceId(req.has("referenceId") ? JsonNodes.asText(req.path("referenceId")) : null);
readRunTaskTagging(req, request);
return request;
}
/**
* Reads the members of a RunTask request that tag the tasks it launches, {@code tags}, {@code propagateTags} and
* {@code enableECSManagedTags}, into {@code request}, as a direct RunTask reads them: a Step Functions
* {@code ecs:runTask} task, whose tags are authorized as a direct RunTask's are, tags its tasks the same way.
*/
public void readRunTaskTagging(JsonNode req, RunTaskRequest request) {
request.setEnableECSManagedTags(JsonNodes.asBoolean(req.path("enableECSManagedTags"), false));
request.setPropagateTags(parseChoice(req, "propagateTags", PROPAGATE_TAGS));
request.setReferenceId(req.has("referenceId") ? JsonNodes.asText(req.path("referenceId")) : null);
request.setTags(parseTagMap(req.path("tags")));
return request;
}
private Response handleStopTask(JsonNode req, String region) {
@@ -1714,7 +1723,7 @@ public class EcsJsonHandler {
return result;
}
private static final int MAX_TAGS_PER_RESOURCE = 50;
private static final int MAX_TAGS_PER_RESOURCE = EcsService.MAX_TAGS_PER_RESOURCE;
private static final int MAX_TAG_KEY_LENGTH = 128;
private static final int MAX_TAG_VALUE_LENGTH = 256;
@@ -219,6 +219,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
public static final String PROPAGATE_TAGS_SERVICE = "SERVICE";
public static final String PROPAGATE_TAGS_TASK_DEFINITION = "TASK_DEFINITION";
public static final String PROPAGATE_TAGS_NONE = "NONE";
/** The most tags ECS lets a resource carry, the limit a request's own tag list is held to as well. */
static final int MAX_TAGS_PER_RESOURCE = 50;
/** A service deployment whose target revision's tasks are not all up yet. */
public static final String DEPLOYMENT_STATUS_IN_PROGRESS = "IN_PROGRESS";
/** A service deployment whose target revision is running at its requested task count. */
@@ -1588,6 +1590,19 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
LaunchType launchType, String group, String startedBy,
List<ContainerOverride> containerOverrides,
NetworkConfiguration networkConfiguration, String region) {
return runTask(runTaskRequest(clusterRef, taskDefinitionRef, count, launchType, group, startedBy,
containerOverrides, networkConfiguration), region);
}
/**
* The RunTask request a caller other than the ECS API builds from its members (an EventBridge or Scheduler
* target, a Step Functions task), container overrides set only when there are any; a caller adds what else it
* sends, such as its tags.
*/
public static RunTaskRequest runTaskRequest(String clusterRef, String taskDefinitionRef, int count,
LaunchType launchType, String group, String startedBy,
List<ContainerOverride> containerOverrides,
NetworkConfiguration networkConfiguration) {
RunTaskRequest request = new RunTaskRequest();
request.setCluster(clusterRef);
request.setTaskDefinition(taskDefinitionRef);
@@ -1601,7 +1616,36 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
overrides.setContainerOverrides(containerOverrides);
request.setOverrides(overrides);
}
return runTask(request, region);
return request;
}
/**
* The tags a launched task gets: the task definition's when the request propagates them, and the request's own
* on top. Propagating adds tags and drops none the request names, as the RunTask reference describes it, and a key
* in both keeps the request's value, the one authorized as the request's tags ({@code aws:RequestTag}), so the
* tags checked are the tags the task carries.
*/
private static Map<String, String> taskTags(TaskDefinition taskDef, RunTaskRequest request) {
Map<String, String> tags = new LinkedHashMap<>();
if (PROPAGATE_TAGS_TASK_DEFINITION.equals(request.getPropagateTags()) && taskDef.getTags() != null) {
tags.putAll(taskDef.getTags());
}
if (request.getTags() != null) {
tags.putAll(request.getTags());
}
return tags;
}
/**
* Refuses a request whose tasks would carry more tags than a resource takes, before any is launched: the tags it
* names and the task definition's it propagates, a key in both counted once, as {@link #taskTags} merges them.
* Every key counts, as the handler counts a request's own list, with the same refusal.
*/
private static void checkTaskTagCount(TaskDefinition taskDef, RunTaskRequest request) {
if (taskTags(taskDef, request).size() > MAX_TAGS_PER_RESOURCE) {
throw new AwsException("InvalidParameterException",
"Too many tags specified. A resource takes at most " + MAX_TAGS_PER_RESOURCE + " tags.", 400);
}
}
public List<EcsTask> runTask(RunTaskRequest request, String region) {
@@ -1617,6 +1661,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
EcsCluster cluster = resolveClusterOrDefault(request.getCluster(), region);
TaskDefinition taskDef = resolveLaunchableTaskDefinition(request.getTaskDefinition(), region);
checkTaskTagCount(taskDef, request);
return launchTasks(cluster, taskDef, request, null, null, region);
}
@@ -1646,6 +1691,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
EcsCluster cluster = resolveClusterOrDefault(request.getCluster(), region);
TaskDefinition taskDef = resolveLaunchableTaskDefinition(request.getTaskDefinition(), region);
checkTaskTagCount(taskDef, request);
List<EcsTask> result = new ArrayList<>();
// StartTask places one task onto each named container instance, which is EC2 by definition.
request.setCount(1);
@@ -1715,10 +1761,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
task.setAttributes(List.of(new Attribute(CPU_ARCHITECTURE_ATTRIBUTE, hostCpuArchitecture(),
null, null)));
applyPlatform(task, taskDef, request);
Map<String, String> taskTags = PROPAGATE_TAGS_TASK_DEFINITION.equals(request.getPropagateTags())
? taskDef.getTags() : request.getTags();
if (taskTags != null && !taskTags.isEmpty()) {
task.setTags(new LinkedHashMap<>(taskTags));
Map<String, String> taskTags = taskTags(taskDef, request);
if (!taskTags.isEmpty()) {
task.setTags(taskTags);
}
// Before the task is visible: an awsvpc task that cannot get its ENI (an unknown
// subnet, say) never existed, the way AWS rejects the request rather than placing it.
@@ -36,6 +36,7 @@ import io.floci.aws.services.ecs.model.ContainerOverride;
import io.floci.aws.services.ecs.model.EcsTask;
import io.floci.aws.services.ecs.model.LaunchType;
import io.floci.aws.services.ecs.model.NetworkConfiguration;
import io.floci.aws.services.ecs.model.RunTaskRequest;
import io.floci.aws.services.ecs.model.TaskDefinition;
import io.floci.aws.services.eventbridge.EventBridgeHandler;
import io.floci.aws.services.eventbridge.EventBridgeInvoker;
@@ -2394,10 +2395,13 @@ public class AslExecutor {
JsonNode networkConfigNode = recaseKeys(objectMapper, input.path("NetworkConfiguration"), false);
NetworkConfiguration networkConfiguration = ecsJsonHandler.parseNetworkConfiguration(networkConfigNode);
RunTaskRequest request = EcsService.runTaskRequest(cluster, taskDefinition, count, launchType, group,
startedBy, overrides, networkConfiguration);
List<EcsTask> launched;
try {
launched = ecsService.runTask(cluster, taskDefinition, count, launchType, group, startedBy,
overrides, networkConfiguration, region);
// The tags are authorized as a direct RunTask's are (TaskPermissions), so they tag the tasks as its do.
ecsJsonHandler.readRunTaskTagging(recaseKeys(objectMapper, input, false), request);
launched = ecsService.runTask(request, region);
} catch (AwsException e) {
throw new FailStateException("ECS." + e.getErrorCode(), e.getMessage());
}
@@ -425,10 +425,26 @@ record TaskPermissions(String deniedError, List<Permission> permissions, boolean
owner.accountId(), null);
List<Map<String, List<String>>> contexts = input.isObject()
? dynamoDbConditionKeys(namedAs, input, owner.region(), lookups) : List.of(Map.of());
return accessDenied(DYNAMODB_SDK_PREFIX, (named.isEmpty() ? List.of(ANY_RESOURCE) : named).stream()
// What the same request made directly also needs (RequestChecks): the tags a CreateTable sends, as condition
// keys of its own action, merged with DynamoDB's, and dynamodb:TagResource on the table it creates.
List<Permission> direct = input.isObject() ? requestChecks(namedAs, input, machine, null, lookups) : List.of();
String action = IamAuthorizedActions.actionFor("dynamodb", operation);
List<Map<String, List<String>>> tagContexts = direct.stream().filter(check -> check.action().equals(action))
.map(Permission::conditionKeys).distinct().toList();
List<Map<String, List<String>>> merged = tagContexts.isEmpty() ? contexts : contexts.stream()
.flatMap(context -> tagContexts.stream().map(tags -> {
Map<String, List<String>> both = new LinkedHashMap<>(context);
both.putAll(tags);
return Map.copyOf(both);
}))
.distinct()
.toList();
List<Permission> permissions = new ArrayList<>((named.isEmpty() ? List.of(ANY_RESOURCE) : named).stream()
.filter(resource -> ANY_RESOURCE.equals(resource) || AwsArnUtils.isArn(resource))
.flatMap(resource -> contexts.stream().map(context -> new Permission(namedAs, resource, context)))
.flatMap(resource -> merged.stream().map(context -> new Permission(namedAs, resource, context)))
.toList());
direct.stream().filter(check -> !check.action().equals(action)).forEach(permissions::add);
return accessDenied(DYNAMODB_SDK_PREFIX, permissions);
}
/**
@@ -554,37 +570,38 @@ record TaskPermissions(String deniedError, List<Permission> permissions, boolean
}
/**
* The ECS call an API makes, checked as the vendored request resources check the same call made directly, on what
* its request names, its members read in either casing as the integration recases them: {@code RunTask} on the
* The ECS call an API makes, checked as the same call made directly is ({@link #requestChecks}), on what its
* request names, its members read in either casing as the integration recases them: {@code RunTask} on the
* revision ECS resolves its task definition to, a family alone being its latest, and a service on the cluster the
* request names, or the default one. {@code ListServices} acts on no resource type. A request that is no object is
* answered by the service. The roles the call passes need {@code iam:PassRole}, as the same call's made directly
* do: a task definition's task role and execution role, and a role override, which the CDK grants for a
* {@code RunTask} task as well.
* request names, or the default one. {@code ListServices} acts on no resource type. The roles the call passes need
* {@code iam:PassRole}: a task definition's task role and execution role, and a role override, which the CDK grants
* for a {@code RunTask} task as well; and the tags a {@code RunTask} sends need {@code ecs:TagResource}, the call
* itself being checked with them. A request that is no object, or that names nothing it can reach, is answered by
* the service, whatever roles or tags it names.
*/
private static List<Permission> ecs(String operation, JsonNode input, StateMachine machine,
StoredResourceArns ecs, RequestLookups lookups) {
JsonNode request = AslExecutor.recaseKeys(MAPPER, input, false);
return withPassedRoles(requestPermissions("ecs", operation, request, machine, ecs), "ecs", operation, request,
machine, lookups);
if (requestPermissions("ecs", operation, request, machine, ecs).isEmpty()) {
return List.of();
}
return requestChecks("ecs:" + operation, request, machine, ecs, lookups);
}
/**
* {@code permissions} and, when they are any, {@code iam:PassRole} on each role the request passes, as the same
* request made directly is checked ({@link RequestChecks#passedRoles}). A request needing no permission is left
* to its service, whatever roles it names.
* The checks the same request made directly needs, in the state machine's partition, Region and account
* ({@link RequestChecks#of}): the operation's action on each resource the request names, {@code stored} finding the
* ones only its service knows, or on any resource when it names none; {@code iam:PassRole} on each role it passes;
* and the service's tagging action on what it creates, for the tags it carries, which the operation's own action
* is checked with too where it takes them. An operation the table does not read needs nothing here.
*/
private static List<Permission> withPassedRoles(List<Permission> permissions, String namespace, String operation,
JsonNode request, StateMachine machine, RequestLookups lookups) {
if (permissions.isEmpty() || !request.isObject()) {
return permissions;
}
private static List<Permission> requestChecks(String operation, JsonNode request, StateMachine machine,
StoredResourceArns stored, RequestLookups lookups) {
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
List<Permission> checked = new ArrayList<>(permissions);
RequestChecks.passedRoles(namespace + ":" + operation, request, owner.partition(),
owner.region(), owner.accountId(), lookups.roles())
.forEach(check -> checked.add(new Permission(check.action(), check.resource(), check.context())));
return checked;
return RequestChecks.of(operation, request, owner.partition(), owner.region(), owner.accountId(), stored,
lookups.roles()).stream()
.map(check -> new Permission(check.action(), check.resource(), check.context()))
.toList();
}
/**
@@ -609,34 +626,28 @@ record TaskPermissions(String deniedError, List<Permission> permissions, boolean
}
/**
* The EMR calls the API's {@code start} makes, each checked as the vendored request resources check the same
* call made directly: the integration finds the cluster by {@code ClusterId} alone, and hands it to each call
* in the member that call names it by. {@code RunJobFlow} acts on no resource type, and passes the cluster's roles,
* which need {@code iam:PassRole}, as the CDK grants it on the service role, the cluster role and the auto scaling
* role. A request naming no cluster is refused by the integration.
* The EMR calls the API's {@code start} makes, each checked as the same call made directly is
* ({@link #requestChecks}): the integration finds the cluster by {@code ClusterId} alone, and hands it to each call
* in the member that call names it by. {@code RunJobFlow} is the task's own request, which acts on no resource
* type, passes the cluster's roles, which need {@code iam:PassRole}, as the CDK grants it on the service role, the
* cluster role and the auto scaling role, and needs {@code elasticmapreduce:AddTags} for the tags it sends, being
* checked with them itself. A request naming no cluster is refused by the integration.
*/
private static TaskPermissions emr(String api, JsonNode input, StateMachine machine, RequestLookups lookups) {
String clusterId = text(input.path("ClusterId"));
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
List<Permission> permissions = new ArrayList<>();
for (String operation : EMR_CALLS.getOrDefault(api, List.of())) {
String namedAs = "elasticmapreduce:" + operation;
String action = IamAuthorizedActions.actionFor("elasticmapreduce", operation);
if (RequestResources.actsOnNoResource(namedAs)) {
permissions.add(new Permission(action, ANY_RESOURCE));
if ("RunJobFlow".equals(operation)) {
permissions.addAll(requestChecks(namedAs, input, machine, null, lookups));
continue;
}
if (clusterId == null) {
return accessDenied(EMR_PREFIX, List.of());
}
for (String resource : RequestResources.ofBody(namedAs, emrRequest(operation, clusterId),
owner.partition(), owner.region(), owner.accountId(), null)) {
permissions.add(new Permission(action, resource));
}
permissions.addAll(requestChecks(namedAs, emrRequest(operation, clusterId), machine, null, lookups));
}
return accessDenied(EMR_PREFIX, "createCluster".equals(api)
? withPassedRoles(permissions, "elasticmapreduce", "RunJobFlow", input, machine, lookups)
: permissions);
return accessDenied(EMR_PREFIX, permissions);
}
/**
@@ -674,30 +685,23 @@ record TaskPermissions(String deniedError, List<Permission> permissions, boolean
|| "cancelJobRun".equals(api) && !request.has("jobRunId")) {
return accessDenied(EMR_SERVERLESS_PREFIX, List.of());
}
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
return accessDenied(EMR_SERVERLESS_PREFIX, RequestChecks.of("emr-serverless:" + AslExecutor.capitalizeFirst(api),
request, owner.partition(), owner.region(), owner.accountId(), null, lookups.roles()).stream()
.map(check -> new Permission(check.action(), check.resource(), check.context())).toList());
return accessDenied(EMR_SERVERLESS_PREFIX, requestChecks("emr-serverless:" + AslExecutor.capitalizeFirst(api),
request, machine, null, lookups));
}
/**
* The action on the schedule the request names, as the request-resources table reads it for a direct Scheduler
* request: its name and group, a group left out being the one {@code stored} gives as Scheduler's default, and
* {@code iam:PassRole} on the role its target runs as, which the CDK grants. A request naming no schedule is
* refused by Scheduler.
* The check the same Scheduler request made directly gets ({@link #requestChecks}): its action on the schedule it
* names, by its name and group, a group left out being the one {@code stored} gives as Scheduler's default, and
* {@code iam:PassRole} on the role its target runs as, which the CDK grants. A schedule takes no tags. A request
* naming no schedule is refused by Scheduler.
*/
private static TaskPermissions scheduler(String api, JsonNode input, StateMachine machine,
StoredResourceArns stored, RequestLookups lookups) {
if (text(input.path("Name")) == null) {
return accessDenied(SCHEDULER_PREFIX, List.of());
}
String operation = AslExecutor.capitalizeFirst(api);
String action = IamAuthorizedActions.actionFor("scheduler", operation);
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
return accessDenied(SCHEDULER_PREFIX, withPassedRoles(RequestResources.ofBody("scheduler:" + operation, input,
owner.partition(), owner.region(), owner.accountId(), stored).stream()
.map(resource -> new Permission(action, resource))
.toList(), "scheduler", operation, input, machine, lookups));
return accessDenied(SCHEDULER_PREFIX, requestChecks("scheduler:" + AslExecutor.capitalizeFirst(api), input,
machine, stored, lookups));
}
/**
@@ -709,17 +713,21 @@ record TaskPermissions(String deniedError, List<Permission> permissions, boolean
}
/**
* The check the vendored request resources give the same call made directly ({@link #requestPermissions}),
* {@code stored} finding the stack or the stack set a name names; on any resource when the request names none,
* whatever its input is, as a direct request naming none is checked. The service role a stack operation names and
* a StackSet's administration role need {@code iam:PassRole}, as they do made directly.
* The checks the same call made directly gets ({@link #requestChecks}), {@code stored} finding the stack or the
* stack set a name names; on any resource when the request names none, whatever its input is, as a direct request
* naming none is checked. The service role a stack operation names and a StackSet's administration role need
* {@code iam:PassRole}, and the tags a stack or stack set operation sends need {@code cloudformation:TagResource},
* the operation itself being checked with them, as they do made directly. An input that is no object names
* nothing, and is checked on any resource alone.
*/
private static TaskPermissions cloudFormation(String operation, JsonNode input, StateMachine machine,
StoredResourceArns stored, RequestLookups lookups) {
List<Permission> permissions = requestPermissions("cloudformation", operation, input, machine, stored);
return accessDenied(CLOUDFORMATION_PREFIX, withPassedRoles(permissions.isEmpty()
? List.of(new Permission(IamAuthorizedActions.actionFor("cloudformation", operation), ANY_RESOURCE))
: permissions, "cloudformation", operation, input, machine, lookups));
if (!input.isObject()) {
return accessDenied(CLOUDFORMATION_PREFIX, List.of(new Permission(
IamAuthorizedActions.actionFor("cloudformation", operation), ANY_RESOURCE)));
}
return accessDenied(CLOUDFORMATION_PREFIX, requestChecks("cloudformation:" + operation, input, machine, stored,
lookups));
}
/**
@@ -424,6 +424,67 @@ class EcsFargateEdgeCaseIntegrationTest {
.body("tasks[0].tags[0].value", equalTo("platform"));
}
/**
* Propagating the task definition's tags adds them to the ones the request names rather than replacing them, and
* a key in both keeps the request's value: the request's tags are the ones a RunTask is authorized for.
*/
@Test
void propagatedTaskDefinitionTagsJoinTheRequestsOwn() {
call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200);
call("RegisterTaskDefinition", "{\"family\":\"edge-td-tags-both\","
+ "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\","
+ "\"cpu\":\"256\",\"memory\":\"512\",\"tags\":[{\"key\":\"owner\",\"value\":\"platform\"},"
+ "{\"key\":\"team\",\"value\":\"definition\"}],"
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 200);
call("RunTask", "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"edge-td-tags-both\","
+ "\"launchType\":\"FARGATE\"," + NETWORK + ",\"propagateTags\":\"TASK_DEFINITION\","
+ "\"tags\":[{\"key\":\"team\",\"value\":\"data\"},{\"key\":\"run\",\"value\":\"7\"}]}", 200)
.then()
.body("tasks[0].tags.size()", equalTo(3))
.body("tasks[0].tags.find { it.key == 'owner' }.value", equalTo("platform"))
.body("tasks[0].tags.find { it.key == 'team' }.value", equalTo("data"))
.body("tasks[0].tags.find { it.key == 'run' }.value", equalTo("7"));
}
/**
* The tags a task would carry, its own and the task definition's it propagates, are held to the 50 a resource
* takes, a key in both counted once: two lists within the limit whose union is over it are refused and launch
* nothing, and a union of exactly 50 runs.
*/
@Test
void propagatedAndOwnTagsTogetherAreHeldToTheResourceLimit() {
call("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}", 200);
call("RegisterTaskDefinition", "{\"family\":\"edge-td-tag-limit\","
+ "\"requiresCompatibilities\":[\"FARGATE\"],\"networkMode\":\"awsvpc\","
+ "\"cpu\":\"256\",\"memory\":\"512\",\"tags\":" + tagList("d", 0, 30) + ","
+ "\"containerDefinitions\":[{\"name\":\"app\",\"image\":\"nginx:latest\"}]}", 200);
String run = "{\"cluster\":\"" + CLUSTER + "\",\"taskDefinition\":\"edge-td-tag-limit\","
+ "\"launchType\":\"FARGATE\"," + NETWORK + ",\"propagateTags\":\"TASK_DEFINITION\",\"tags\":";
int before = call("ListTasks", "{\"cluster\":\"" + CLUSTER + "\"}", 200).jsonPath()
.getList("taskArns").size();
call("RunTask", run + tagList("r", 0, 30) + "}", 400)
.then().body("__type", containsString("InvalidParameterException"))
.body("message", containsString("Too many tags"));
assertEquals(before, call("ListTasks", "{\"cluster\":\"" + CLUSTER + "\"}", 200).jsonPath()
.getList("taskArns").size());
// 10 of the request's keys are the definition's own: 30 + 30 - 10 = 50.
call("RunTask", run + tagList("d", 20, 30) + "}", 200)
.then().body("tasks[0].tags.size()", equalTo(50));
}
/** {@code count} tags {@code <prefix><n>}, n from {@code from}, each valued by its key. */
private static String tagList(String prefix, int from, int count) {
StringBuilder tags = new StringBuilder("[");
for (int i = from; i < from + count; i++) {
tags.append(i == from ? "" : ",").append("{\"key\":\"").append(prefix).append(i)
.append("\",\"value\":\"v\"}");
}
return tags.append("]").toString();
}
/**
* The ENI allocation reaches into EC2, whose not-found codes RunTask does not declare. An SDK
* given {@code InvalidSubnetID.NotFound} sees an unmodelled failure instead of the
@@ -9,6 +9,7 @@ import io.floci.aws.services.ecs.container.HostVolumePolicy;
import io.floci.aws.services.ecs.model.Container;
import io.floci.aws.services.ecs.model.EcsTask;
import io.floci.aws.services.ecs.model.NetworkConfiguration;
import io.floci.aws.services.ecs.model.RunTaskRequest;
import io.floci.aws.services.stepfunctions.model.Execution;
import io.floci.aws.services.stepfunctions.model.HistoryEvent;
import io.floci.aws.services.stepfunctions.model.StateMachine;
@@ -31,7 +32,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
@@ -97,7 +97,7 @@ class AslExecutorEcsRunTaskModeTest {
void requestResponseDoesNotFailWhenNoTasksLaunched() throws Exception {
// No tasks could be placed (AWS: 200 with a non-empty Failures list). Request-response
// must return the envelope and let execution continue, not fail the state.
when(ecsService.runTask(any(), any(), anyInt(), any(), any(), any(), any(), any(), any()))
when(ecsService.runTask(any(RunTaskRequest.class), any()))
.thenReturn(new ArrayList<>());
Execution execution = run("arn:aws:states:::ecs:runTask",
@@ -112,7 +112,7 @@ class AslExecutorEcsRunTaskModeTest {
@Test
void syncFailsWithAmazonEcsUnknownWhenNoTasksLaunched() throws Exception {
when(ecsService.runTask(any(), any(), anyInt(), any(), any(), any(), any(), any(), any()))
when(ecsService.runTask(any(RunTaskRequest.class), any()))
.thenReturn(new ArrayList<>());
Execution execution = run("arn:aws:states:::ecs:runTask.sync",
@@ -132,12 +132,12 @@ class AslExecutorEcsRunTaskModeTest {
assertEquals("FAILED", execution.getStatus());
assertEquals("States.TaskFailed", execution.getError());
assertEquals("Unsupported resource: arn:aws:states:::ecs:runTask.sync:2", execution.getCause());
verify(ecsService, never()).runTask(any(), any(), anyInt(), any(), any(), any(), any(), any(), any());
verify(ecsService, never()).runTask(any(RunTaskRequest.class), any());
}
@Test
void networkConfigurationIsThreadedThroughToRunTask() throws Exception {
when(ecsService.runTask(any(), any(), anyInt(), any(), any(), any(), any(), any(), any()))
when(ecsService.runTask(any(RunTaskRequest.class), any()))
.thenReturn(new ArrayList<>());
run("arn:aws:states:::ecs:runTask", """
@@ -154,11 +154,10 @@ class AslExecutorEcsRunTaskModeTest {
}
""");
ArgumentCaptor<NetworkConfiguration> captor = ArgumentCaptor.forClass(NetworkConfiguration.class);
verify(ecsService).runTask(
any(), any(), anyInt(), any(), any(), any(), any(), captor.capture(), any());
ArgumentCaptor<RunTaskRequest> captor = ArgumentCaptor.forClass(RunTaskRequest.class);
verify(ecsService).runTask(captor.capture(), any());
NetworkConfiguration passed = captor.getValue();
NetworkConfiguration passed = captor.getValue().getNetworkConfiguration();
assertNotNull(passed, "NetworkConfiguration should be parsed and passed, not dropped");
assertNotNull(passed.getAwsvpcConfiguration());
assertEquals(List.of("subnet-123"), passed.getAwsvpcConfiguration().getSubnets());
@@ -166,6 +165,30 @@ class AslExecutorEcsRunTaskModeTest {
assertEquals("ENABLED", passed.getAwsvpcConfiguration().getAssignPublicIp());
}
/**
* The tags a task sends, which are authorized as a direct RunTask's are, tag the tasks it launches as a direct
* RunTask's do, with its tag propagation and managed tags.
*/
@Test
void tagsArePassedToRunTask() throws Exception {
when(ecsService.runTask(any(RunTaskRequest.class), any())).thenReturn(new ArrayList<>());
run("arn:aws:states:::ecs:runTask", """
{
"TaskDefinition": "my-task-def",
"Tags": [{"Key": "team", "Value": "data"}],
"PropagateTags": "TASK_DEFINITION",
"EnableECSManagedTags": true
}
""");
ArgumentCaptor<RunTaskRequest> captor = ArgumentCaptor.forClass(RunTaskRequest.class);
verify(ecsService).runTask(captor.capture(), eq(REGION));
assertEquals(Map.of("team", "data"), captor.getValue().getTags());
assertEquals("TASK_DEFINITION", captor.getValue().getPropagateTags());
assertTrue(captor.getValue().isEnableECSManagedTags());
}
@Test
void syncFailsWithStatesTimeoutWhenTheTaskOutlivesTimeoutSeconds() throws Exception {
launchOneTask();
@@ -434,7 +457,7 @@ class AslExecutorEcsRunTaskModeTest {
}
private void launchOneTask() {
when(ecsService.runTask(any(), any(), anyInt(), any(), any(), any(), any(), any(), any()))
when(ecsService.runTask(any(RunTaskRequest.class), any()))
.thenReturn(List.of(task("PENDING")));
}
@@ -302,6 +302,45 @@ class StepFunctionsControlTaskIamIntegrationTest {
target.reached().check();
}
/**
* Tags a stack is created with need {@code cloudformation:TagResource} on the stack, with {@code CreateStack} as
* {@code cloudformation:CreateAction}, as a direct {@code CreateStack} does, and {@code CreateStack} itself is
* checked with them: a role allowed {@code CreateStack} alone is refused and creates nothing.
*/
@Test
void tagsAStackIsCreatedWithNeedTagResource() throws Exception {
Target untagged = target("aws-sdk:cloudformation:createStack");
Map<String, Object> arguments = new LinkedHashMap<>(untagged.arguments());
arguments.put("Tags", List.of(Map.of("Key", "team", "Value", "data")));
Target target = new Target(untagged.integration(), untagged.machineName(), arguments, untagged.action(),
untagged.resourceArn(), untagged.error(), untagged.serviceError(), untagged.reached(),
untagged.notReached(), untagged.passedRole(), untagged.companions());
Map<String, Object> createStack = Map.of("Effect", "Allow", "Action", List.of(target.action()),
"Resource", List.of(target.resourceArn()),
"Condition", Map.of("StringEquals", Map.of("aws:RequestTag/team", "data")));
Response refused = terminal(start(machine("sfn-control-" + UUID.randomUUID(), jsonPathTask(target, null),
role(STATES_TRUST, target.grantWith(createStack))), "{}"));
assertFailed(refused, target.error());
assertTrue(refused.jsonPath().getString("cause").contains("cloudformation:TagResource"), refused.asString());
target.notReached().check();
Response allowed = terminal(start(machine("sfn-control-" + UUID.randomUUID(), jsonPathTask(target, null),
role(STATES_TRUST, policy(List.of(createStack, Map.of("Effect", "Allow",
"Action", List.of("cloudformation:TagResource"), "Resource", List.of(target.resourceArn()),
"Condition", Map.of("StringEquals", Map.of("cloudformation:CreateAction", "CreateStack"))))))),
"{}"));
assertAnsweredByTheService(allowed, target);
target.reached().check();
// The tags checked are the ones the stack gets, as a direct CreateStack's are.
Response described = cloudFormation("DescribeStacks",
Map.of("StackName", arguments.get("StackName").toString()));
described.then().statusCode(200);
assertEquals("data", described.xmlPath()
.getString("**.find { it.name() == 'Tags' }.member.find { it.Key == 'team' }.Value"),
described.asString());
}
/** {@code target} naming a service role when it is a stack it creates, which the others already pass. */
private Target passingARole(Target target) {
if (!"aws-sdk:cloudformation:createStack".equals(target.integration())) {
@@ -671,6 +671,38 @@ class StepFunctionsDataTaskIamIntegrationTest {
verify(redshiftDataService, timeout(5000)).executeStatement(any(JsonNode.class), anyString());
}
/**
* Tags a table is created with need {@code dynamodb:TagResource} on it, as a direct {@code CreateTable}'s do, and
* {@code CreateTable} itself is checked with them: a role allowed {@code CreateTable} alone is refused and creates
* nothing, and with both the table carries the tags.
*/
@Test
void tagsATableIsCreatedWithNeedTagResource() throws Exception {
String name = "sfn-iam-" + UUID.randomUUID();
cleanup.register(() -> sfn().json(ACCOUNT, "dynamodb", "DynamoDB_20120810.DeleteTable",
"application/x-amz-json-1.0", Map.of("TableName", name)));
Map<String, Object> task = Map.of("Type", "Task", "Resource", "arn:aws:states:::aws-sdk:dynamodb:createTable",
"Parameters", Map.of("TableName", name, "BillingMode", "PAY_PER_REQUEST",
"AttributeDefinitions", List.of(Map.of("AttributeName", "pk", "AttributeType", "S")),
"KeySchema", List.of(Map.of("AttributeName", "pk", "KeyType", "HASH")),
"Tags", List.of(Map.of("Key", "team", "Value", "data"))),
"End", true);
Map<String, Object> createTable = Map.of("Effect", "Allow", "Action", "dynamodb:CreateTable",
"Resource", tableArn(name), "Condition", Map.of("StringEquals", Map.of("aws:RequestTag/team", "data")));
Response refused = terminal(start(machine(task, role(STATES_TRUST, policy(List.of(createTable)))), "{}"));
assertFailed(refused, "DynamoDb.AccessDeniedException");
assertTrue(refused.jsonPath().getString("cause").contains("dynamodb:TagResource"), refused.asString());
assertEquals(400, sfn().json(ACCOUNT, "dynamodb", "DynamoDB_20120810.DescribeTable",
"application/x-amz-json-1.0", Map.of("TableName", name)).statusCode());
Response allowed = terminal(start(machine(task, role(STATES_TRUST, policy(List.of(createTable,
Map.of("Effect", "Allow", "Action", "dynamodb:TagResource", "Resource", tableArn(name)))))), "{}"));
assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString());
Response tags = dynamoDb("ListTagsOfResource", Map.of("ResourceArn", tableArn(name)));
assertEquals(List.of(Map.of("Key", "team", "Value", "data")), tags.jsonPath().getList("Tags"), tags.asString());
}
private static String allow(String resource, String... actions) {
return allowEach(List.of(resource), actions);
}
@@ -307,6 +307,124 @@ class StepFunctionsJobTaskIamIntegrationTest {
target.reached().check();
}
/**
* Tags a task is started with need {@code ecs:TagResource}, with {@code RunTask} as {@code ecs:CreateAction}, as a
* direct {@code RunTask} does, and {@code RunTask} itself is checked with them: a role allowed {@code RunTask} alone
* is refused and starts nothing.
*/
@Test
void tagsARunTaskSendsNeedTagResource() throws Exception {
String family = "sfn-jobs-" + UUID.randomUUID();
ecs("RegisterTaskDefinition", Map.of("family", family, "containerDefinitions",
List.of(Map.of("name", "runner", "image", "floci-test/runner:latest", "memory", 128))))
.then().statusCode(200);
cleanup.register(() -> {
ecs("DeregisterTaskDefinition", Map.of("taskDefinition", family + ":1")).then().statusCode(200);
ecs("DeleteTaskDefinitions", Map.of("taskDefinitions", List.of(family + ":1"))).then().statusCode(200);
});
String cluster = ecsCluster();
Map<String, Object> task = task("ecs:runTask", Map.of("Cluster", cluster, "TaskDefinition", family,
"Tags", List.of(Map.of("Key", "team", "Value", "data"))));
Map<String, Object> runTask = Map.of("Effect", "Allow", "Action", List.of("ecs:RunTask"),
"Resource", List.of(taskDefinitionArn(family, 1)), "Condition",
Map.of("StringEquals", Map.of("aws:RequestTag/team", "data")));
Response refused = terminal(start(machine(task, role(STATES_TRUST, policy(List.of(runTask)))), "{}"));
assertFailed(refused, "ECS.AccessDeniedException");
assertTrue(refused.jsonPath().getString("cause").contains("ecs:TagResource"), refused.asString());
assertEquals(List.of(), runningTasks(cluster));
Response allowed = terminal(start(machine(task, role(STATES_TRUST, policy(List.of(runTask,
Map.of("Effect", "Allow", "Action", List.of("ecs:TagResource"), "Resource", List.of(ANY_RESOURCE),
"Condition", Map.of("StringEquals", Map.of("ecs:CreateAction", "RunTask"))))))), "{}"));
assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString());
List<String> launched = runningTasks(cluster);
assertEquals(1, launched.size());
// The tags checked are the ones the task gets, as a direct RunTask's are.
Response described = ecs("DescribeTasks", Map.of("cluster", cluster, "tasks", launched,
"include", List.of("TAGS")));
described.then().statusCode(200);
assertEquals(List.of(Map.of("key", "team", "value", "data")), described.jsonPath().getList("tasks[0].tags"),
described.asString());
}
/**
* A task that sends tags and propagates its task definition's is checked for the tags it sends alone, as a direct
* RunTask is: {@code aws:TagKeys} names only those, so a policy allowing no other key holds. The task carries
* both, the request's value winning on a key in both, as a direct RunTask's does.
*/
@Test
void aRunTaskPropagatingItsDefinitionsTagsIsCheckedForItsOwnAndCarriesBoth() throws Exception {
String family = "sfn-jobs-" + UUID.randomUUID();
ecs("RegisterTaskDefinition", Map.of("family", family, "containerDefinitions",
List.of(Map.of("name", "runner", "image", "floci-test/runner:latest", "memory", 128)),
"tags", List.of(Map.of("key", "owner", "value", "platform"), Map.of("key", "team", "value", "definition"))))
.then().statusCode(200);
cleanup.register(() -> {
ecs("DeregisterTaskDefinition", Map.of("taskDefinition", family + ":1")).then().statusCode(200);
ecs("DeleteTaskDefinitions", Map.of("taskDefinitions", List.of(family + ":1"))).then().statusCode(200);
});
String cluster = ecsCluster();
Map<String, Object> task = task("ecs:runTask", Map.of("Cluster", cluster, "TaskDefinition", family,
"PropagateTags", "TASK_DEFINITION", "Tags", List.of(Map.of("Key", "team", "Value", "data"))));
Map<String, Object> onlyTeam = Map.of("ForAllValues:StringEquals", Map.of("aws:TagKeys", List.of("team")),
"StringEquals", Map.of("aws:RequestTag/team", "data"));
Map<String, Object> runTask = Map.of("Effect", "Allow", "Action", List.of("ecs:RunTask"),
"Resource", List.of(taskDefinitionArn(family, 1)), "Condition", onlyTeam);
Response refused = terminal(start(machine(task, role(STATES_TRUST, policy(List.of(runTask)))), "{}"));
assertFailed(refused, "ECS.AccessDeniedException");
assertTrue(refused.jsonPath().getString("cause").contains("ecs:TagResource"), refused.asString());
assertEquals(List.of(), runningTasks(cluster));
Response allowed = terminal(start(machine(task, role(STATES_TRUST, policy(List.of(runTask,
Map.of("Effect", "Allow", "Action", List.of("ecs:TagResource"), "Resource", List.of(ANY_RESOURCE),
"Condition", onlyTeam))))), "{}"));
assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString());
List<String> launched = runningTasks(cluster);
assertEquals(1, launched.size());
Response described = ecs("DescribeTasks", Map.of("cluster", cluster, "tasks", launched,
"include", List.of("TAGS")));
described.then().statusCode(200);
Map<String, String> tags = new LinkedHashMap<>();
for (Map<String, String> tag : described.jsonPath().<Map<String, String>>getList("tasks[0].tags")) {
tags.put(tag.get("key"), tag.get("value"));
}
assertEquals(Map.of("owner", "platform", "team", "data"), tags, described.asString());
}
/**
* Tags a cluster is created with need {@code elasticmapreduce:AddTags}, as a direct {@code RunJobFlow} does, and
* {@code RunJobFlow} itself is checked with them: a role allowed {@code RunJobFlow} alone is refused and creates
* nothing.
*/
@Test
void tagsAClusterIsCreatedWithNeedAddTags() throws Exception {
Target untagged = createClusterTarget();
Map<String, Object> arguments = new LinkedHashMap<>(untagged.arguments());
arguments.put("Tags", List.of(Map.of("Key", "team", "Value", "data")));
Target target = new Target(untagged.integration(), untagged.error(), untagged.resourceArn(), arguments,
untagged.reached(), untagged.notReached(), untagged.actions());
Response refused = terminal(start(machine(jsonPathTask(target, null), role(STATES_TRUST, target.grant())), "{}"));
assertFailed(refused, target.error());
assertTrue(refused.jsonPath().getString("cause").contains("elasticmapreduce:AddTags"), refused.asString());
target.notReached().check();
Response created = terminal(start(machine(jsonPathTask(target, null), role(STATES_TRUST, policy(List.of(
Map.of("Effect", "Allow", "Action", List.of("elasticmapreduce:RunJobFlow"),
"Resource", List.of(ANY_RESOURCE),
"Condition", Map.of("StringEquals", Map.of("aws:RequestTag/team", "data"))),
Map.of("Effect", "Allow", "Action", List.of("elasticmapreduce:AddTags"),
"Resource", List.of(ANY_RESOURCE)))))), "{}"));
assertEquals("SUCCEEDED", created.jsonPath().getString("status"), created.asString());
target.reached().check();
// The tags checked are the ones the cluster gets, as a direct RunJobFlow's are.
JsonNode cluster = describeCluster(clusterIdsNamed(arguments.get("Name").toString()).getFirst());
assertEquals(MAPPER.valueToTree(List.of(Map.of("Key", "team", "Value", "data"))), cluster.path("Tags"),
cluster.toString());
}
/**
* Tags an application is created with need {@code emr-serverless:TagResource} on the application it makes, as a
* direct {@code CreateApplication} does, and the create itself is checked with them.
@@ -20,6 +20,7 @@ import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.node.ObjectNode;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -829,6 +830,143 @@ class TaskPermissionsTest {
.orElseThrow().permissions());
}
private static final Map<String, List<String>> TAGGED =
Map.of("aws:RequestTag/team", List.of("data"), "aws:TagKeys", List.of("team"));
/** {@link #TAGGED} with the create action a tagging action that takes {@code <namespace>:CreateAction} is given. */
private static Map<String, List<String>> tagged(String namespace, String operation) {
Map<String, List<String>> context = new LinkedHashMap<>(TAGGED);
context.put(namespace + ":CreateAction", List.of(operation));
return context;
}
/**
* The tags a RunTask sends need {@code ecs:TagResource}, with the call that tags as {@code ecs:CreateAction}, on
* what the request-resources table gives the call, and RunTask itself is checked with them, as a direct RunTask is.
*/
@ParameterizedTest
@ValueSource(strings = {"ecs:runTask", "ecs:runTask.sync"})
void tagsARunTaskSendsNeedTagResource(String tail) throws Exception {
assertEquals(List.of(new Permission("ecs:RunTask", TASK_DEFINITION, TAGGED),
new Permission("iam:PassRole", TASK_ROLE, TO_ECS_TASKS),
new Permission("iam:PassRole", EXECUTION_ROLE, TO_ECS_TASKS),
new Permission("ecs:TagResource", TASK_DEFINITION, tagged("ecs", "RunTask"))),
TaskPermissions.of(integration(tail),
json("{\"TaskDefinition\":\"orders\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"data\"}]}"),
machine("aws"), null, ecs(), false, new TaskPermissions.ControlServices(null, null, null, null, null),
roles()).orElseThrow().permissions());
}
/**
* Propagating the task definition's tags adds nothing to check: the tags a RunTask is authorized for are the ones
* it sends, as a direct RunTask's are, and the definition's were authorized when they were put on it.
*/
@Test
void propagatingTheDefinitionsTagsChecksOnlyTheTagsSent() throws Exception {
String tagged = "{\"TaskDefinition\":\"orders\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"data\"}]";
assertEquals(TaskPermissions.of(integration("ecs:runTask"), json(tagged + "}"), machine("aws"), null, ecs(),
false, new TaskPermissions.ControlServices(null, null, null, null, null), roles()).orElseThrow(),
TaskPermissions.of(integration("ecs:runTask"),
json(tagged + ",\"PropagateTags\":\"TASK_DEFINITION\"}"), machine("aws"), null, ecs(), false,
new TaskPermissions.ControlServices(null, null, null, null, null), roles()).orElseThrow());
}
/** A RunTask ECS answers needs nothing, whatever tags it sends. */
@Test
void aRunTaskNamingNoDefinitionNeedsNoTagResource() throws Exception {
assertEquals(List.of(), TaskPermissions.of(integration("ecs:runTask"),
json("{\"Tags\":[{\"Key\":\"team\",\"Value\":\"data\"}]}"), machine("aws"), null, ecs(), false,
new TaskPermissions.ControlServices(null, null, null, null, null), roles()).orElseThrow().permissions());
}
/**
* The tags a cluster is created with need {@code elasticmapreduce:AddTags}, which takes no create action, on any
* resource as {@code RunJobFlow} acts on none, and {@code RunJobFlow} itself is checked with them.
*/
@ParameterizedTest
@ValueSource(strings = {"elasticmapreduce:createCluster", "elasticmapreduce:createCluster.sync"})
void tagsAClusterIsCreatedWithNeedAddTags(String tail) throws Exception {
assertEquals(List.of(new Permission("elasticmapreduce:RunJobFlow", "*", TAGGED),
new Permission("elasticmapreduce:AddTags", "*", TAGGED)),
TaskPermissions.of(integration(tail),
json("{\"Name\":\"c\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"data\"}]}"),
machine("aws")).orElseThrow().permissions());
}
/**
* The tags a stack or stack set operation sends need {@code cloudformation:TagResource}, with the operation as
* {@code cloudformation:CreateAction}, on the stack or stack set it acts on, or on the one it makes: the change set
* of a CreateChangeSet, and the stack of a CreateStack, its id open, as the request-resources table marks that stack
* made. The operation itself is checked with them, as the same request made directly is.
*/
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"createStack|{\"StackName\":\"s\"}|stack/s/id|stack/s/*",
"updateStack|{\"StackName\":\"s\"}|stack/s/id|stack/s/id",
"createChangeSet|{\"StackName\":\"new\",\"ChangeSetName\":\"c\"}|stack/new/*|changeSet/c/*",
"updateStackSet|{\"StackSetName\":\"ss\"}|stackset/ss:id|stackset/ss:id"})
void tagsAStackOperationSendsNeedTagResource(String api, String request, String resource, String taggedResource)
throws Exception {
String operation = AslExecutor.capitalizeFirst(api);
String arn = "arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":" + resource;
String taggedArn = "arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":" + taggedResource;
ObjectNode tagged = (ObjectNode) json(request);
tagged.putArray("Tags").addObject().put("Key", "team").put("Value", "data");
List<Permission> permissions = control("aws-sdk:cloudformation:" + api, tagged.toString(), stacks(), null, null,
false).permissions();
assertEquals(new Permission("cloudformation:" + operation, arn, TAGGED), permissions.getFirst());
assertEquals(new Permission("cloudformation:TagResource", taggedArn, tagged("cloudformation", operation)),
permissions.getLast());
assertTrue(permissions.stream().noneMatch(permission -> permission.conditionKeys().isEmpty()
&& permission.action().equals("cloudformation:" + operation)), permissions.toString());
}
/** A stack set created with tags tags the stack set it makes. */
@Test
void tagsAStackSetIsCreatedWithNeedTagResourceOnTheStackSet() throws Exception {
List<Permission> permissions = control("aws-sdk:cloudformation:createStackSet",
"{\"StackSetName\":\"n\",\"PermissionModel\":\"SERVICE_MANAGED\","
+ "\"Tags\":[{\"Key\":\"team\",\"Value\":\"data\"}]}").permissions();
assertEquals(List.of(new Permission("cloudformation:CreateStackSet", "*", TAGGED),
new Permission("cloudformation:TagResource",
"arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":stackset/n:*",
tagged("cloudformation", "CreateStackSet"))), permissions);
}
/** A stack operation sending no tags needs no tagging action. */
@ParameterizedTest
@ValueSource(strings = {"createStack", "updateStack", "createChangeSet"})
void aStackOperationSendingNoTagsNeedsNoTagResource(String api) throws Exception {
assertTrue(control("aws-sdk:cloudformation:" + api, "{\"StackName\":\"s\",\"Tags\":[]}", stacks(), null,
null, false).permissions().stream()
.noneMatch(permission -> permission.action().equals("cloudformation:TagResource")));
}
/**
* The tags a CreateTable sends need {@code dynamodb:TagResource} on the table, as a direct CreateTable's do, and
* CreateTable itself is checked with them beside its DynamoDB condition keys; without tags it needs nothing more.
*/
@Test
void tagsACreateTableSendsNeedTagResource() throws Exception {
String table = "arn:aws:dynamodb:eu-west-1:" + ACCOUNT + ":table/orders";
List<Permission> permissions = TaskPermissions.of(integration("aws-sdk:dynamodb:createTable"),
json("{\"TableName\":\"orders\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"data\"}]}"),
machine("aws")).orElseThrow().permissions();
assertEquals(2, permissions.size(), permissions.toString());
assertEquals("dynamodb:CreateTable", permissions.getFirst().action());
assertEquals(table, permissions.getFirst().resourceArn());
assertTrue(permissions.getFirst().conditionKeys().entrySet().containsAll(TAGGED.entrySet()),
permissions.toString());
assertEquals(new Permission("dynamodb:TagResource", table, TAGGED), permissions.getLast());
assertEquals(List.of("dynamodb:CreateTable"), TaskPermissions.of(integration("aws-sdk:dynamodb:createTable"),
json("{\"TableName\":\"orders\"}"), machine("aws")).orElseThrow().permissions().stream()
.map(Permission::action).toList());
}
/** IAM's role {@code service}, under a path, and the profile holding {@code cluster}; ECS's roles of {@code orders}. */
private static TaskPermissions.RequestLookups roles() {
IamService iam = mock(IamService.class);