feat(stepfunctions): evaluate the execution role on ECS, EMR and EMR Serverless tasks (#7723)

Under IAM enforcement, these tasks are now authorized as the execution role, or as the Credentials role a state names. ECS runTask, in all its forms, is checked on the task definition revision it would run, so a family and the revision it stands for are the same resource. The ECS SDK tasks are checked on the service ECS would act on or describe, and listServices on any resource. Each EMR and EMR Serverless API is checked on its cluster, application or job run under its IAM action, and a ByName API needs the list it makes as well as the modify. createCluster and createApplication have no resource type, so they are checked on any resource.

A .sync task needs its starting call alone, so a job cannot fail mid-wait for lack of a Describe permission. A request naming nothing it can reach is left to its service, and a form an integration does not serve stays unsupported. With enforcement off nothing changes.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-11-14 09:40:33 -04:00
1 parent c5e7c3d84e
commit 6f928e6062
9 files changed
+1492 -16

No files matched your search

@@ -6161,6 +6161,11 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
return td;
}
/** The ARN of the definition {@code ref} names, the revision a task started from it runs. Reads only. */
public Optional<String> taskDefinitionArn(String ref, String region) {
return Optional.ofNullable(findTaskDefinition(ref, region)).map(TaskDefinition::getTaskDefinitionArn);
}
/** 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) {
@@ -6247,6 +6252,31 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
.findFirst().orElse(null);
}
/**
* The ARN of the service {@code updateService} would act on, found the way it finds it: by the last segment of
* the reference within the cluster the request names. Reads only, so it creates no default cluster.
*/
public Optional<String> updatedServiceArn(String clusterRef, String serviceRef, String region) {
return existingClusterName(clusterRef, region)
.map(cluster -> services.get(serviceKey(region, cluster, extractServiceName(serviceRef))))
.map(EcsServiceModel::getServiceArn);
}
/** The ARN of the service {@code describeServices} would answer for the reference. Reads only. */
public Optional<String> describedServiceArn(String clusterRef, String serviceRef, String region) {
return existingClusterName(clusterRef, region)
.map(cluster -> resolveService(cluster, serviceRef, region))
.map(EcsServiceModel::getServiceArn);
}
/** The name of the cluster {@code resolveClusterOrDefault} would answer with, without creating the default. */
private Optional<String> existingClusterName(String clusterRef, String region) {
if (clusterRef == null || clusterRef.isBlank() || DEFAULT_CLUSTER.equals(clusterRef)) {
return Optional.of(DEFAULT_CLUSTER);
}
return Optional.ofNullable(resolveCluster(clusterRef, region)).map(EcsCluster::getClusterName);
}
private EcsServiceModel resolveServiceOrThrow(String clusterName, String serviceId, String region) {
EcsServiceModel svc = resolveService(clusterName, serviceId, region);
if (svc == null) {
@@ -1258,9 +1258,11 @@ public class AslExecutor {
}
/** Integrations {@link TaskPermissions} does not map stay unchecked, Lambda and API Gateway check their own. */
private void authorizeTask(StatesIntegration integration, JsonNode input, StateMachine sm, JsonNode credentials) {
private void authorizeTask(StatesIntegration integration, JsonNode input, StateMachine sm, JsonNode credentials,
String taskToken) {
Optional<TaskPermissions> required = TaskPermissions.of(integration, input, sm,
redshiftDataHandler == null ? null : redshiftDataHandler.storedResourceArns());
redshiftDataHandler == null ? null : redshiftDataHandler.storedResourceArns(), ecsService,
taskToken != null);
if (required.isEmpty()) {
return;
}
@@ -1455,7 +1457,7 @@ public class AslExecutor {
}
if (iamEnforcementEnabled()) {
authorizeTask(integration, input, sm, credentials);
authorizeTask(integration, input, sm, credentials, taskToken);
}
if (integration.is("apigateway", "invoke") && integration.suffix().isEmpty()) {
@@ -80,9 +80,15 @@ public class EmrServerlessTaskInvoker {
private record Wait(Set<String> done, Set<String> deadEnds) {}
/** Whether {@link #start} takes the integration, as one of the six APIs itself or its {@code .sync}. */
static boolean serves(StatesIntegration integration) {
return WAITS.containsKey(integration.api())
&& (integration.suffix().isEmpty() || ".sync".equals(integration.suffix()));
}
Job start(StatesIntegration integration, JsonNode input, String region) {
String api = integration.api();
if (!WAITS.containsKey(api) || !integration.suffix().isEmpty() && !".sync".equals(integration.suffix())) {
if (!serves(integration)) {
throw unsupported(integration);
}
JsonNode request = input != null && input.isObject() ? input : objectMapper.createObjectNode();
@@ -274,7 +280,7 @@ public class EmrServerlessTaskInvoker {
}
/** The first of {@code node}'s fields named {@code name} in any case, or a missing node. */
private static JsonNode field(JsonNode node, String name) {
static JsonNode field(JsonNode node, String name) {
for (Map.Entry<String, JsonNode> field : node.properties()) {
if (field.getKey().equalsIgnoreCase(name)) {
return field.getValue();
@@ -58,10 +58,16 @@ public class EmrTaskInvoker {
*/
record Job(String api, String clusterId, String stepId, ObjectNode response) {}
/** Whether {@link #start} takes the integration, as a {@code .sync} of an API that waits or the API itself. */
static boolean serves(StatesIntegration integration) {
String api = integration.api();
return APIS.contains(api) && (integration.suffix().isEmpty()
|| ".sync".equals(integration.suffix()) && SYNC_APIS.contains(api));
}
Job start(StatesIntegration integration, JsonNode input, String region) {
String api = integration.api();
if (!APIS.contains(api)
|| !integration.suffix().isEmpty() && !(".sync".equals(integration.suffix()) && SYNC_APIS.contains(api))) {
if (!serves(integration)) {
throw unsupported(integration);
}
JsonNode request = input != null && input.isObject() ? input : objectMapper.createObjectNode();
@@ -2,12 +2,14 @@ package io.floci.aws.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RequestResources;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.services.dynamodb.DynamoDbPartiQLParser;
import io.floci.aws.services.dynamodb.DynamoDbTableNames;
import io.floci.aws.services.ecs.EcsService;
import io.floci.aws.services.eventbridge.EventBridgeService;
import io.floci.aws.services.iam.IamAuthorizedActions;
import io.floci.aws.services.iam.ResourceArnBuilder;
@@ -46,9 +48,25 @@ record TaskPermissions(String deniedError, List<Permission> permissions) {
private static final String DYNAMODB_SDK_PREFIX = "DynamoDb.";
private static final String REDSHIFT_DATA_PREFIX = "RedshiftData.";
private static final String RDS_DATA_PREFIX = "RdsData.";
private static final String ECS_OPTIMIZED_PREFIX = "ECS.";
private static final String ECS_SDK_PREFIX = "Ecs.";
private static final String EMR_PREFIX = "EMR.";
private static final String EMR_SERVERLESS_PREFIX = "EmrServerless.";
private static final Set<String> DYNAMODB_OPTIMIZED =
Set.of("putItem", "getItem", "deleteItem", "updateItem", "scan");
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* The EMR calls each API makes, in order: a ByName API first lists the cluster's members to find the id, as the
* CDK's policy for it grants.
*/
private static final Map<String, List<String>> EMR_CALLS = Map.of(
"createCluster", List.of("RunJobFlow"),
"setClusterTerminationProtection", List.of("SetTerminationProtection"),
"terminateCluster", List.of("TerminateJobFlows"),
"addStep", List.of("AddJobFlowSteps"),
"cancelStep", List.of("CancelSteps"),
"modifyInstanceFleetByName", List.of("ListInstanceFleets", "ModifyInstanceFleet"),
"modifyInstanceGroupByName", List.of("ListInstanceGroups", "ModifyInstanceGroups"));
/** The permissions of a mapped integration, or nothing for one that is not checked. */
static Optional<TaskPermissions> of(StatesIntegration integration, JsonNode input, StateMachine machine) {
@@ -63,6 +81,35 @@ record TaskPermissions(String deniedError, List<Permission> permissions) {
*/
static Optional<TaskPermissions> of(StatesIntegration integration, JsonNode input, StateMachine machine,
StoredResourceArns redshiftData) {
return of(integration, input, machine, redshiftData, null, false);
}
/**
* The permissions of a mapped integration, or nothing for one that is not checked.
*
* @param redshiftData finds the workgroup or the session target a Data API request names; without it a
* workgroup is any workgroup and a session names nothing
* @param ecs finds the task definition revision or the service a request reaches, reading only; without
* it such a request names nothing
* @param callback whether the state's resource ended in {@code .waitForTaskToken}, which {@code integration}
* no longer shows: EMR and EMR Serverless have no such form, so theirs stays unsupported
*/
static Optional<TaskPermissions> of(StatesIntegration integration, JsonNode input, StateMachine machine,
StoredResourceArns redshiftData, EcsService ecs, boolean callback) {
if (integration.isAnySuffix("ecs", "runTask")
&& (integration.suffix().isEmpty() || ".sync".equals(integration.suffix()))) {
return Optional.of(ecsRunTask(input, machine, ecs));
}
if (integration.isSdkService("ecs") && SdkManagementTaskInvoker.supports(integration)) {
return Optional.of(ecsSdk(integration.api(), input, machine, ecs));
}
if (!callback && integration.isOptimizedService("elasticmapreduce") && EmrTaskInvoker.serves(integration)) {
return Optional.of(emr(integration.api(), input, machine));
}
if (!callback && integration.isOptimizedService("emr-serverless")
&& EmrServerlessTaskInvoker.serves(integration)) {
return Optional.of(emrServerless(integration.api(), input, machine));
}
if (integration.is("sqs", "sendMessage")) {
return Optional.of(sqsSendMessage("SQS.", input, machine));
}
@@ -277,4 +324,122 @@ record TaskPermissions(String deniedError, List<Permission> permissions) {
return accessDenied(RDS_DATA_PREFIX, AwsArnUtils.isArn(secretArn)
? List.of(execute, new Permission("secretsmanager:GetSecretValue", secretArn)) : List.of(execute));
}
/**
* {@code ecs:RunTask} on the revision the task would run, as {@code EcsService.runTask} resolves the reference, so
* a family and the revision it stands for are the same resource. A definition ECS does not have names nothing, so
* ECS answers it.
*/
private static TaskPermissions ecsRunTask(JsonNode input, StateMachine machine, EcsService ecs) {
String taskDefinition = input.path("TaskDefinition").asText(null);
if (ecs == null || taskDefinition == null) {
return accessDenied(ECS_OPTIMIZED_PREFIX, List.of());
}
return accessDenied(ECS_OPTIMIZED_PREFIX, ecs.taskDefinitionArn(taskDefinition, regionOf(machine))
.map(arn -> List.of(new Permission("ecs:RunTask", arn))).orElse(List.of()));
}
/**
* The ECS action on the service each request reaches, read as the handler reads its members, either casing being
* recased for it, and resolved as the handler resolves them: a service ECS does not have names nothing, so ECS
* answers it. {@code ListServices} has no resource type in the service reference.
*/
private static TaskPermissions ecsSdk(String api, JsonNode input, StateMachine machine, EcsService ecs) {
String action = "ecs:" + AslExecutor.capitalizeFirst(api);
if ("listServices".equals(api)) {
return accessDenied(ECS_SDK_PREFIX, List.of(new Permission(action, ANY_RESOURCE)));
}
JsonNode request = AslExecutor.recaseKeys(MAPPER, input, false);
if (ecs == null || !request.isObject()) {
return accessDenied(ECS_SDK_PREFIX, List.of());
}
String cluster = request.has("cluster") ? request.path("cluster").asText() : null;
String region = regionOf(machine);
Set<String> services = new LinkedHashSet<>();
if ("updateService".equals(api)) {
ecs.updatedServiceArn(cluster, request.path("service").asText(), region).ifPresent(services::add);
} else if (request.path("services").isArray()) {
for (JsonNode service : request.path("services")) {
ecs.describedServiceArn(cluster, service.asText(), region).ifPresent(services::add);
}
}
return accessDenied(ECS_SDK_PREFIX,
services.stream().map(service -> new Permission(action, service)).toList());
}
/**
* 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. A request naming no cluster
* is refused by the integration.
*/
private static TaskPermissions emr(String api, JsonNode input, StateMachine machine) {
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));
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));
}
}
return accessDenied(EMR_PREFIX, permissions);
}
/** The members of the EMR request the integration sends that name the cluster. */
private static JsonNode emrRequest(String operation, String clusterId) {
return switch (operation) {
case "AddJobFlowSteps" -> MAPPER.createObjectNode().put("JobFlowId", clusterId);
case "SetTerminationProtection", "TerminateJobFlows" -> {
ObjectNode request = MAPPER.createObjectNode();
request.putArray("JobFlowIds").add(clusterId);
yield request;
}
default -> MAPPER.createObjectNode().put("ClusterId", clusterId);
};
}
/**
* The action of the API's own name on the application or job run it names, the ids read in either case as the
* integration reads them. A request missing one is refused by the integration. {@code CreateApplication} has no
* resource type in the service reference.
*/
private static TaskPermissions emrServerless(String api, JsonNode input, StateMachine machine) {
String action = "emr-serverless:" + AslExecutor.capitalizeFirst(api);
if ("createApplication".equals(api)) {
return accessDenied(EMR_SERVERLESS_PREFIX, List.of(new Permission(action, ANY_RESOURCE)));
}
String application = text(EmrServerlessTaskInvoker.field(input, "ApplicationId"));
String jobRun = text(EmrServerlessTaskInvoker.field(input, "JobRunId"));
if (application == null || "cancelJobRun".equals(api) && jobRun == null) {
return accessDenied(EMR_SERVERLESS_PREFIX, List.of());
}
String resource = "/applications/" + application + ("cancelJobRun".equals(api) ? "/jobruns/" + jobRun : "");
return accessDenied(EMR_SERVERLESS_PREFIX,
List.of(new Permission(action, arn(machine, "emr-serverless", resource))));
}
/** The ARN of a resource of the state machine's partition, Region and account. */
private static String arn(StateMachine machine, String service, String resource) {
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
return new AwsArnUtils.Arn(owner.partition(), service, owner.region(), owner.accountId(), resource).toString();
}
private static String regionOf(StateMachine machine) {
return AwsArnUtils.parse(machine.getStateMachineArn()).region();
}
/** The value when it is the non-blank string an id has to be, as the integrations require of one. */
private static String text(JsonNode value) {
return value.isTextual() && !value.asText().isBlank() ? value.asText() : null;
}
}