Light, fluffy, and always free - The AWS Local Emulator alternative
fix(stepfunctions): authorize nested task credentials (#6084)
Andre Kurait07501289664a
diff --git a/docs/services/step-functions.md b/docs/services/step-functions.mdindex 5b9f7eaa9c..51859550cb 100644--- a/docs/services/step-functions.md+++ b/docs/services/step-functions.md@@ -46,6 +46,27 @@definition, role, logging, tracing, encryption, and tags without replacing the state machine;changes to `StateMachineName` or `StateMachineType` use replacement semantics.+## Nested task credentials++Nested `states:startExecution` tasks, including `.sync` and `.sync:2`, and the SDK+`sfn:startExecution` and `sfn:startSyncExecution` integrations accept `Credentials.RoleArn`.+JSONPath `RoleArn.$` resolves against the state input after `InputPath` and before+`Parameters`. The role must exist with its exact ARN in the execution's partition.+The child call and polling use that role's account; parent history, subsequent states,+and cancellation checks retain the parent's account.++With IAM enforcement enabled, the existing task authorizer checks the execution role's+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. 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+that does not match the selected task account fails with+`StepFunctions.AWSStepFunctionsException` for optimized integrations or+`Sfn.SfnException` for SDK integrations, matching the live AWS probes.+## Execution history events`GetExecutionHistory` emits an event family around a Task state's `TaskStateEntered` anddiff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.javaindex 2659bb66b0..c4d262b511 100644--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java@@ -268,6 +268,7 @@ public class AslExecutor {private final WebClient webClient;private final ApiGatewayTaskInvoker apiGatewayTaskInvoker;private final EmulatorConfig config;+ private final NestedTaskCredentials nestedTaskCredentials;private final CustomResourceLiveness customResourceLiveness;private final Clock clock;private final Sleeper sleeper;@@ -295,15 +296,15 @@ public class AslExecutor {ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator,Instance<StepFunctionsService> sfnService, EmulatorConfig config, Vertx vertx,CustomResourceLiveness customResourceLiveness, RedshiftDataJsonHandler redshiftDataHandler,- ServiceRegistry serviceRegistry, LambdaTaskAuthorizer lambdaTaskAuthorizer,- ApiGatewayTaskInvoker apiGatewayTaskInvoker) {+ ServiceRegistry serviceRegistry, NestedTaskCredentials nestedTaskCredentials,+ LambdaTaskAuthorizer lambdaTaskAuthorizer, ApiGatewayTaskInvoker apiGatewayTaskInvoker) {this(lambdaExecutor, targetResolver, dynamoDb, dynamoDbJsonHandler,sqsJsonHandler, snsJsonHandler, cloudFormationHandler,ec2Service, s3Service, ecsService, ecsJsonHandler,eventBridgeHandler, schedulerService, schedulerController, rdsDataService,objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, redshiftDataHandler, serviceRegistry,- lambdaTaskAuthorizer, null, null, apiGatewayTaskInvoker);+ nestedTaskCredentials, lambdaTaskAuthorizer, null, null, apiGatewayTaskInvoker);}AslExecutor(LambdaExecutorService lambdaExecutor, LambdaTargetResolver targetResolver,@@ -319,9 +320,11 @@ public class AslExecutor {CustomResourceLiveness customResourceLiveness,Clock clock, Sleeper sleeper, Integer maxWaitSecondsOverride,RedshiftDataJsonHandler redshiftDataHandler, ServiceRegistry serviceRegistry,- LambdaTaskAuthorizer lambdaTaskAuthorizer, Duration expressMaxExecutionTimeOverride,- LongSupplier nanoTimeOverride, ApiGatewayTaskInvoker apiGatewayTaskInvoker) {+ NestedTaskCredentials nestedTaskCredentials, LambdaTaskAuthorizer lambdaTaskAuthorizer,+ Duration expressMaxExecutionTimeOverride, LongSupplier nanoTimeOverride,+ ApiGatewayTaskInvoker apiGatewayTaskInvoker) {this.apiGatewayTaskInvoker = apiGatewayTaskInvoker;+ this.nestedTaskCredentials = nestedTaskCredentials;this.serviceRegistry = serviceRegistry;this.lambdaTaskAuthorizer = lambdaTaskAuthorizer;this.customResourceLiveness = customResourceLiveness;@@ -383,7 +386,7 @@ public class AslExecutor {ec2Service, s3Service, ecsService, ecsJsonHandler,eventBridgeHandler, schedulerService, schedulerController, rdsDataService,objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,- Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, null, null, null, null, null, null);+ Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, null, null, null, null, null, null, null);}// Kept for tests that do not exercise the Redshift Data API integration.@@ -404,7 +407,7 @@ public class AslExecutor {ec2Service, s3Service, ecsService, ecsJsonHandler,eventBridgeHandler, schedulerService, schedulerController, rdsDataService,objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,- clock, sleeper, maxWaitSecondsOverride, null, null, null, null, null, null);+ clock, sleeper, maxWaitSecondsOverride, null, null, null, null, null, null, null);}AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore,@@ -909,10 +912,11 @@ public class AslExecutor {}JsonNode effectiveInput;- // The role a task's Credentials name is read the way its Parameters or Arguments are, and- // only under IAM enforcement, the one place it is used.+ // Read Credentials for IAM checks and nested account routing.+ boolean nestedTask = NestedTaskCredentials.isNested(StatesIntegration.parse(resource).orElse(null));JsonNode credentials = null;- boolean readCredentials = stateDef.has("Credentials") && iamEnforcementEnabled();+ boolean readCredentials = stateDef.has("Credentials")+ && (iamEnforcementEnabled() || (mockedInvocation == null && nestedTask));if (jsonata) {effectiveInput = input;if (stateDef.has("Arguments")) {@@ -946,13 +950,25 @@ public class AslExecutor {addTaskScheduledEvent(chain, profile, stateDef, effectiveInput, sm);addTaskStartedEvent(chain, profile);try {+ String taskAccount = null;+ if (mockedInvocation == null && credentials != null && nestedTask) {+ taskAccount = nestedTaskCredentials.account(credentials, resource, effectiveInput, sm);+ }+ if (mockedInvocation == null) {+ NestedTaskCredentials.validateTargetAccount(resource, effectiveInput, sm, taskAccount);+ }+ JsonNode resourceInput = effectiveInput;+ String resourceToken = taskToken;taskResult = mockedInvocation != null? mockedTaskResult(mockedInvocation.steps(), stateName, mockedInvocation.responseIndex())- : invokeResource(effectiveResource, effectiveInput, sm, taskToken,+ : RequestScopes.callAsChecked(taskAccount, () -> invokeResource(+ effectiveResource, resourceInput, sm, resourceToken,context.path("Execution").path("Id").asText(null),executionDeadlineNanos, taskDeadlineNanos,jsonata ? null : stateDef.path("Parameters"), credentialsRoleArn,- jobResponse -> addTaskSubmittedEvent(chain, profile, jobResponse));+ jobResponse -> RequestScopes.runAs(+ AwsArnUtils.parse(sm.getStateMachineArn()).accountId(),+ () -> addTaskSubmittedEvent(chain, profile, jobResponse))));if (tokenFuture != null) {taskResult = awaitToken(tokenFuture, stateDef, taskToken, executionDeadlineNanos,taskDeadlineNanos);@@ -5932,7 +5948,8 @@ public class AslExecutor {return false;}try {- return abortedByCaller(sfnService.get().describeExecution(executionArn));+ return RequestScopes.callAs(AwsArnUtils.parse(executionArn).accountId(),+ () -> abortedByCaller(sfnService.get().describeExecution(executionArn)));} catch (AwsException e) {LOG.warnv("Execution {0} vanished while a .sync task was waiting on its job; ending the wait ({1})",executionArn, e.getMessage());diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/NestedTaskCredentials.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/NestedTaskCredentials.javanew file mode 100644index 0000000000..b2e706e556--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/NestedTaskCredentials.java@@ -0,0 +1,104 @@+package io.github.hectorvent.floci.services.stepfunctions;++import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.AwsArnUtils;+import io.github.hectorvent.floci.services.iam.IamService;+import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;++import java.util.Optional;+import java.util.Set;++@ApplicationScoped+public class NestedTaskCredentials {+ private final IamService iam;+ private final EmulatorConfig config;+ private final LambdaTaskAuthorizer authorizer;++ @Inject+ public NestedTaskCredentials(IamService iam, EmulatorConfig config, LambdaTaskAuthorizer authorizer) {+ this.iam = iam;+ this.config = config;+ this.authorizer = authorizer;+ }++ String account(JsonNode credentials, String resource, JsonNode input, StateMachine machine) {+ StatesIntegration integration = StatesIntegration.parse(resource).orElse(null);+ if (!isNested(integration)) {+ throw new AslExecutor.FailStateException("States.Runtime",+ "Task Credentials account routing is supported only for nested executions");+ }+ if (!credentials.isObject() || credentials.size() != 1 || !credentials.path("RoleArn").isTextual()) {+ throw new AslExecutor.FailStateException("States.Runtime",+ "Task Credentials must resolve to an object containing RoleArn");+ }+ String roleArn = credentials.path("RoleArn").asText();+ AwsArnUtils.Arn role;+ try {+ role = AwsArnUtils.parse(roleArn);+ } catch (IllegalArgumentException error) {+ throw new AslExecutor.FailStateException("States.Runtime", "Task Credentials RoleArn is invalid");+ }+ AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());+ if (!"iam".equals(role.service()) || !role.region().isEmpty()+ || !role.resource().startsWith("role/") || !role.accountId().matches("\\d{12}")+ || !role.partition().equals(owner.partition())) {+ throw new AslExecutor.FailStateException("States.Runtime",+ "Task Credentials must name an IAM role in the execution partition");+ }+ String name = role.resource().substring(role.resource().lastIndexOf('/') + 1);+ if (iam.findRole(role.accountId(), name).filter(found -> IamService.roleArnMatches(roleArn, found)).isEmpty()) {+ throw assumptionDenied(machine, roleArn);+ }+ if (config.services().iam().enforcementEnabled()) {+ if (authorizer.assumeRefusal(machine.getRoleArn(), roleArn, machine.getStateMachineArn()).isPresent()) {+ throw assumptionDenied(machine, roleArn);+ }+ validateTargetAccount(resource, input, machine, role.accountId());+ String target = input.path("StateMachineArn").asText(null);+ if (AwsArnUtils.isArn(target)) {+ String action = integration.isSdk("sfn", "startSyncExecution")+ ? "states:StartSyncExecution" : "states:StartExecution";+ Optional<String> refusal = authorizer.refusal(roleArn, action, target);+ if (refusal.isPresent()) {+ throw accessDenied(integration, refusal.get());+ }+ }+ }+ return role.accountId();+ }++ private static AslExecutor.FailStateException assumptionDenied(StateMachine machine, String roleArn) {+ return new AslExecutor.FailStateException("States.TaskFailed",+ "The role " + machine.getRoleArn() + " is not authorized to assume the task state's role, "+ + roleArn + ".");+ }++ static void validateTargetAccount(String resource, JsonNode input, StateMachine machine, String taskAccount) {+ StatesIntegration integration = StatesIntegration.parse(resource).orElse(null);+ String target = input.path("StateMachineArn").asText(null);+ if (!isNested(integration) || !AwsArnUtils.isArn(target)) {+ return;+ }+ String account = taskAccount != null ? taskAccount : AwsArnUtils.parse(machine.getStateMachineArn()).accountId();+ if (!account.equals(AwsArnUtils.parse(target).accountId())) {+ throw accessDenied(integration, "Not authorized to access this resource: " + target);+ }+ }++ private static AslExecutor.FailStateException accessDenied(StatesIntegration integration, String cause) {+ String error = integration.isAnySuffix("states", "startExecution")+ ? "StepFunctions.AWSStepFunctionsException" : "Sfn.SfnException";+ return new AslExecutor.FailStateException(error, cause);+ }++ static boolean isNested(StatesIntegration integration) {+ return integration != null+ && ((integration.isAnySuffix("states", "startExecution")+ && Set.of("", ".sync", ".sync:2").contains(integration.suffix()))+ || integration.isSdk("sfn", "startExecution")+ || integration.isSdk("sfn", "startSyncExecution"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorFixture.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorFixture.javaindex 9a37025279..2fbf220295 100644--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorFixture.java+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorFixture.java@@ -244,7 +244,7 @@ final class AslExecutorFixture {schedulerService, schedulerController, rdsDataService, objectMapper,jsonataEvaluator != null ? jsonataEvaluator : new JsonataEvaluator(objectMapper),sfnService, config, vertx, customResourceLiveness, clock, sleeper, maxWaitSeconds,- redshiftDataHandler, serviceRegistry, lambdaTaskAuthorizer, expressMaxExecutionTime,+ redshiftDataHandler, serviceRegistry, null, lambdaTaskAuthorizer, expressMaxExecutionTime,nanoTime, null);}}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorMockedResponsesTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorMockedResponsesTest.javaindex 832adc3a38..db0735eccd 100644--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorMockedResponsesTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorMockedResponsesTest.java@@ -31,7 +31,7 @@ class AslExecutorMockedResponsesTest {private static final String REGION = "us-east-2";private static final String ACCOUNT = "000000000000";- private static final String UNSUPPORTED_RESOURCE = "arn:aws:states:::apigateway:invoke";+ private static final String UNSUPPORTED_RESOURCE = "arn:aws:states:::unsupported:invoke";private final ObjectMapper objectMapper = new ObjectMapper();private LambdaExecutorService lambdaExecutor;diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/NestedTaskCredentialsTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/NestedTaskCredentialsTest.javanew file mode 100644index 0000000000..ac3825b8c9--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/NestedTaskCredentialsTest.java@@ -0,0 +1,29 @@+package io.github.hectorvent.floci.services.stepfunctions;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.services.iam.IamService;+import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verifyNoInteractions;++class NestedTaskCredentialsTest {+ @ParameterizedTest+ @ValueSource(strings = {"lambda:invoke", "states:startExecution.waitForTaskToken", "aws-sdk:sfn:sendTaskSuccess"})+ void unsupportedIntegrationFailsBeforeRoleLookup(String resource) {+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);+ IamService iam = mock(IamService.class);+ LambdaTaskAuthorizer authorizer = mock(LambdaTaskAuthorizer.class);+ NestedTaskCredentials credentials = new NestedTaskCredentials(iam, config, authorizer);+ assertThrows(AslExecutor.FailStateException.class,+ () -> credentials.account(new ObjectMapper().createObjectNode().put(+ "RoleArn", "arn:aws:iam::000000000222:role/target"),+ "arn:aws:states:::" + resource, new ObjectMapper().createObjectNode(), new StateMachine()));+ verifyNoInteractions(iam, authorizer);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsNestedTaskIamIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsNestedTaskIamIntegrationTest.javanew file mode 100644index 0000000000..23a43cecb5--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsNestedTaskIamIntegrationTest.java@@ -0,0 +1,217 @@+package io.github.hectorvent.floci.services.stepfunctions;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.testing.EnforcementFixtures;+import io.github.hectorvent.floci.testing.IamEnforcementProfile;+import io.github.hectorvent.floci.testing.PartitionCleanup;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.common.http.TestHTTPResource;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.TestProfile;+import io.quarkus.test.junit.mockito.InjectSpy;+import io.restassured.response.Response;+import org.junit.jupiter.api.BeforeAll;+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;+import java.util.Map;+import java.util.UUID;+import java.util.concurrent.TimeUnit;++import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;+import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.junit.jupiter.api.Assertions.fail;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.clearInvocations;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;++@QuarkusTest+@TestProfile(IamEnforcementProfile.class)+class StepFunctionsNestedTaskIamIntegrationTest {+ private static final String SOURCE = "000000000431";+ private static final String TARGET = "000000000432";+ private static final ObjectMapper MAPPER = new ObjectMapper();+ private static final String PASS = """+ {"StartAt":"Done","States":{"Done":{"Type":"Pass","End":true}}}+ """;+ private static final String STATES_TRUST = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole",+ "Principal":{"Service":"states.amazonaws.com"}}]}+ """;++ @TestHTTPResource+ URI baseUri;++ @InjectSpy+ JsonataEvaluator jsonataEvaluator;++ @RegisterExtension+ final PartitionCleanup cleanup = new PartitionCleanup();++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @ParameterizedTest+ @ValueSource(strings = {"states:startExecution", "states:startExecution.sync",+ "states:startExecution.sync:2", "aws-sdk:sfn:startExecution", "aws-sdk:sfn:startSyncExecution"})+ void allowedNestedTasksUseTheAssumedRoleAccount(String integration) throws Exception {+ Fixture fixture = fixture(integration, "allow");+ String execution = start(fixture.parent());+ Response completed = terminal(execution);+ assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());+ if (integration.endsWith("startSyncExecution")) {+ JsonNode output = MAPPER.readTree(completed.jsonPath().getString("output"));+ assertEquals(fixture.child(), output.path("StateMachineArn").asText());+ assertEquals("SUCCEEDED", output.path("Status").asText());+ } else {+ request(TARGET, "ListExecutions", Map.of("stateMachineArn", fixture.child()))+ .then().statusCode(200).body("executions.size()", equalTo(1));+ }+ request(SOURCE, "GetExecutionHistory", Map.of("executionArn", execution))+ .then().statusCode(200);+ request(TARGET, "DescribeExecution", Map.of("executionArn", execution))+ .then().statusCode(400);+ }++ @ParameterizedTest+ @CsvSource({"states:startExecution,assume-deny", "aws-sdk:sfn:startExecution,assume-deny",+ "states:startExecution,trust-deny", "aws-sdk:sfn:startExecution,trust-deny",+ "states:startExecution,start-deny", "aws-sdk:sfn:startExecution,start-deny"})+ void deniedAssumptionOrTaskPermissionsDoNotStartAChild(String integration, String scenario) throws Exception {+ Fixture fixture = fixture(integration, scenario);+ Response completed = terminal(start(fixture.parent()));+ assertEquals("FAILED", completed.jsonPath().getString("status"), completed.asString());+ String expectedError = "start-deny".equals(scenario)+ ? (integration.startsWith("aws-sdk:") ? "Sfn.SfnException" : "StepFunctions.AWSStepFunctionsException")+ : "States.TaskFailed";+ assertEquals(expectedError, completed.jsonPath().getString("error"), completed.asString());+ if ("start-deny".equals(scenario)) {+ assertTrue(completed.jsonPath().getString("cause").contains("states:StartExecution"), completed.asString());+ } else {+ assertEquals("The role " + fixture.executionRole()+ + " is not authorized to assume the task state's role, " + fixture.taskRole() + ".",+ completed.jsonPath().getString("cause"));+ }+ request(TARGET, "ListExecutions", Map.of("stateMachineArn", fixture.child()))+ .then().statusCode(200).body("executions.size()", equalTo(0));+ }++ @ParameterizedTest+ @ValueSource(strings = {"states:startExecution", "aws-sdk:sfn:startExecution"})+ void jsonataTaskCredentialsAreResolvedOnce(String integration) throws Exception {+ Fixture fixture = fixture(integration, "allow");+ String definition = MAPPER.writeValueAsString(Map.of(+ "QueryLanguage", "JSONata", "StartAt", "Child", "States", Map.of("Child", Map.of(+ "Type", "Task", "Resource", "arn:aws:states:::" + integration,+ "Credentials", Map.of("RoleArn", "{% $states.input.role %}"),+ "Arguments", Map.of("StateMachineArn", fixture.child(), "Input", Map.of()),+ "End", true))));+ request(SOURCE, "UpdateStateMachine", Map.of(+ "stateMachineArn", fixture.parent(), "definition", definition)).then().statusCode(200);+ clearInvocations(jsonataEvaluator);++ Response started = request(SOURCE, "StartExecution", Map.of(+ "stateMachineArn", fixture.parent(),+ "input", MAPPER.writeValueAsString(Map.of("role", fixture.taskRole()))));+ started.then().statusCode(200);+ Response completed = terminal(started.jsonPath().getString("executionArn"));++ assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());+ verify(jsonataEvaluator, times(1)).resolveTemplate(any(), eq("Credentials"), any(), any());+ request(TARGET, "ListExecutions", Map.of("stateMachineArn", fixture.child()))+ .then().statusCode(200).body("executions.size()", equalTo(1));+ }++ private Fixture fixture(String integration, String scenario) throws Exception {+ String executionRole = role(SOURCE, STATES_TRUST, """+ {"Version":"2012-10-17","Statement":[{"Effect":"%s","Action":"sts:AssumeRole","Resource":"*"}]}+ """.formatted("assume-deny".equals(scenario) ? "Deny" : "Allow"));+ String childRole = role(TARGET, STATES_TRUST, """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"states:*","Resource":"*"}]}+ """);+ String child = machine(TARGET, PASS,+ integration.endsWith("startSyncExecution") ? "EXPRESS" : "STANDARD", childRole);+ String trust = "trust-deny".equals(scenario) ? """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole",+ "Principal":{"Service":"lambda.amazonaws.com"}}]}+ """ : """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole",+ "Principal":{"AWS":"arn:aws:iam::%s:root"},+ "Condition":{"ArnEquals":{"aws:PrincipalArn":"%s"}}}]}+ """.formatted(SOURCE, executionRole);+ String taskRole = role(TARGET, trust, """+ {"Version":"2012-10-17","Statement":[{"Effect":"%s","Action":"states:*","Resource":"*"}]}+ """.formatted("start-deny".equals(scenario) ? "Deny" : "Allow"));+ String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Child", "States", Map.of("Child", Map.of(+ "Type", "Task", "Resource", "arn:aws:states:::" + integration,+ "Credentials", Map.of("RoleArn", taskRole),+ "Parameters", Map.of("StateMachineArn", child, "Input", Map.of()), "End", true))));+ return new Fixture(machine(SOURCE, definition, "STANDARD", executionRole), child, executionRole, taskRole);+ }++ private String role(String account, String trust, String policy) {+ return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), account, "/",+ "nested-iam-" + UUID.randomUUID(), trust, policy);+ }++ private String machine(String account, String definition, String type, String role) {+ String name = "nested-iam-" + UUID.randomUUID();+ String arn = "arn:aws:states:us-east-1:" + account + ":stateMachine:" + name;+ cleanup.register(() -> {+ Response executions = request(account, "ListExecutions", Map.of("stateMachineArn", arn));+ if (executions.statusCode() == 200) {+ for (Map<String, String> execution : executions.jsonPath().<Map<String, String>>getList("executions")) {+ if ("RUNNING".equals(execution.get("status"))) {+ request(account, "StopExecution", Map.of("executionArn", execution.get("executionArn")))+ .then().statusCode(200);+ }+ }+ }+ request(account, "DeleteStateMachine", Map.of("stateMachineArn", arn)).then().statusCode(200);+ });+ Response created = request(account, "CreateStateMachine", Map.of(+ "name", name, "definition", definition, "type", type, "roleArn", role));+ created.then().statusCode(200);+ return created.jsonPath().getString("stateMachineArn");+ }++ private String start(String machine) {+ Response started = request(SOURCE, "StartExecution", Map.of("stateMachineArn", machine, "input", "{}"));+ started.then().statusCode(200);+ return started.jsonPath().getString("executionArn");+ }++ private Response terminal(String execution) throws Exception {+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);+ do {+ Response response = request(SOURCE, "DescribeExecution", Map.of("executionArn", execution));+ response.then().statusCode(200);+ if (!"RUNNING".equals(response.jsonPath().getString("status"))) {+ return response;+ }+ Thread.sleep(25);+ } while (System.nanoTime() < deadline);+ fail("Execution did not terminate: " + execution);+ return null;+ }++ private Response request(String account, String action, Map<String, ?> input) {+ return given().port(baseUri.getPort()).header("Authorization", auth(account, "states"))+ .header("X-Amz-Target", "AWSStepFunctions." + action)+ .contentType("application/x-amz-json-1.0").body(MAPPER.valueToTree(input).toString()).post("/");+ }++ private record Fixture(String parent, String child, String executionRole, String taskRole) {+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.javanew file mode 100644index 0000000000..082bc1ca0f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java@@ -0,0 +1,336 @@+package io.github.hectorvent.floci.services.stepfunctions;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.services.lambda.LambdaExecutorService;+import io.github.hectorvent.floci.services.lambda.model.InvokeResult;+import io.github.hectorvent.floci.testing.EnforcementFixtures;+import io.github.hectorvent.floci.testing.PartitionCleanup;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.InjectMock;+import io.quarkus.test.common.http.TestHTTPResource;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.mockito.InjectSpy;+import io.restassured.response.Response;+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.ValueSource;++import java.net.URI;+import java.nio.charset.StandardCharsets;+import java.util.Map;+import java.util.UUID;++import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;+import static io.restassured.RestAssured.given;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.junit.jupiter.api.Assertions.fail;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.argThat;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.clearInvocations;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++@QuarkusTest+class StepFunctionsTaskCredentialsIntegrationTest {+ private static final String SOURCE = "000000000331";+ private static final String TARGET = "000000000332";+ private static final ObjectMapper MAPPER = new ObjectMapper();+ private static final String PASS = """+ {"StartAt":"Done","States":{"Done":{"Type":"Pass","End":true}}}+ """;++ @TestHTTPResource+ URI baseUri;++ @InjectMock+ LambdaExecutorService lambdaExecutor;++ @InjectSpy+ JsonataEvaluator jsonataEvaluator;++ @RegisterExtension+ final PartitionCleanup cleanup = new PartitionCleanup();++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @ParameterizedTest+ @ValueSource(strings = {"states:startExecution", "states:startExecution.sync",+ "states:startExecution.sync:2", "aws-sdk:sfn:startExecution", "aws-sdk:sfn:startSyncExecution"})+ void nestedTaskUsesRoleAccountAndRestoresParentAccount(String resource) throws Exception {+ String child = machine(TARGET, PASS, resource.endsWith("startSyncExecution") ? "EXPRESS" : "STANDARD");+ String ownChild = machine(SOURCE, PASS, "STANDARD");+ ObjectNode definition = definition(child, resource, role());+ ObjectNode task = (ObjectNode) definition.path("States").path("Child");+ task.remove("End");+ task.put("Next", "OwnChild");+ task.put("ResultPath", "$.child");+ ((ObjectNode) definition.path("States")).set("OwnChild", MAPPER.readTree("""+ {"Type":"Task","Resource":"arn:aws:states:::states:startExecution.sync:2",+ "Parameters":{"StateMachineArn":"%s","Input":{"restored":true}},"End":true}+ """.formatted(ownChild)));+ String parent = machine(SOURCE, definition.toString(), "STANDARD");+ String execution = start(parent, "{}");+ Response done = terminal(SOURCE, execution);+ assertEquals("SUCCEEDED", done.jsonPath().getString("status"), done.asString());+ JsonNode output = MAPPER.readTree(done.jsonPath().getString("output"));+ assertEquals(true, output.path("Output").path("restored").asBoolean());+ request(TARGET, "DescribeExecution", Map.of("executionArn", execution)).then().statusCode(400);+ Response history = request(SOURCE, "GetExecutionHistory", Map.of("executionArn", execution));+ history.then().statusCode(200);+ assertTrue(history.asString().contains(child), history.asString());+ assertTrue(history.asString().contains("ExecutionSucceeded"), history.asString());+ }++ @Test+ void dynamicRoleUsesInputPathBeforeParameters() throws Exception {+ String child = machine(TARGET, PASS, "STANDARD");+ String taskRole = role();+ ObjectNode definition = definition(child, "states:startExecution.sync:2", taskRole);+ ObjectNode task = (ObjectNode) definition.path("States").path("Child");+ task.put("InputPath", "$.selected");+ task.set("Credentials", MAPPER.valueToTree(Map.of("RoleArn.$", "$.role")));+ String input = MAPPER.writeValueAsString(Map.of("selected", Map.of("role", taskRole)));+ String execution = start(machine(SOURCE, definition.toString(), "STANDARD"), input);+ Response done = terminal(SOURCE, execution);+ assertEquals("SUCCEEDED", done.jsonPath().getString("status"), done.asString());+ }++ @Test+ void jsonataRoleUsesOriginalStateInput() throws Exception {+ String child = machine(TARGET, PASS, "STANDARD");+ ObjectNode definition = definition(child, "states:startExecution.sync:2", role());+ definition.put("QueryLanguage", "JSONata");+ ObjectNode task = (ObjectNode) definition.path("States").path("Child");+ task.set("Arguments", task.remove("Parameters"));+ task.set("Credentials", MAPPER.valueToTree(Map.of("RoleArn", "{% $states.input.role %}")));+ String parent = machine(SOURCE, definition.toString(), "STANDARD");+ clearInvocations(jsonataEvaluator);+ Response done = terminal(SOURCE, start(parent,+ MAPPER.writeValueAsString(Map.of("role", role()))));+ assertEquals("SUCCEEDED", done.jsonPath().getString("status"), done.asString());+ verify(jsonataEvaluator, times(1)).resolveTemplate(any(), eq("Credentials"), any(), any());+ }++ @ParameterizedTest+ @ValueSource(strings = {"states:startExecution", "states:startExecution.sync", "states:startExecution.sync:2",+ "aws-sdk:sfn:startExecution", "aws-sdk:sfn:startSyncExecution"})+ void foreignArnAloneDoesNotGrantAccountAccess(String resource) throws Exception {+ String child = machine(TARGET, PASS, resource.endsWith("startSyncExecution") ? "EXPRESS" : "STANDARD");+ ObjectNode definition = definition(child, resource, role());+ ((ObjectNode) definition.path("States").path("Child")).remove("Credentials");+ Response done = terminal(SOURCE, start(machine(SOURCE, definition.toString(), "STANDARD"), "{}"));+ assertEquals("FAILED", done.jsonPath().getString("status"), done.asString());+ assertEquals(resource.startsWith("aws-sdk:") ? "Sfn.SfnException" : "StepFunctions.AWSStepFunctionsException",+ done.jsonPath().getString("error"));+ }++ @ParameterizedTest+ @ValueSource(strings = {"missing", "wrong-path", "foreign-partition", "invalid-arn"})+ void invalidCredentialsCannotStartChild(String invalid) throws Exception {+ String existing = role();+ String value = switch (invalid) {+ case "missing" -> existing + "-missing";+ case "wrong-path" -> existing.replace(":role/", ":role/different/");+ case "foreign-partition" -> existing.replace("arn:aws:", "arn:aws-cn:");+ default -> "not-an-arn";+ };+ String child = machine(TARGET, PASS, "STANDARD");+ ObjectNode definition = definition(child, "states:startExecution.sync:2", value);+ Response done = terminal(SOURCE, start(machine(SOURCE, definition.toString(), "STANDARD"), "{}"));+ assertEquals("FAILED", done.jsonPath().getString("status"), done.asString());+ if ("missing".equals(invalid) || "wrong-path".equals(invalid)) {+ assertEquals("States.TaskFailed", done.jsonPath().getString("error"));+ } else {+ assertEquals("States.Runtime", done.jsonPath().getString("error"));+ }+ request(TARGET, "ListExecutions", Map.of("stateMachineArn", child)).then()+ .statusCode(200).body("executions.size()", org.hamcrest.Matchers.equalTo(0));+ }++ @ParameterizedTest+ @ValueSource(strings = {"missing-role", "extra-member", "non-object", "null-role", "numeric-role"})+ void malformedCredentialsCannotStartChild(String invalid) throws Exception {+ String taskRole = role();+ JsonNode credentials = switch (invalid) {+ case "missing-role" -> MAPPER.createObjectNode();+ case "extra-member" -> MAPPER.valueToTree(Map.of("RoleArn", taskRole, "Extra", true));+ case "non-object" -> MAPPER.createArrayNode().add(taskRole);+ case "null-role" -> MAPPER.readTree("{\"RoleArn\":null}");+ default -> MAPPER.valueToTree(Map.of("RoleArn", 42));+ };+ String child = machine(TARGET, PASS, "STANDARD");+ ObjectNode definition = definition(child, "states:startExecution.sync:2", taskRole);+ ((ObjectNode) definition.path("States").path("Child")).set("Credentials", credentials);+ Response done = terminal(SOURCE, start(machine(SOURCE, definition.toString(), "STANDARD"), "{}"));+ assertEquals("FAILED", done.jsonPath().getString("status"), done.asString());+ assertEquals("States.Runtime", done.jsonPath().getString("error"));+ assertEquals("Task Credentials must resolve to an object containing RoleArn",+ done.jsonPath().getString("cause"));+ request(TARGET, "ListExecutions", Map.of("stateMachineArn", child)).then()+ .statusCode(200).body("executions.size()", org.hamcrest.Matchers.equalTo(0));+ }++ @ParameterizedTest+ @ValueSource(strings = {"direct", "optimized"})+ void lambdaCredentialsRetainDefaultIamDisabledBehavior(String integration) throws Exception {+ String name = "credentials-worker-" + UUID.randomUUID();+ String function = "arn:aws:lambda:us-east-1:" + SOURCE + ":function:" + name;+ cleanup.register(() -> given().port(baseUri.getPort()).header("Authorization", auth(SOURCE, "lambda"))+ .delete("/2015-03-31/functions/{name}", name).then().statusCode(204));+ given().port(baseUri.getPort()).header("Authorization", auth(SOURCE, "lambda"))+ .contentType("application/json").body(Map.of(+ "FunctionName", name, "Runtime", "nodejs20.x", "Handler", "index.handler",+ "Role", "arn:aws:iam::" + SOURCE + ":role/lambda-role"))+ .post("/2015-03-31/functions").then().statusCode(201);+ when(lambdaExecutor.invoke(any(), any(), any())).thenReturn(+ new InvokeResult(200, null, "{\"ok\":true}".getBytes(StandardCharsets.UTF_8), null, "req"));+ ObjectNode definition = definition(function, "lambda:invoke", role());+ ObjectNode task = (ObjectNode) definition.path("States").path("Child");+ if ("direct".equals(integration)) {+ task.put("Resource", function);+ task.set("Parameters", MAPPER.createObjectNode());+ } else {+ task.set("Parameters", MAPPER.valueToTree(Map.of("FunctionName", function)));+ }+ Response done = terminal(SOURCE, start(machine(SOURCE, definition.toString(), "STANDARD"), "{}"));+ assertEquals("SUCCEEDED", done.jsonPath().getString("status"), done.asString());+ assertTrue(done.jsonPath().getString("output").contains("\"ok\":true"), done.asString());+ verify(lambdaExecutor).invoke(argThat(fn -> fn != null && function.equals(fn.getFunctionArn())), any(), any());+ }++ @Test+ void childFailureIsCaughtInParentAccount() throws Exception {+ String child = machine(TARGET, """+ {"StartAt":"Fail","States":{"Fail":{"Type":"Fail","Error":"ChildFailure"}}}+ """, "STANDARD");+ ObjectNode definition = definition(child, "states:startExecution.sync:2", role());+ ((ObjectNode) definition.path("States").path("Child")).set("Catch",+ MAPPER.readTree("[{\"ErrorEquals\":[\"States.TaskFailed\"],\"Next\":\"Recovered\"}]"));+ ((ObjectNode) definition.path("States")).set("Recovered",+ MAPPER.readTree("{\"Type\":\"Pass\",\"End\":true}"));+ Response done = terminal(SOURCE, start(machine(SOURCE, definition.toString(), "STANDARD"), "{}"));+ assertEquals("SUCCEEDED", done.jsonPath().getString("status"), done.asString());+ assertTrue(done.jsonPath().getString("output").contains("ChildFailure"), done.asString());+ }++ @Test+ void stoppingParentStopsForeignChild() throws Exception {+ String child = machine(TARGET, """+ {"StartAt":"Wait","States":{"Wait":{"Type":"Wait","Seconds":60,"End":true}}}+ """, "STANDARD");+ String parent = machine(SOURCE, definition(child, "states:startExecution.sync:2", role()).toString(),+ "STANDARD");+ String execution = start(parent, "{}");+ String childExecution = null;+ for (int i = 0; i < 100; i++) {+ Response history = request(SOURCE, "GetExecutionHistory", Map.of("executionArn", execution));+ history.then().statusCode(200);+ for (JsonNode event : MAPPER.readTree(history.asString()).path("events")) {+ if ("TaskSubmitted".equals(event.path("type").asText())) {+ childExecution = MAPPER.readTree(event.path("taskSubmittedEventDetails").path("output").asText())+ .path("ExecutionArn").asText();+ }+ }+ if (childExecution != null) {+ break;+ }+ Thread.sleep(50);+ }+ assertTrue(childExecution != null && childExecution.contains(TARGET));+ request(SOURCE, "StopExecution", Map.of("executionArn", execution)).then().statusCode(200);+ assertEquals("ABORTED", terminal(TARGET, childExecution).jsonPath().getString("status"));+ assertEquals("ABORTED", terminal(SOURCE, execution).jsonPath().getString("status"));+ }++ @Test+ void taskTimeoutStopsForeignChild() throws Exception {+ String child = machine(TARGET, """+ {"StartAt":"Wait","States":{"Wait":{"Type":"Wait","Seconds":60,"End":true}}}+ """, "STANDARD");+ ObjectNode definition = definition(child, "states:startExecution.sync:2", role());+ ((ObjectNode) definition.path("States").path("Child")).put("TimeoutSeconds", 1);+ Response done = terminal(SOURCE, start(machine(SOURCE, definition.toString(), "STANDARD"), "{}"));+ assertEquals("FAILED", done.jsonPath().getString("status"), done.asString());+ assertEquals("States.Timeout", done.jsonPath().getString("error"));+ Response children = request(TARGET, "ListExecutions", Map.of("stateMachineArn", child));+ children.then().statusCode(200).body("executions.size()", org.hamcrest.Matchers.equalTo(1));+ String execution = children.jsonPath().getString("executions[0].executionArn");+ assertEquals("ABORTED", terminal(TARGET, execution).jsonPath().getString("status"));+ }++ private static ObjectNode definition(String child, String resource, String role) throws Exception {+ return (ObjectNode) MAPPER.readTree("""+ {"StartAt":"Child","States":{"Child":{"Type":"Task","Resource":"arn:aws:states:::%s",+ "Credentials":{"RoleArn":"%s"},"Parameters":{"StateMachineArn":"%s","Input":{}},"End":true}}}+ """.formatted(resource, role, child));+ }++ private String role() {+ String name = "nested-" + UUID.randomUUID();+ return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), TARGET, "/", name, """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole",+ "Principal":{"AWS":"arn:aws:iam::%s:root"}}]}+ """.formatted(SOURCE), """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",+ "Action":"states:StartExecution","Resource":"*"}]}+ """);+ }++ private String machine(String account, String definition, String type) throws Exception {+ String name = "credentials-" + UUID.randomUUID();+ String arn = "arn:aws:states:us-east-1:" + account + ":stateMachine:" + name;+ cleanup.register(() -> removeMachine(account, arn));+ Response response = request(account, "CreateStateMachine", Map.of(+ "name", name, "definition", definition,+ "type", type, "roleArn", "arn:aws:iam::" + account + ":role/execution"));+ response.then().statusCode(200);+ return response.jsonPath().getString("stateMachineArn");+ }++ private void removeMachine(String account, String arn) {+ Response executions = request(account, "ListExecutions", Map.of("stateMachineArn", arn));+ executions.then().statusCode(200);+ for (Map<String, String> execution : executions.jsonPath().<Map<String, String>>getList("executions")) {+ if ("RUNNING".equals(execution.get("status"))) {+ request(account, "StopExecution", Map.of("executionArn", execution.get("executionArn")))+ .then().statusCode(200);+ }+ }+ request(account, "DeleteStateMachine", Map.of("stateMachineArn", arn)).then().statusCode(200);+ }++ private String start(String machine, String input) throws Exception {+ Response response = request(SOURCE, "StartExecution", Map.of("stateMachineArn", machine, "input", input));+ response.then().statusCode(200);+ return response.jsonPath().getString("executionArn");+ }++ private Response terminal(String account, String execution) throws Exception {+ for (int i = 0; i < 100; i++) {+ Response response = request(account, "DescribeExecution", Map.of("executionArn", execution));+ response.then().statusCode(200);+ if (!"RUNNING".equals(response.jsonPath().getString("status"))) {+ return response;+ }+ Thread.sleep(50);+ }+ fail("Execution did not terminate: " + execution);+ return null;+ }++ private Response request(String account, String action, Map<String, ?> input) {+ return given().port(baseUri.getPort()).header("Authorization", auth(account, "states"))+ .header("X-Amz-Target", "AWSStepFunctions." + action)+ .contentType("application/x-amz-json-1.0").body(MAPPER.valueToTree(input).toString()).post("/");+ }+}