diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md index fbc0ed2e2d..011bfe6ae5 100644 --- a/docs/services/step-functions.md +++ b/docs/services/step-functions.md @@ -90,11 +90,11 @@ With IAM enforcement enabled, the existing task authorizer checks the execution permission to assume the task role, its trust policy, and the task role's permission to start the child. Account routing also works with enforcement disabled. The `.sync` polling and cancellation paths retain the task account; their additional IAM permissions -are not evaluated. Lambda, API Gateway, SQS, SNS, EventBridge, DynamoDB, S3 `putObject`, RDS Data and -Redshift Data tasks evaluate `Credentials` themselves +are not evaluated. Lambda, API Gateway, SQS, SNS, EventBridge, DynamoDB, S3 `putObject`, RDS Data, +Redshift Data, ECS, EMR and EMR Serverless tasks evaluate `Credentials` themselves ([Lambda](#lambda-tasks-under-iam-enforcement), [messaging](#messaging-tasks-under-iam-enforcement), -[data](#data-tasks-under-iam-enforcement)); other integrations retain their existing credential -handling. +[data](#data-tasks-under-iam-enforcement), [jobs](#job-tasks-under-iam-enforcement)); other +integrations retain their existing credential handling. A foreign state-machine ARN without task credentials grants no account access. A missing or mismatched task role fails with `States.TaskFailed`. A target account @@ -708,8 +708,63 @@ AWS. Apart from `dynamodb:EnclosingOperation`, only global condition keys are av policies: `dynamodb:LeadingKeys`, `dynamodb:Attributes` and the like are absent. Global tables are not treated apart. With enforcement off nothing here is evaluated. -Integrations other than these, the messaging tasks, Lambda, API Gateway and nested executions are not -evaluated yet: they run in the state machine's account whatever the execution role's policies say. +## Job tasks under IAM enforcement + +These tasks are evaluated with [IAM enforcement](iam.md#resource-based-policies) on, in the same steps +and with the same role errors as [messaging tasks](#messaging-tasks-under-iam-enforcement). Each action +and resource type comes from the Service Authorization Reference: + +| Resource | Action | Resource evaluated | Refused with | +|---|---|---|---| +| `arn:aws:states:::ecs:runTask`, with `.sync` or `.waitForTaskToken` | `ecs:RunTask` | The task definition revision the task would run | `ECS.AccessDeniedException` | +| `arn:aws:states:::aws-sdk:ecs:updateService` | `ecs:UpdateService` | The service it acts on | `Ecs.AccessDeniedException` | +| `arn:aws:states:::aws-sdk:ecs:describeServices` | `ecs:DescribeServices` | Each service it answers for | `Ecs.AccessDeniedException` | +| `arn:aws:states:::aws-sdk:ecs:listServices` | `ecs:ListServices` | `*` | `Ecs.AccessDeniedException` | +| `arn:aws:states:::elasticmapreduce:createCluster`, `.sync` | `elasticmapreduce:RunJobFlow` | `*` | `EMR.AccessDeniedException` | +| `arn:aws:states:::elasticmapreduce:setClusterTerminationProtection` | `elasticmapreduce:SetTerminationProtection` | `cluster/` | `EMR.AccessDeniedException` | +| `arn:aws:states:::elasticmapreduce:terminateCluster`, `.sync` | `elasticmapreduce:TerminateJobFlows` | `cluster/` | `EMR.AccessDeniedException` | +| `arn:aws:states:::elasticmapreduce:addStep`, `.sync` | `elasticmapreduce:AddJobFlowSteps` | `cluster/` | `EMR.AccessDeniedException` | +| `arn:aws:states:::elasticmapreduce:cancelStep` | `elasticmapreduce:CancelSteps` | `cluster/` | `EMR.AccessDeniedException` | +| `arn:aws:states:::elasticmapreduce:modifyInstanceFleetByName` | `elasticmapreduce:ListInstanceFleets`, `ModifyInstanceFleet` | `cluster/` | `EMR.AccessDeniedException` | +| `arn:aws:states:::elasticmapreduce:modifyInstanceGroupByName` | `elasticmapreduce:ListInstanceGroups`, `ModifyInstanceGroups` | `cluster/` | `EMR.AccessDeniedException` | +| `arn:aws:states:::emr-serverless:createApplication`, `.sync` | `emr-serverless:CreateApplication` | `*` | `EmrServerless.AccessDeniedException` | +| `arn:aws:states:::emr-serverless:startApplication`, `stopApplication`, `deleteApplication`, `.sync` | `emr-serverless:StartApplication` and so on | `/applications/` | `EmrServerless.AccessDeniedException` | +| `arn:aws:states:::emr-serverless:startJobRun`, `.sync` | `emr-serverless:StartJobRun` | `/applications/` | `EmrServerless.AccessDeniedException` | +| `arn:aws:states:::emr-serverless:cancelJobRun`, `.sync` | `emr-serverless:CancelJobRun` | `/applications//jobruns/` | `EmrServerless.AccessDeniedException` | + +A task definition is evaluated as the revision it resolves to, so a bare family, `family:revision` and +the ARN give the same resource: `task-definition/:`. A role allowed only an older +revision is refused a bare family whose latest revision is newer. + +The ECS services are resolved as ECS resolves them. `updateService` acts on the service of that name in +the request's `Cluster`, or in `default` with none, whatever cluster a service ARN in the request +names, and that is the service evaluated. + +A ByName API needs its `List` action as well as its `Modify` one, since it reads the cluster's fleets or +groups to find the id. Nothing documents this for a task: it is inferred from what the integration +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`, `createCluster` or +`startJobRun` pass, nor a tagging action such as `elasticmapreduce:AddTags` for what they tag. + +A request naming nothing it can reach has only the role checks, and its service answers it: no +`TaskDefinition` or one ECS does not have, a service or cluster ECS does not have, no `ClusterId`, no +`ApplicationId`, or a `cancelJobRun` without `JobRunId`. A form an integration does not serve keeps +its answer: `.waitForTaskToken` on EMR and EMR Serverless and `.sync` on an EMR API with no wait are +"Unsupported" whether or not enforcement is on, and so is any API Floci does not have. + +`.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. + +Integrations other than these, the data and messaging tasks, Lambda, API Gateway and nested executions +are not evaluated yet: they run in the state machine's account whatever the execution role's policies +say. ## Task credentials in history @@ -773,10 +828,11 @@ their `UUID` spelling. ECS `listServices` supports the same `MaxResults` and opaque `NextToken` as the direct ECS API. Lambda mapping tasks currently return an unpaginated list; `Marker` and `MaxItems` are rejected with `Lambda.InvalidParameterValueException` -instead of being silently ignored. These six integrations do not evaluate the -state-machine execution role's per-action IAM policies; among the task integrations, Lambda, API +instead of being silently ignored. The three Lambda mapping and Secrets Manager integrations do not +evaluate the state-machine execution role's per-action IAM policies; the three ECS ones +[do](#job-tasks-under-iam-enforcement), and among the task integrations so do Lambda, API Gateway, nested executions, the [messaging tasks](#messaging-tasks-under-iam-enforcement) and the -[data tasks](#data-tasks-under-iam-enforcement) do. Name-based lookups use the +[data tasks](#data-tasks-under-iam-enforcement). Name-based lookups use the execution scope; explicit ARNs retain the underlying service's cross-account lookup behavior. The underlying services' validation still applies. They implement request-response calls, without job-completion polling. diff --git a/src/main/java/io/floci/aws/services/ecs/EcsService.java b/src/main/java/io/floci/aws/services/ecs/EcsService.java index a08315e51a..cb98f92bb3 100644 --- a/src/main/java/io/floci/aws/services/ecs/EcsService.java +++ b/src/main/java/io/floci/aws/services/ecs/EcsService.java @@ -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 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 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 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 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 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) { diff --git a/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java b/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java index a2e47be66c..0504e36b47 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java @@ -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 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()) { diff --git a/src/main/java/io/floci/aws/services/stepfunctions/EmrServerlessTaskInvoker.java b/src/main/java/io/floci/aws/services/stepfunctions/EmrServerlessTaskInvoker.java index 6188162905..f34ec4c361 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/EmrServerlessTaskInvoker.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/EmrServerlessTaskInvoker.java @@ -80,9 +80,15 @@ public class EmrServerlessTaskInvoker { private record Wait(Set done, Set 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 field : node.properties()) { if (field.getKey().equalsIgnoreCase(name)) { return field.getValue(); diff --git a/src/main/java/io/floci/aws/services/stepfunctions/EmrTaskInvoker.java b/src/main/java/io/floci/aws/services/stepfunctions/EmrTaskInvoker.java index 571cff212f..d34293adbc 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/EmrTaskInvoker.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/EmrTaskInvoker.java @@ -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(); diff --git a/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java b/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java index 4ab4376a0a..ab8e86dce1 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java @@ -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 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 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> 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 of(StatesIntegration integration, JsonNode input, StateMachine machine) { @@ -63,6 +81,35 @@ record TaskPermissions(String deniedError, List permissions) { */ static Optional 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 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 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 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 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; + } } diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsJobTaskIamIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsJobTaskIamIntegrationTest.java new file mode 100644 index 0000000000..62d40beb29 --- /dev/null +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsJobTaskIamIntegrationTest.java @@ -0,0 +1,986 @@ +package io.floci.aws.services.stepfunctions; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.floci.aws.testing.StepFunctionsTestClient; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +import org.awaitility.core.ConditionFactory; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.net.URI; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Stream; + +import static io.floci.aws.testing.EnforcementFixtures.auth; +import static io.floci.aws.testing.StepFunctionsTestClient.LAMBDA_TRUST; +import static io.floci.aws.testing.StepFunctionsTestClient.STATES_TRUST; +import static io.floci.aws.testing.StepFunctionsTestClient.trusting; +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * ECS, EMR and EMR Serverless tasks under IAM enforcement. All three run for real in their test defaults, with no + * container behind them (ECS in mock mode, EMR's and EMR Serverless's work simulated), so the tests read what a task + * did from the service itself. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class StepFunctionsJobTaskIamIntegrationTest { + private static final String ACCOUNT = "000000000471"; + private static final String REGION = "us-east-1"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String EMR_SERVERLESS_TRUST = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole", + "Principal":{"Service":"emr-serverless.amazonaws.com"}}]} + """; + private static final String READ_ONLY = allow("*", "sns:ListTopics"); + private static final String ASSUME = allow("*", "sts:AssumeRole"); + private static final String ALLOW_ALL = + allow("*", "ecs:*", "elasticmapreduce:*", "emr-serverless:*", "sts:AssumeRole"); + private static final String ANY_RESOURCE = "*"; + private static final Check NOTHING_TO_READ = () -> { }; + private static final Map GROUPS = Map.of("KeepJobFlowAliveWhenNoSteps", true, "InstanceGroups", + List.of(Map.of("Name", "Primary", "InstanceRole", "MASTER", "InstanceType", "m5.xlarge", "InstanceCount", 1), + Map.of("Name", "Core", "InstanceRole", "CORE", "InstanceType", "m5.xlarge", "InstanceCount", 2))); + private static final Map FLEETS = Map.of("KeepJobFlowAliveWhenNoSteps", true, "InstanceFleets", + List.of(Map.of("Name", "Primary", "InstanceFleetType", "MASTER", "TargetOnDemandCapacity", 1, + "InstanceTypeConfigs", List.of(Map.of("InstanceType", "m5.xlarge"))), + Map.of("Name", "Core", "InstanceFleetType", "CORE", "TargetOnDemandCapacity", 2, + "InstanceTypeConfigs", List.of(Map.of("InstanceType", "m5.xlarge"))))); + private static final Map STEP = Map.of("Name", "job", "ActionOnFailure", "CONTINUE", + "HadoopJarStep", Map.of("Jar", "command-runner.jar", "Args", List.of("spark-submit", "s3://bucket/job.py"))); + private static final Map JOB_DRIVER = + Map.of("SparkSubmit", Map.of("EntryPoint", "s3://bucket/jobs/app.py")); + + @TestHTTPResource + URI baseUri; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + /** Every API an integration serves, each with what it reaches. */ + static Stream everyApi() { + return Stream.of("ecs:runTask", "aws-sdk:ecs:updateService", "aws-sdk:ecs:listServices", + "aws-sdk:ecs:describeServices", "elasticmapreduce:createCluster", + "elasticmapreduce:setClusterTerminationProtection", "elasticmapreduce:terminateCluster", + "elasticmapreduce:addStep", "elasticmapreduce:cancelStep", "elasticmapreduce:modifyInstanceFleetByName", + "elasticmapreduce:modifyInstanceGroupByName", "emr-serverless:createApplication", + "emr-serverless:startApplication", "emr-serverless:stopApplication", "emr-serverless:deleteApplication", + "emr-serverless:startJobRun", "emr-serverless:cancelJobRun"); + } + + /** One of each integration, for what does not differ between an integration's APIs. */ + static Stream eachIntegration() { + return Stream.of("ecs:runTask", "aws-sdk:ecs:updateService", "elasticmapreduce:addStep", + "emr-serverless:startApplication"); + } + + static Stream eachIntegrationInBothLanguages() { + return eachIntegration().flatMap(integration -> Stream.of(Arguments.of(integration, "jsonpath"), + Arguments.of(integration, "jsonata"))); + } + + @ParameterizedTest + @MethodSource("everyApi") + void anExecutionRoleAllowedTheActionOnTheResourceReachesTheService(String integration) throws Exception { + Target target = target(integration); + + Response completed = terminal(start(machine(jsonPathTask(target, null), role(STATES_TRUST, target.grant())), "{}")); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + target.reached().check(); + } + + @ParameterizedTest + @MethodSource("everyApi") + void anExecutionRoleNotAllowedTheActionIsRefused(String integration) throws Exception { + Target target = target(integration); + + Response completed = terminal(start(machine(jsonPathTask(target, null), role(STATES_TRUST, READ_ONLY)), "{}")); + + assertFailed(completed, target.error()); + String cause = completed.jsonPath().getString("cause"); + assertTrue(cause.contains(target.action()), cause); + assertTrue(cause.contains(target.resourceArn()), cause); + target.notReached().check(); + } + + @ParameterizedTest + @MethodSource("everyApi") + void theActionOnAnotherResourceDoesNotCount(String integration) throws Exception { + Target target = target(integration); + assumeFalse(ANY_RESOURCE.equals(target.resourceArn()), "the service reference gives it no resource"); + String role = role(STATES_TRUST, allow(target.resourceArn() + "-elsewhere", target.actions())); + + assertFailed(terminal(start(machine(jsonPathTask(target, null), role), "{}")), target.error()); + target.notReached().check(); + } + + /** {@code *} is what these are evaluated on: a role allowed them only on some ARN is refused. */ + @ParameterizedTest + @MethodSource("everyApi") + void anActionWithNoResourceTypeNeedsAGrantOnAnyResource(String integration) throws Exception { + Target target = target(integration); + assumeTrue(ANY_RESOURCE.equals(target.resourceArn()), "the service reference gives it a resource"); + String role = role(STATES_TRUST, allow("arn:aws:ecs:" + REGION + ":" + ACCOUNT + ":cluster/x", target.action())); + + assertFailed(terminal(start(machine(jsonPathTask(target, null), role), "{}")), target.error()); + } + + @ParameterizedTest + @MethodSource("eachIntegration") + void anExecutionRoleThatDoesNotTrustStepFunctionsIsRefusedWhateverItsPolicies(String integration) throws Exception { + Target target = target(integration); + String role = role(LAMBDA_TRUST, target.grant()); + + Response completed = terminal(start(machine(jsonPathTask(target, null), role), "{}")); + + assertFailed(completed, "States.Permissions"); + assertTrue(completed.jsonPath().getString("cause").contains(role), completed.asString()); + target.notReached().check(); + } + + @ParameterizedTest + @MethodSource("eachIntegration") + void anExecutionRoleThatDoesNotExistIsRefused(String integration) throws Exception { + Target target = target(integration); + String role = "arn:aws:iam::" + ACCOUNT + ":role/no-such-role-" + UUID.randomUUID(); + + Response completed = terminal(start(machine(jsonPathTask(target, null), role), "{}")); + + assertFailed(completed, "States.Permissions"); + assertTrue(completed.jsonPath().getString("cause").contains(role), completed.asString()); + target.notReached().check(); + } + + @ParameterizedTest + @MethodSource("eachIntegrationInBothLanguages") + void credentialsReachTheServiceAsTheirRoleWithoutTheExecutionRolesPermission(String integration, String form) + throws Exception { + Target target = target(integration); + String executionRole = role(STATES_TRUST, ASSUME); + String taskRole = role(trusting(executionRole), target.grant()); + Map task = "jsonata".equals(form) ? jsonataTask(target, "{% $states.input.role %}") + : jsonPathTask(target, taskRole); + + String execution = start(machine(task, executionRole), MAPPER.writeValueAsString(Map.of("role", taskRole))); + Response completed = terminal(execution); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + target.reached().check(); + assertEquals(taskRole, eventsOfType(execution, "TaskScheduled").getFirst() + .path("taskScheduledEventDetails").path("taskCredentials").path("roleArn").asText()); + } + + @ParameterizedTest + @MethodSource("eachIntegration") + void aRoleTheExecutionRoleCannotAssumeFailsInTheNestedForm(String integration) throws Exception { + Target target = target(integration); + String executionRole = role(STATES_TRUST, target.grant()); + String taskRole = role(STATES_TRUST, target.grant()); + + Response completed = terminal(start(machine(jsonPathTask(target, taskRole), executionRole), "{}")); + + assertFailed(completed, "States.TaskFailed"); + assertTrue(completed.jsonPath().getString("cause").contains("is not authorized to assume"), completed.asString()); + target.notReached().check(); + } + + @ParameterizedTest + @MethodSource("eachIntegration") + void aCredentialsRoleNotAllowedTheActionIsRefusedEvenIfTheExecutionRoleIs(String integration) throws Exception { + Target target = target(integration); + String executionRole = role(STATES_TRUST, ALLOW_ALL); + String taskRole = role(trusting(executionRole), READ_ONLY); + + assertFailed(terminal(start(machine(jsonPathTask(target, taskRole), executionRole), "{}")), target.error()); + target.notReached().check(); + } + + @ParameterizedTest + @MethodSource("eachIntegration") + void aRefusalCanBeRetriedAndCaught(String integration) throws Exception { + Target target = target(integration); + Map task = new LinkedHashMap<>(jsonPathTask(target, null)); + task.put("Retry", List.of(Map.of("ErrorEquals", List.of(target.error()), "IntervalSeconds", 1, + "BackoffRate", 1.0, "MaxAttempts", 1))); + task.put("Catch", List.of(Map.of("ErrorEquals", List.of(target.error()), "Next", "Recovered"))); + String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Send", "States", Map.of("Send", task, + "Recovered", Map.of("Type", "Pass", "End", true)))); + String execution = start(machineWithDefinition(definition, role(STATES_TRUST, READ_ONLY)), "{}"); + + Response completed = terminal(execution); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + assertEquals(2, eventsOfType(execution, "TaskFailed").size()); + assertEquals(target.error(), eventsOfType(execution, "TaskFailed").getLast() + .path("taskFailedEventDetails").path("error").asText()); + } + + /** A family is the revision it would run: the grant on that revision is what counts, however it is named. */ + @ParameterizedTest + @ValueSource(strings = {"family", "revision", "arn"}) + void aTaskDefinitionIsEvaluatedAsTheRevisionItRuns(String form) throws Exception { + String family = family(); + registerRevision(family); + String latest = taskDefinitionArn(family, 2); + String named = switch (form) { + case "family" -> family; + case "revision" -> family + ":2"; + default -> latest; + }; + String cluster = ecsCluster(); + Map task = task("ecs:runTask", Map.of("Cluster", cluster, "TaskDefinition", named)); + + Response allowed = terminal(start(machine(task, role(STATES_TRUST, allow(latest, "ecs:RunTask"))), "{}")); + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + assertEquals(1, runningTasks(cluster).size()); + + Response refused = terminal(start(machine(task, role(STATES_TRUST, + allow(taskDefinitionArn(family, 1), "ecs:RunTask"))), "{}")); + assertFailed(refused, "ECS.AccessDeniedException"); + assertTrue(refused.jsonPath().getString("cause").contains(latest), refused.asString()); + assertEquals(1, runningTasks(cluster).size()); + } + + @Test + void anOlderRevisionNamedOutrightIsThatRevision() throws Exception { + String family = family(); + registerRevision(family); + String cluster = ecsCluster(); + Map task = task("ecs:runTask", Map.of("Cluster", cluster, "TaskDefinition", family + ":1")); + + Response allowed = terminal(start(machine(task, role(STATES_TRUST, + allow(taskDefinitionArn(family, 1), "ecs:RunTask"))), "{}")); + + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + assertEquals(1, runningTasks(cluster).size()); + } + + /** The CDK grants {@code ecs:RunTask} on {@code :*} without its fix's feature flag. */ + @Test + void aGrantOnEveryRevisionOfAFamilyCovers() throws Exception { + String family = family(); + String cluster = ecsCluster(); + Map task = task("ecs:runTask", Map.of("Cluster", cluster, "TaskDefinition", family)); + + Response allowed = terminal(start(machine(task, role(STATES_TRUST, + allow("arn:aws:ecs:" + REGION + ":" + ACCOUNT + ":task-definition/" + family + ":*", "ecs:RunTask"))), "{}")); + + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + } + + @Test + void aTaskDefinitionEcsDoesNotHaveIsLeftToEcs() throws Exception { + Map task = task("ecs:runTask", Map.of("TaskDefinition", "no-such-family-" + UUID.randomUUID())); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")), "ECS.ClientException"); + } + + /** {@code .sync} needs the starting call alone: the wait reads what the task launched with no Describe grant. */ + @Test + void runTaskSyncNeedsOnlyRunTaskAndWaits() throws Exception { + String family = family(); + String cluster = ecsCluster(); + Map task = task("ecs:runTask.sync", Map.of("Cluster", cluster, "TaskDefinition", family)); + String role = role(STATES_TRUST, allow(taskDefinitionArn(family, 1), "ecs:RunTask")); + + String execution = start(machine(task, role), "{}"); + String launched = awaitRunningTask(cluster); + assertEquals("RUNNING", request("DescribeExecution", Map.of("executionArn", execution)) + .jsonPath().getString("status")); + ecs("StopTask", Map.of("cluster", cluster, "task", launched)).then().statusCode(200); + + Response completed = terminal(execution); + assertFalse(String.valueOf(completed.jsonPath().getString("error")).endsWith("AccessDeniedException"), + completed.asString()); + } + + @Test + void runTaskSyncRefusedLaunchesNothing() throws Exception { + String family = family(); + String cluster = ecsCluster(); + Map task = task("ecs:runTask.sync", Map.of("Cluster", cluster, "TaskDefinition", family)); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")), "ECS.AccessDeniedException"); + assertEquals(List.of(), runningTasks(cluster)); + } + + @Test + void runTaskWaitForTaskTokenAllowedLaunchesAndWaits() throws Exception { + String family = family(); + String cluster = ecsCluster(); + Map task = new LinkedHashMap<>(task("ecs:runTask.waitForTaskToken", + Map.of("Cluster", cluster, "TaskDefinition", family, "StartedBy.$", "$$.Task.Token"))); + task.put("TimeoutSeconds", 60); + String role = role(STATES_TRUST, allow(taskDefinitionArn(family, 1), "ecs:RunTask")); + + String execution = start(machine(task, role), "{}"); + String launched = awaitRunningTask(cluster); + Response described = ecs("DescribeTasks", Map.of("cluster", cluster, "tasks", List.of(launched))); + String token = described.jsonPath().getString("tasks[0].startedBy"); + request("SendTaskSuccess", Map.of("taskToken", token, "output", "{\"done\":true}")).then().statusCode(200); + + Response completed = terminal(execution); + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + } + + @Test + void runTaskWaitForTaskTokenRefusedDoesNotWaitAndLaunchesNothing() throws Exception { + String family = family(); + String cluster = ecsCluster(); + Map task = new LinkedHashMap<>(task("ecs:runTask.waitForTaskToken", + Map.of("Cluster", cluster, "TaskDefinition", family, "StartedBy.$", "$$.Task.Token"))); + task.put("TimeoutSeconds", 60); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")), "ECS.AccessDeniedException"); + assertEquals(List.of(), runningTasks(cluster)); + } + + /** {@code .sync} authorizes the starting call: none of these policies holds the read the wait makes. */ + @ParameterizedTest + @CsvSource({"elasticmapreduce:addStep.sync,elasticmapreduce:addStep", + "elasticmapreduce:createCluster.sync,elasticmapreduce:createCluster", + "emr-serverless:startApplication.sync,emr-serverless:startApplication"}) + void aSyncTaskNeedsOnlyItsStartingCall(String resource, String api) throws Exception { + Target target = target(api); + Map task = task(resource, target.arguments()); + + Response completed = terminal(start(machine(task, role(STATES_TRUST, target.grant())), "{}"), 60); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + } + + @ParameterizedTest + @CsvSource({"elasticmapreduce:addStep.sync,elasticmapreduce:addStep,EMR.AccessDeniedException", + "emr-serverless:startApplication.sync,emr-serverless:startApplication,EmrServerless.AccessDeniedException"}) + void aSyncTaskRefusedStartsNothing(String resource, String api, String error) throws Exception { + Target target = target(api); + + assertFailed(terminal(start(machine(task(resource, target.arguments()), role(STATES_TRUST, READ_ONLY)), "{}")), + error); + target.notReached().check(); + } + + /** A ByName API lists the cluster's members to find the id, so either action alone stops it. */ + @ParameterizedTest + @CsvSource({ + "elasticmapreduce:modifyInstanceFleetByName,elasticmapreduce:ListInstanceFleets", + "elasticmapreduce:modifyInstanceFleetByName,elasticmapreduce:ModifyInstanceFleet", + "elasticmapreduce:modifyInstanceGroupByName,elasticmapreduce:ListInstanceGroups", + "elasticmapreduce:modifyInstanceGroupByName,elasticmapreduce:ModifyInstanceGroups"}) + void aByNameApiNeedsBothItsActions(String integration, String alone) throws Exception { + Target target = target(integration); + String role = role(STATES_TRUST, allow(target.resourceArn(), alone)); + + assertFailed(terminal(start(machine(jsonPathTask(target, null), role), "{}")), "EMR.AccessDeniedException"); + target.notReached().check(); + } + + /** The service ARN's own cluster is not what {@code UpdateService} reads: the task acts on the request's. */ + @Test + void updateServiceIsEvaluatedOnTheServiceItActsOn() throws Exception { + String family = family(); + String named = ecsCluster(); + String other = ecsCluster(); + String name = "svc-" + UUID.randomUUID(); + String inNamed = ecsService(named, name, family); + String inOther = ecsService(other, name, family); + Map task = task("aws-sdk:ecs:updateService", + Map.of("Cluster", other, "Service", inNamed, "DesiredCount", 1)); + + Response refused = terminal(start(machine(task, role(STATES_TRUST, allow(inNamed, "ecs:UpdateService"))), "{}")); + assertFailed(refused, "Ecs.AccessDeniedException"); + assertTrue(refused.jsonPath().getString("cause").contains(inOther), refused.asString()); + assertEquals(0, desiredCount(other, name)); + + Response allowed = terminal(start(machine(task, role(STATES_TRUST, allow(inOther, "ecs:UpdateService"))), "{}")); + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + assertEquals(1, desiredCount(other, name)); + assertEquals(0, desiredCount(named, name)); + } + + @Test + void describeServicesNeedsTheActionOnEveryService() throws Exception { + String family = family(); + String cluster = ecsCluster(); + String first = ecsService(cluster, "first", family); + String second = ecsService(cluster, "second", family); + Map task = task("aws-sdk:ecs:describeServices", + Map.of("Cluster", cluster, "Services", List.of("first", second))); + + Response refused = terminal(start(machine(task, role(STATES_TRUST, allow(first, "ecs:DescribeServices"))), "{}")); + assertFailed(refused, "Ecs.AccessDeniedException"); + assertTrue(refused.jsonPath().getString("cause").contains(second), refused.asString()); + + Response allowed = terminal(start(machine(task, role(STATES_TRUST, + allow(serviceArn(cluster, "*"), "ecs:DescribeServices"))), "{}")); + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + assertEquals(2, MAPPER.readTree(allowed.jsonPath().getString("output")).path("Services").size()); + } + + /** What a service does not have reaches nothing: a role allowed nothing gets the service's own answer. */ + @Test + void aServiceEcsDoesNotHaveIsLeftToEcs() throws Exception { + String cluster = ecsCluster(); + String role = role(STATES_TRUST, READ_ONLY); + + assertFailed(terminal(start(machine(task("aws-sdk:ecs:updateService", + Map.of("Cluster", cluster, "Service", "no-such-service")), role), "{}")), "Ecs.ServiceNotFoundException"); + assertFailed(terminal(start(machine(task("aws-sdk:ecs:updateService", + Map.of("Cluster", "no-such-cluster", "Service", "any")), role), "{}")), "Ecs.ClusterNotFoundException"); + Response described = terminal(start(machine(task("aws-sdk:ecs:describeServices", + Map.of("Cluster", cluster, "Services", List.of("no-such-service"))), role), "{}")); + assertEquals("SUCCEEDED", described.jsonPath().getString("status"), described.asString()); + assertEquals("MISSING", MAPPER.readTree(described.jsonPath().getString("output")) + .path("Failures").get(0).path("Reason").asText()); + } + + /** A form or an API the integration does not serve keeps its existing answer, whatever the role may do. */ + @ParameterizedTest + @ValueSource(strings = {"elasticmapreduce:createCluster.waitForTaskToken", + "elasticmapreduce:addStep.waitForTaskToken", "elasticmapreduce:cancelStep.sync", + "elasticmapreduce:listClusters", "emr-serverless:createApplication.waitForTaskToken", + "emr-serverless:startJobRun.sync:2", "emr-serverless:listApplications", "aws-sdk:ecs:runTask", + "aws-sdk:ecs:updateService.sync", "ecs:describeTasks"}) + void aFormOrAnApiNotServedStaysUnsupported(String resource) throws Exception { + Map task = new LinkedHashMap<>(task(resource, + Map.of("ClusterId", "j-any", "ApplicationId", "00any", "Service", "any", "TaskDefinition", "any"))); + task.put("TimeoutSeconds", 60); + + Response completed = terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")); + + assertFailed(completed, "States.TaskFailed"); + assertTrue(completed.jsonPath().getString("cause").contains("Unsupported"), completed.asString()); + } + + /** The integration's own validation answers a request naming nothing, whatever the role may do. */ + @ParameterizedTest + @CsvSource({"elasticmapreduce:addStep,The field ClusterId is required.", + "elasticmapreduce:terminateCluster,The field ClusterId is required.", + "emr-serverless:startApplication,The field ApplicationId is required.", + "emr-serverless:startJobRun,The field ApplicationId is required.", + "ecs:runTask,TaskDefinition is required for the ecs:runTask integration"}) + void aRequestNamingNothingIsLeftToTheIntegration(String resource, String cause) throws Exception { + Response completed = terminal(start(machine(task(resource, Map.of("Other", "x")), + role(STATES_TRUST, READ_ONLY)), "{}")); + + assertFailed(completed, "States.TaskFailed"); + assertEquals(cause, completed.jsonPath().getString("cause"), completed.asString()); + } + + @Test + void cancelJobRunNamingNoRunIsLeftToTheIntegration() throws Exception { + String application = application(); + Response completed = terminal(start(machine(task("emr-serverless:cancelJobRun", + Map.of("ApplicationId", application)), role(STATES_TRUST, READ_ONLY)), "{}")); + + assertFailed(completed, "States.TaskFailed"); + assertEquals("The field JobRunId is required.", completed.jsonPath().getString("cause"), completed.asString()); + } + + /** A Task may write an EMR Serverless id in the API's camelCase: it is still the same resource. */ + @Test + void anApplicationIdWrittenInCamelCaseIsStillEvaluated() throws Exception { + String application = application(); + Map task = task("emr-serverless:startApplication", Map.of("applicationId", application)); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")), + "EmrServerless.AccessDeniedException"); + } + + /** + * What a task acts on and how to observe it. + * + * @param actions the actions the call needs, all on {@code resourceArn}, in the order they are evaluated + */ + private record Target(String integration, String error, String resourceArn, Map arguments, + Check reached, Check notReached, String... actions) { + + String action() { + return actions[0]; + } + + String grant() { + return allow(resourceArn, actions); + } + } + + @FunctionalInterface + private interface Check { + void check() throws Exception; + } + + + private Target target(String integration) throws Exception { + return switch (integration) { + case "ecs:runTask" -> runTaskTarget(); + case "aws-sdk:ecs:updateService" -> updateServiceTarget(); + case "aws-sdk:ecs:listServices" -> new Target(integration, "Ecs.AccessDeniedException", ANY_RESOURCE, + Map.of("Cluster", ecsCluster()), NOTHING_TO_READ, NOTHING_TO_READ, "ecs:ListServices"); + case "aws-sdk:ecs:describeServices" -> describeServicesTarget(); + case "elasticmapreduce:createCluster" -> createClusterTarget(); + case "elasticmapreduce:setClusterTerminationProtection" -> terminationProtectionTarget(); + case "elasticmapreduce:terminateCluster" -> terminateClusterTarget(); + case "elasticmapreduce:addStep" -> addStepTarget(); + case "elasticmapreduce:cancelStep" -> cancelStepTarget(); + case "elasticmapreduce:modifyInstanceFleetByName" -> fleetTarget(); + case "elasticmapreduce:modifyInstanceGroupByName" -> groupTarget(); + case "emr-serverless:createApplication" -> createApplicationTarget(); + case "emr-serverless:startApplication" -> startApplicationTarget(); + case "emr-serverless:stopApplication" -> stopApplicationTarget(); + case "emr-serverless:deleteApplication" -> deleteApplicationTarget(); + case "emr-serverless:startJobRun" -> startJobRunTarget(); + case "emr-serverless:cancelJobRun" -> cancelJobRunTarget(); + default -> throw new IllegalArgumentException(integration); + }; + } + + private Target runTaskTarget() throws Exception { + String family = family(); + String cluster = ecsCluster(); + return new Target("ecs:runTask", "ECS.AccessDeniedException", taskDefinitionArn(family, 1), + Map.of("Cluster", cluster, "TaskDefinition", family), + () -> assertEquals(1, runningTasks(cluster).size()), + () -> assertEquals(List.of(), runningTasks(cluster)), "ecs:RunTask"); + } + + private Target updateServiceTarget() throws Exception { + String family = family(); + String cluster = ecsCluster(); + String service = ecsService(cluster, "svc", family); + return new Target("aws-sdk:ecs:updateService", "Ecs.AccessDeniedException", service, + Map.of("Cluster", cluster, "Service", "svc", "DesiredCount", 1), + () -> assertEquals(1, desiredCount(cluster, "svc")), + () -> assertEquals(0, desiredCount(cluster, "svc")), "ecs:UpdateService"); + } + + private Target describeServicesTarget() throws Exception { + String family = family(); + String cluster = ecsCluster(); + String service = ecsService(cluster, "svc", family); + return new Target("aws-sdk:ecs:describeServices", "Ecs.AccessDeniedException", service, + Map.of("Cluster", cluster, "Services", List.of("svc")), NOTHING_TO_READ, NOTHING_TO_READ, + "ecs:DescribeServices"); + } + + private Target createClusterTarget() { + String name = "sfn-jobs-" + UUID.randomUUID(); + cleanup.register(() -> { + for (String id : clusterIdsNamed(name)) { + emr("TerminateJobFlows", Map.of("JobFlowIds", List.of(id))).then().statusCode(200); + } + }); + return new Target("elasticmapreduce:createCluster", "EMR.AccessDeniedException", ANY_RESOURCE, + Map.of("Name", name, "ReleaseLabel", "emr-7.5.0", "Instances", GROUPS), + () -> assertEquals(1, clusterIdsNamed(name).size()), + () -> assertEquals(List.of(), clusterIdsNamed(name)), "elasticmapreduce:RunJobFlow"); + } + + private Target terminationProtectionTarget() throws Exception { + String id = emrCluster(GROUPS); + return new Target("elasticmapreduce:setClusterTerminationProtection", "EMR.AccessDeniedException", + emrClusterArn(id), Map.of("ClusterId", id, "TerminationProtected", true), + () -> assertTrue(describeCluster(id).path("TerminationProtected").asBoolean()), + () -> assertFalse(describeCluster(id).path("TerminationProtected").asBoolean()), + "elasticmapreduce:SetTerminationProtection"); + } + + private Target terminateClusterTarget() throws Exception { + String id = emrCluster(GROUPS); + return new Target("elasticmapreduce:terminateCluster", "EMR.AccessDeniedException", emrClusterArn(id), + Map.of("ClusterId", id), + () -> assertTrue(describeCluster(id).path("Status").path("State").asText().startsWith("TERMINAT")), + () -> assertEquals("WAITING", describeCluster(id).path("Status").path("State").asText()), + "elasticmapreduce:TerminateJobFlows"); + } + + private Target addStepTarget() throws Exception { + String id = emrCluster(GROUPS); + return new Target("elasticmapreduce:addStep", "EMR.AccessDeniedException", emrClusterArn(id), + Map.of("ClusterId", id, "Step", STEP), + () -> assertEquals(1, steps(id).size()), + () -> assertEquals(0, steps(id).size()), "elasticmapreduce:AddJobFlowSteps"); + } + + private Target cancelStepTarget() throws Exception { + String id = emrCluster(GROUPS); + Response added = emr("AddJobFlowSteps", Map.of("JobFlowId", id, "Steps", List.of(STEP))); + added.then().statusCode(200); + String stepId = added.jsonPath().getString("StepIds[0]"); + return new Target("elasticmapreduce:cancelStep", "EMR.AccessDeniedException", emrClusterArn(id), + Map.of("ClusterId", id, "StepId", stepId), NOTHING_TO_READ, NOTHING_TO_READ, + "elasticmapreduce:CancelSteps"); + } + + private Target fleetTarget() throws Exception { + String id = emrCluster(FLEETS); + return new Target("elasticmapreduce:modifyInstanceFleetByName", "EMR.AccessDeniedException", emrClusterArn(id), + Map.of("ClusterId", id, "InstanceFleetName", "Core", "InstanceFleet", Map.of("TargetOnDemandCapacity", 5)), + () -> assertEquals(5, fleetCapacity(id)), () -> assertEquals(2, fleetCapacity(id)), + "elasticmapreduce:ListInstanceFleets", "elasticmapreduce:ModifyInstanceFleet"); + } + + private Target groupTarget() throws Exception { + String id = emrCluster(GROUPS); + return new Target("elasticmapreduce:modifyInstanceGroupByName", "EMR.AccessDeniedException", emrClusterArn(id), + Map.of("ClusterId", id, "InstanceGroupName", "Core", "InstanceGroup", Map.of("InstanceCount", 4)), + () -> assertEquals(4, groupCount(id)), () -> assertEquals(2, groupCount(id)), + "elasticmapreduce:ListInstanceGroups", "elasticmapreduce:ModifyInstanceGroups"); + } + + private Target createApplicationTarget() { + String name = "sfn-jobs-" + UUID.randomUUID(); + cleanup.register(() -> { + for (String id : applicationIdsNamed(name)) { + removeApplication(id); + } + }); + return new Target("emr-serverless:createApplication", "EmrServerless.AccessDeniedException", ANY_RESOURCE, + Map.of("Name", name, "ReleaseLabel", "emr-7.5.0", "Type", "SPARK"), + () -> assertEquals(1, applicationIdsNamed(name).size()), + () -> assertEquals(List.of(), applicationIdsNamed(name)), "emr-serverless:CreateApplication"); + } + + private Target startApplicationTarget() throws Exception { + String id = application(); + return new Target("emr-serverless:startApplication", "EmrServerless.AccessDeniedException", applicationArn(id), + Map.of("ApplicationId", id), + () -> assertTrue(applicationState(id).startsWith("START"), applicationState(id)), + () -> assertEquals("CREATED", applicationState(id)), "emr-serverless:StartApplication"); + } + + private Target stopApplicationTarget() throws Exception { + String id = application(); + emrServerless().post("/applications/" + id + "/start").then().statusCode(200); + awaiting("application " + id + " started").until(() -> "STARTED".equals(applicationState(id))); + return new Target("emr-serverless:stopApplication", "EmrServerless.AccessDeniedException", applicationArn(id), + Map.of("ApplicationId", id), + () -> assertTrue(applicationState(id).startsWith("STOP"), applicationState(id)), + () -> assertEquals("STARTED", applicationState(id)), "emr-serverless:StopApplication"); + } + + private Target deleteApplicationTarget() throws Exception { + String id = application(); + return new Target("emr-serverless:deleteApplication", "EmrServerless.AccessDeniedException", applicationArn(id), + Map.of("ApplicationId", id), + () -> assertEquals("TERMINATED", applicationState(id)), + () -> assertEquals("CREATED", applicationState(id)), "emr-serverless:DeleteApplication"); + } + + private Target startJobRunTarget() throws Exception { + String id = application(); + return new Target("emr-serverless:startJobRun", "EmrServerless.AccessDeniedException", applicationArn(id), + Map.of("ApplicationId", id, "ExecutionRoleArn", jobRole(), "JobDriver", JOB_DRIVER), + () -> assertEquals(1, jobRuns(id).size()), + () -> assertEquals(0, jobRuns(id).size()), "emr-serverless:StartJobRun"); + } + + private Target cancelJobRunTarget() throws Exception { + String id = application(); + Response started = emrServerless().body(MAPPER.writeValueAsString(Map.of("clientToken", UUID.randomUUID().toString(), + "mode", "STREAMING", "executionRoleArn", jobRole(), + "jobDriver", Map.of("sparkSubmit", Map.of("entryPoint", "s3://bucket/jobs/app.py"))))) + .post("/applications/" + id + "/jobruns"); + started.then().statusCode(200); + String run = started.jsonPath().getString("jobRunId"); + return new Target("emr-serverless:cancelJobRun", "EmrServerless.AccessDeniedException", + applicationArn(id) + "/jobruns/" + run, Map.of("ApplicationId", id, "JobRunId", run), + () -> assertTrue(jobRunState(id, run).startsWith("CANCEL"), jobRunState(id, run)), + () -> assertFalse(jobRunState(id, run).startsWith("CANCEL"), jobRunState(id, run)), + "emr-serverless:CancelJobRun"); + } + + private String family() throws Exception { + String family = "sfn-jobs-" + UUID.randomUUID(); + registerRevision(family); + cleanup.register(() -> { + for (int revision : List.of(2, 1)) { + String reference = family + ":" + revision; + if (ecs("DeregisterTaskDefinition", Map.of("taskDefinition", reference)).statusCode() == 200) { + ecs("DeleteTaskDefinitions", Map.of("taskDefinitions", List.of(reference))).then().statusCode(200); + } + } + }); + return family; + } + + private void registerRevision(String family) { + ecs("RegisterTaskDefinition", Map.of("family", family, "containerDefinitions", + List.of(Map.of("name", "runner", "image", "floci-test/runner:latest", "memory", 128)))) + .then().statusCode(200); + } + + private static String taskDefinitionArn(String family, int revision) { + return "arn:aws:ecs:" + REGION + ":" + ACCOUNT + ":task-definition/" + family + ":" + revision; + } + + private String ecsCluster() { + String name = "sfn-jobs-" + UUID.randomUUID(); + ecs("CreateCluster", Map.of("clusterName", name)).then().statusCode(200); + cleanup.register(() -> { + for (String task : runningTasks(name)) { + ecs("StopTask", Map.of("cluster", name, "task", task)).then().statusCode(200); + } + ecs("DeleteCluster", Map.of("cluster", name)).then().statusCode(200); + }); + return name; + } + + private String ecsService(String cluster, String name, String family) { + Response created = ecs("CreateService", Map.of("cluster", cluster, "serviceName", name, + "taskDefinition", family, "desiredCount", 0)); + created.then().statusCode(200); + cleanup.register(() -> ecs("DeleteService", Map.of("cluster", cluster, "service", name, "force", true)) + .then().statusCode(200)); + return created.jsonPath().getString("service.serviceArn"); + } + + private static String serviceArn(String cluster, String service) { + return "arn:aws:ecs:" + REGION + ":" + ACCOUNT + ":service/" + cluster + "/" + service; + } + + private List runningTasks(String cluster) { + Response listed = ecs("ListTasks", Map.of("cluster", cluster)); + listed.then().statusCode(200); + return listed.jsonPath().getList("taskArns"); + } + + private String awaitRunningTask(String cluster) throws Exception { + awaiting("a task in " + cluster).until(() -> !runningTasks(cluster).isEmpty()); + return runningTasks(cluster).getFirst(); + } + + private int desiredCount(String cluster, String service) { + Response described = ecs("DescribeServices", Map.of("cluster", cluster, "services", List.of(service))); + described.then().statusCode(200); + return described.jsonPath().getInt("services[0].desiredCount"); + } + + private Response ecs(String action, Map input) { + return sfn().json(ACCOUNT, "ecs", "AmazonEC2ContainerServiceV20141113." + action, "application/x-amz-json-1.1", input); + } + + private String emrCluster(Map instances) throws Exception { + Response created = emr("RunJobFlow", Map.of("Name", "sfn-jobs-" + UUID.randomUUID(), + "ReleaseLabel", "emr-7.5.0", "Instances", instances)); + created.then().statusCode(200); + String id = created.jsonPath().getString("JobFlowId"); + cleanup.register(() -> { + emr("SetTerminationProtection", Map.of("JobFlowIds", List.of(id), "TerminationProtected", false)); + emr("TerminateJobFlows", Map.of("JobFlowIds", List.of(id))).then().statusCode(200); + }); + awaiting("cluster " + id).until(() -> "WAITING".equals(describeCluster(id).path("Status").path("State").asText())); + return id; + } + + private static String emrClusterArn(String id) { + return "arn:aws:elasticmapreduce:" + REGION + ":" + ACCOUNT + ":cluster/" + id; + } + + private JsonNode describeCluster(String id) throws Exception { + Response described = emr("DescribeCluster", Map.of("ClusterId", id)); + described.then().statusCode(200); + return MAPPER.readTree(described.asString()).path("Cluster"); + } + + private List clusterIdsNamed(String name) { + Response listed = emr("ListClusters", Map.of()); + listed.then().statusCode(200); + return listed.jsonPath().getList("Clusters.findAll { it.Name == '" + name + "' }.Id"); + } + + private JsonNode steps(String id) throws Exception { + Response listed = emr("ListSteps", Map.of("ClusterId", id)); + listed.then().statusCode(200); + return MAPPER.readTree(listed.asString()).path("Steps"); + } + + private int fleetCapacity(String id) { + return emr("ListInstanceFleets", Map.of("ClusterId", id)).jsonPath() + .getInt("InstanceFleets.find { it.Name == 'Core' }.TargetOnDemandCapacity"); + } + + private int groupCount(String id) { + return emr("ListInstanceGroups", Map.of("ClusterId", id)).jsonPath() + .getInt("InstanceGroups.find { it.Name == 'Core' }.RequestedInstanceCount"); + } + + private Response emr(String action, Map input) { + return sfn().json(ACCOUNT, "elasticmapreduce", "ElasticMapReduce." + action, "application/x-amz-json-1.1", input); + } + + private String application() throws Exception { + Response created = emrServerless().body(MAPPER.writeValueAsString(Map.of( + "name", "sfn-jobs-" + UUID.randomUUID(), "releaseLabel", "emr-7.5.0", "type", "SPARK", + "clientToken", UUID.randomUUID().toString()))) + .post("/applications"); + created.then().statusCode(200); + String id = created.jsonPath().getString("applicationId"); + cleanup.register(() -> removeApplication(id)); + awaiting("application " + id).until(() -> "CREATED".equals(applicationState(id))); + return id; + } + + private void removeApplication(String id) { + if ("TERMINATED".equals(applicationState(id))) { + return; + } + for (String run : emrServerless().get("/applications/" + id + "/jobruns").jsonPath() + .getList("jobRuns.id")) { + emrServerless().delete("/applications/" + id + "/jobruns/" + run); + } + emrServerless().post("/applications/" + id + "/stop"); + awaiting("application " + id + " stopped") + .until(() -> !applicationState(id).startsWith("START") && !"STOPPING".equals(applicationState(id))); + emrServerless().delete("/applications/" + id).then().statusCode(200); + } + + private static String applicationArn(String id) { + return "arn:aws:emr-serverless:" + REGION + ":" + ACCOUNT + ":/applications/" + id; + } + + private String applicationState(String id) { + return emrServerless().get("/applications/" + id).jsonPath().getString("application.state"); + } + + private List applicationIdsNamed(String name) { + Response listed = emrServerless().get("/applications"); + listed.then().statusCode(200); + return listed.jsonPath().getList("applications.findAll { it.name == '" + name + "' }.id"); + } + + private List jobRuns(String application) { + Response listed = emrServerless().get("/applications/" + application + "/jobruns"); + listed.then().statusCode(200); + return listed.jsonPath().getList("jobRuns.id"); + } + + private String jobRunState(String application, String run) { + return emrServerless().get("/applications/" + application + "/jobruns/" + run).jsonPath() + .getString("jobRun.state"); + } + + private String jobRole() { + return role(EMR_SERVERLESS_TRUST, READ_ONLY); + } + + private RequestSpecification emrServerless() { + return given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "emr-serverless")) + .contentType("application/json"); + } + + + private static Map task(String resource, Map arguments) { + return Map.of("Type", "Task", "Resource", "arn:aws:states:::" + resource, "Parameters", arguments, "End", true); + } + + private Map jsonPathTask(Target target, String taskRole) { + Map task = new LinkedHashMap<>(task(target.integration(), target.arguments())); + if (taskRole != null) { + task.put("Credentials", Map.of("RoleArn", taskRole)); + } + return task; + } + + private Map jsonataTask(Target target, String roleExpression) { + Map task = new LinkedHashMap<>(Map.of("Type", "Task", "QueryLanguage", "JSONata", + "Resource", "arn:aws:states:::" + target.integration(), + "Arguments", target.arguments(), "End", true)); + if (roleExpression != null) { + task.put("Credentials", Map.of("RoleArn", roleExpression)); + } + return task; + } + + private static String allow(String resource, String... actions) { + return policy(List.of(Map.of("Effect", "Allow", "Action", List.of(actions), "Resource", List.of(resource)))); + } + + private static String policy(List> statements) { + try { + return MAPPER.writeValueAsString(Map.of("Version", "2012-10-17", "Statement", statements)); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + + private static void assertFailed(Response completed, String error) { + assertEquals("FAILED", completed.jsonPath().getString("status"), completed.asString()); + assertEquals(error, completed.jsonPath().getString("error"), completed.asString()); + } + + private String role(String trust, String policy) { + return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", + "sfn-jobs-" + UUID.randomUUID(), trust, policy); + } + + private String machine(Map task, String role) throws Exception { + return machineWithDefinition(MAPPER.writeValueAsString( + Map.of("StartAt", "Send", "States", Map.of("Send", task))), role); + } + + private String machineWithDefinition(String definition, String role) { + return sfn().createMachine(ACCOUNT, "sfn-jobs-iam-", definition, "STANDARD", role); + } + + private String start(String machine, String input) { + return sfn().start(ACCOUNT, machine, input); + } + + private Response terminal(String execution) throws Exception { + return terminal(execution, 20); + } + + private Response terminal(String execution, int seconds) throws Exception { + return sfn().terminal(ACCOUNT, execution, seconds); + } + + private List eventsOfType(String execution, String type) throws Exception { + return sfn().eventsOfType(ACCOUNT, execution, type); + } + + private Response request(String action, Map input) { + return sfn().request(ACCOUNT, action, input); + } + + private StepFunctionsTestClient sfn() { + return new StepFunctionsTestClient(baseUri.getPort(), cleanup); + } + + /** Polls for {@code what} as long and as often as the task tests allow a background start. */ + private static ConditionFactory awaiting(String what) { + return await(what).atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofMillis(50)); + } + +} diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java index 80beff0333..3b719e4915 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java @@ -22,6 +22,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import java.net.URI; @@ -290,6 +291,34 @@ class StepFunctionsTaskCredentialsIntegrationTest { assertDataTaskIsNotEvaluated(integration, arguments, "FAILED"); } + /** Past authorization, ECS answers: nothing here reaches anything, and no role is evaluated. */ + @ParameterizedTest + @ValueSource(strings = {"ecs:runTask", "ecs:runTask.sync", "aws-sdk:ecs:updateService", "aws-sdk:ecs:describeServices"}) + void ecsCredentialsRetainDefaultIamDisabledBehavior(String integration) throws Exception { + Map arguments = integration.startsWith("ecs:") + ? Map.of("TaskDefinition", "no-such-family-" + UUID.randomUUID()) + : Map.of("Cluster", "no-such-cluster", "Service", "any", "Services", List.of("any")); + assertDataTaskIsNotEvaluated(integration, arguments, "FAILED"); + } + + @Test + void ecsListServicesCredentialsRetainDefaultIamDisabledBehavior() throws Exception { + assertDataTaskIsNotEvaluated("aws-sdk:ecs:listServices", Map.of(), "SUCCEEDED"); + } + + /** Past authorization, the service answers: these name what it does not have. */ + @ParameterizedTest + @CsvSource({"elasticmapreduce:addStep,ClusterId,j-NOSUCHCLUSTER,FAILED", + "emr-serverless:startApplication,ApplicationId,00nosuchapp00000,FAILED"}) + void emrCredentialsRetainDefaultIamDisabledBehavior(String integration, String member, String value, String status) + throws Exception { + Map arguments = integration.contains("addStep") + ? Map.of(member, value, "Step", Map.of("Name", "job", "ActionOnFailure", "CONTINUE", + "HadoopJarStep", Map.of("Jar", "command-runner.jar"))) + : Map.of(member, value); + assertDataTaskIsNotEvaluated(integration, arguments, status); + } + private void assertDataTaskIsNotEvaluated(String integration, Map arguments, String status) throws Exception { String taskRole = "arn:aws:iam::" + TARGET + ":role/no-such-role"; diff --git a/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java b/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java index 7f3655f07e..f7bdf2d4ca 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java @@ -3,6 +3,7 @@ package io.floci.aws.services.stepfunctions; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.StoredResourceArns; +import io.floci.aws.services.ecs.EcsService; import io.floci.aws.services.stepfunctions.LambdaTaskAuthorizer.Permission; import io.floci.aws.services.stepfunctions.model.StateMachine; import org.junit.jupiter.api.Test; @@ -26,6 +27,10 @@ class TaskPermissionsTest { private static final String TOPIC = "arn:aws:sns:eu-west-1:111122223333:orders"; private static final String REDSHIFT_CLUSTER = "arn:aws:redshift:eu-west-1:111122223333:cluster:orders"; private static final String ENDPOINT = "arn:aws:sns:eu-west-1:111122223333:endpoint/GCM/app/id"; + private static final String TASK_DEFINITION = "arn:aws:ecs:eu-west-1:111122223333:task-definition/orders:7"; + private static final String SERVICE = "arn:aws:ecs:eu-west-1:111122223333:service/c/s"; + private static final String EMR_CLUSTER = "arn:aws:elasticmapreduce:eu-west-1:111122223333:cluster/j-1"; + private static final String APPLICATION = "arn:aws:emr-serverless:eu-west-1:111122223333:/applications/a"; /** Each form resolves in the state machine's Region, whichever host it names, as the queue lookup does. */ @ParameterizedTest @@ -395,6 +400,197 @@ class TaskPermissionsTest { assertEquals(Optional.empty(), TaskPermissions.of(integration("aws-sdk:redshiftdata:executeStatement.sync"), json("{}"), machine("aws"))); } + /** Whatever names it, the check is on the revision {@code EcsService} finds, which is the one it would run. */ + @ParameterizedTest + @ValueSource(strings = {"ecs:runTask", "ecs:runTask.sync"}) + void runTaskIsCheckedOnTheRevisionEcsFinds(String tail) throws Exception { + EcsService ecs = mock(EcsService.class); + when(ecs.taskDefinitionArn("orders", "eu-west-1")).thenReturn(Optional.of(TASK_DEFINITION)); + + assertEquals(TaskPermissions.accessDenied("ECS.", List.of(new Permission("ecs:RunTask", TASK_DEFINITION))), + ecsPermissions(tail, "{\"TaskDefinition\":\"orders\"}", ecs)); + } + + /** A form the integration does not serve is left to its unsupported-mode answer, whatever the role. */ + @Test + void aRunTaskFormEcsDoesNotServeStaysUnchecked() throws Exception { + assertEquals(Optional.empty(), TaskPermissions.of(integration("ecs:runTask.sync:2"), + json("{\"TaskDefinition\":\"orders\"}"), machine("aws"), null, mock(EcsService.class), false)); + } + + /** {@code executeTaskState} strips the suffix, so this is a {@code .waitForTaskToken} as the dispatch sees it. */ + @Test + void runTaskWithATokenIsChecked() throws Exception { + EcsService ecs = mock(EcsService.class); + when(ecs.taskDefinitionArn("orders", "eu-west-1")).thenReturn(Optional.of(TASK_DEFINITION)); + + assertEquals(List.of(new Permission("ecs:RunTask", TASK_DEFINITION)), + TaskPermissions.of(integration("ecs:runTask"), json("{\"TaskDefinition\":\"orders\"}"), machine("aws"), + null, ecs, true).orElseThrow().permissions()); + } + + @ParameterizedTest + @ValueSource(strings = {"{}", "{\"TaskDefinition\":null}", "{\"TaskDefinition\":\"no-such\"}"}) + void aTaskDefinitionEcsDoesNotFindNeedsNoPermission(String request) throws Exception { + assertEquals(TaskPermissions.accessDenied("ECS.", List.of()), + ecsPermissions("ecs:runTask", request, mock(EcsService.class))); + } + + @Test + void runTaskWithoutEcsNamesNothing() throws Exception { + assertEquals(TaskPermissions.accessDenied("ECS.", List.of()), TaskPermissions.of(integration("ecs:runTask"), + json("{\"TaskDefinition\":\"orders\"}"), machine("aws")).orElseThrow()); + } + + /** The members are read in either casing, as the SDK form recases them for the handler. */ + @ParameterizedTest + @ValueSource(strings = {"{\"Cluster\":\"c\",\"Service\":\"s\"}", "{\"cluster\":\"c\",\"service\":\"s\"}"}) + void updateServiceIsCheckedOnTheServiceEcsFinds(String request) throws Exception { + EcsService ecs = mock(EcsService.class); + when(ecs.updatedServiceArn("c", "s", "eu-west-1")).thenReturn(Optional.of(SERVICE)); + + assertEquals(TaskPermissions.accessDenied("Ecs.", List.of(new Permission("ecs:UpdateService", SERVICE))), + ecsPermissions("aws-sdk:ecs:updateService", request, ecs)); + } + + @Test + void updateServiceWithNoClusterAsksForTheDefault() throws Exception { + EcsService ecs = mock(EcsService.class); + when(ecs.updatedServiceArn(null, "s", "eu-west-1")).thenReturn(Optional.of(SERVICE)); + + assertEquals(List.of(new Permission("ecs:UpdateService", SERVICE)), + ecsPermissions("aws-sdk:ecs:updateService", "{\"Service\":\"s\"}", ecs).permissions()); + } + + @Test + void describeServicesIsCheckedOnEachDistinctServiceEcsFinds() throws Exception { + EcsService ecs = mock(EcsService.class); + when(ecs.describedServiceArn("c", "a", "eu-west-1")).thenReturn(Optional.of(SERVICE)); + when(ecs.describedServiceArn("c", SERVICE, "eu-west-1")).thenReturn(Optional.of(SERVICE)); + when(ecs.describedServiceArn("c", "b", "eu-west-1")).thenReturn(Optional.of(SERVICE + "b")); + + assertEquals(List.of(new Permission("ecs:DescribeServices", SERVICE), + new Permission("ecs:DescribeServices", SERVICE + "b")), + ecsPermissions("aws-sdk:ecs:describeServices", + "{\"Cluster\":\"c\",\"Services\":[\"a\",\"" + SERVICE + "\",\"missing\",\"b\"]}", ecs) + .permissions()); + } + + @Test + void listServicesActsOnNoResource() throws Exception { + assertEquals(TaskPermissions.accessDenied("Ecs.", List.of(new Permission("ecs:ListServices", "*"))), + TaskPermissions.of(integration("aws-sdk:ecs:listServices"), json("{}"), machine("aws")).orElseThrow()); + } + + @ParameterizedTest + @ValueSource(strings = {"aws-sdk:ecs:runTask", "aws-sdk:ecs:createService", "aws-sdk:ecs:updateService.sync", + "ecs:updateService", "elasticmapreduce:listClusters", "elasticmapreduce:createCluster.waitForTaskToken", + "elasticmapreduce:cancelStep.sync", "elasticmapreduce:addStep.sync:2", "aws-sdk:elasticmapreduce:addStep", + "emr-serverless:listApplications", "emr-serverless:startJobRun.sync:2", + "emr-serverless:startJobRun.waitForTaskToken", "aws-sdk:emrserverless:startJobRun"}) + void aJobApiNotServedStaysUnchecked(String tail) throws Exception { + assertEquals(Optional.empty(), TaskPermissions.of(integration(tail), + json("{\"ClusterId\":\"j-1\",\"ApplicationId\":\"a\"}"), machine("aws"))); + } + + /** {@code executeTaskState} strips the suffix: the integration alone no longer shows these have no such form. */ + @ParameterizedTest + @ValueSource(strings = {"elasticmapreduce:addStep", "emr-serverless:startJobRun"}) + void anEmrApiWithATokenStaysUnchecked(String tail) throws Exception { + assertEquals(Optional.empty(), TaskPermissions.of(integration(tail), + json("{\"ClusterId\":\"j-1\",\"ApplicationId\":\"a\"}"), machine("aws"), null, null, true)); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "setClusterTerminationProtection|SetTerminationProtection", + "terminateCluster|TerminateJobFlows", + "terminateCluster.sync|TerminateJobFlows", + "addStep|AddJobFlowSteps", + "addStep.sync|AddJobFlowSteps", + "cancelStep|CancelSteps"}) + void anEmrApiNeedsItsActionOnTheCluster(String api, String action) throws Exception { + assertEquals(TaskPermissions.accessDenied("EMR.", List.of(new Permission("elasticmapreduce:" + action, EMR_CLUSTER))), + TaskPermissions.of(integration("elasticmapreduce:" + api), json("{\"ClusterId\":\"j-1\"}"), + machine("aws")).orElseThrow()); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = {"modifyInstanceFleetByName|ListInstanceFleets|ModifyInstanceFleet", + "modifyInstanceGroupByName|ListInstanceGroups|ModifyInstanceGroups"}) + void aByNameApiNeedsTheListAndTheModify(String api, String list, String modify) throws Exception { + assertEquals(List.of(new Permission("elasticmapreduce:" + list, EMR_CLUSTER), + new Permission("elasticmapreduce:" + modify, EMR_CLUSTER)), + TaskPermissions.of(integration("elasticmapreduce:" + api), json("{\"ClusterId\":\"j-1\"}"), + machine("aws")).orElseThrow().permissions()); + } + + @ParameterizedTest + @ValueSource(strings = {"elasticmapreduce:createCluster", "elasticmapreduce:createCluster.sync"}) + void createClusterActsOnNoResource(String tail) throws Exception { + assertEquals(List.of(new Permission("elasticmapreduce:RunJobFlow", "*")), + TaskPermissions.of(integration(tail), json("{}"), machine("aws")).orElseThrow().permissions()); + } + + @ParameterizedTest + @ValueSource(strings = {"{}", "{\"ClusterId\":\" \"}", "{\"ClusterId\":7}", "{\"clusterId\":\"j-1\"}"}) + void anEmrRequestNamingNoClusterNeedsNoPermission(String request) throws Exception { + assertEquals(TaskPermissions.accessDenied("EMR.", List.of()), + TaskPermissions.of(integration("elasticmapreduce:addStep"), json(request), machine("aws")).orElseThrow()); + } + + @Test + void theClusterIsInTheStateMachinesPartition() throws Exception { + assertEquals(List.of(new Permission("elasticmapreduce:AddJobFlowSteps", + "arn:aws-cn:elasticmapreduce:eu-west-1:" + ACCOUNT + ":cluster/j-1")), + TaskPermissions.of(integration("elasticmapreduce:addStep"), json("{\"ClusterId\":\"j-1\"}"), + machine("aws-cn")).orElseThrow().permissions()); + } + + @ParameterizedTest + @CsvSource({"startApplication,StartApplication", "startApplication.sync,StartApplication", + "stopApplication,StopApplication", "deleteApplication,DeleteApplication", "startJobRun,StartJobRun", + "startJobRun.sync,StartJobRun"}) + void anEmrServerlessApiNeedsItsActionOnTheApplication(String api, String action) throws Exception { + assertEquals(TaskPermissions.accessDenied("EmrServerless.", List.of(new Permission("emr-serverless:" + action, APPLICATION))), + TaskPermissions.of(integration("emr-serverless:" + api), json("{\"ApplicationId\":\"a\"}"), + machine("aws")).orElseThrow()); + } + + @Test + void anEmrServerlessIdIsReadInEitherCase() throws Exception { + assertEquals(List.of(new Permission("emr-serverless:CancelJobRun", APPLICATION + "/jobruns/r")), + TaskPermissions.of(integration("emr-serverless:cancelJobRun"), + json("{\"applicationId\":\"a\",\"jobRunId\":\"r\"}"), machine("aws")).orElseThrow().permissions()); + } + + @Test + void cancelJobRunIsCheckedOnTheRun() throws Exception { + assertEquals(List.of(new Permission("emr-serverless:CancelJobRun", APPLICATION + "/jobruns/r")), + TaskPermissions.of(integration("emr-serverless:cancelJobRun.sync"), + json("{\"ApplicationId\":\"a\",\"JobRunId\":\"r\"}"), machine("aws")).orElseThrow().permissions()); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = {"startJobRun|{}", "startJobRun|{\"ApplicationId\":7}", + "startApplication|{\"ApplicationId\":\" \"}", "cancelJobRun|{\"ApplicationId\":\"a\"}", + "cancelJobRun|{\"JobRunId\":\"r\"}"}) + void anEmrServerlessRequestMissingAnIdNeedsNoPermission(String api, String request) throws Exception { + assertEquals(TaskPermissions.accessDenied("EmrServerless.", List.of()), + TaskPermissions.of(integration("emr-serverless:" + api), json(request), machine("aws")).orElseThrow()); + } + + @Test + void createApplicationActsOnNoResource() throws Exception { + assertEquals(List.of(new Permission("emr-serverless:CreateApplication", "*")), + TaskPermissions.of(integration("emr-serverless:createApplication"), json("{}"), machine("aws")) + .orElseThrow().permissions()); + } + + private static TaskPermissions ecsPermissions(String tail, String request, EcsService ecs) throws Exception { + return TaskPermissions.of(integration(tail), json(request), machine("aws"), null, ecs, false).orElseThrow(); + } + private static List sdkPermissions(String api, String request) throws Exception { return TaskPermissions.of(integration("aws-sdk:dynamodb:" + api), json(request), machine("aws")).orElseThrow().permissions(); }