Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(stepfunctions): run executions under the execution's account (#1566)

Alex Bannaf558472a4da4
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java
index 5175ee2461..780409afeb 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
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.stepfunctions;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
+import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
@@ -23,6 +24,9 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.quarkus.arc.Arc;
+import io.quarkus.arc.ArcContainer;
+import io.quarkus.arc.ManagedContext;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
@@ -37,6 +41,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
+import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
@@ -96,7 +101,7 @@ public class AslExecutor {
*/
public void executeAsync(StateMachine sm, Execution exec, List<HistoryEvent> history,
BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
- executor.submit(() -> doExecute(sm, exec, history, onUpdate));
+ executor.submit(() -> runUnderExecutionAccount(sm, () -> doExecute(sm, exec, history, onUpdate)));
}
/**
@@ -105,7 +110,8 @@ public class AslExecutor {
public void executeSync(StateMachine sm, Execution exec, List<HistoryEvent> history,
BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
try {
- Future<?> f = executor.submit(() -> doExecute(sm, exec, history, onUpdate));
+ Future<?> f = executor.submit(() ->
+ runUnderExecutionAccount(sm, () -> doExecute(sm, exec, history, onUpdate)));
f.get(300, TimeUnit.SECONDS);
} catch (java.util.concurrent.TimeoutException e) {
exec.setStatus("TIMED_OUT");
@@ -116,6 +122,68 @@ public class AslExecutor {
}
}
+ /**
+ * Runs {@code body} on this worker thread under a CDI request scope whose account is
+ * the one encoded in the state machine ARN, so service integrations (Lambda, DynamoDB,
+ * SQS, ECS, …) and the execution-store writes resolve to the execution's account rather
+ * than the configured default. Without this, an execution started under account B would
+ * have its integrations run against account A's resources.
+ *
+ * <p>Mirrors {@code CurEmissionScheduler#runUnderAccount}. Falls back to running the body
+ * directly when Arc is not running (e.g. plain unit tests that construct AslExecutor
+ * without a CDI container).
+ */
+ private void runUnderExecutionAccount(StateMachine sm, Runnable body) {
+ try {
+ callUnderExecutionAccount(sm, () -> {
+ body.run();
+ return null;
+ });
+ } catch (RuntimeException | Error e) {
+ throw e;
+ } catch (Exception e) {
+ // A Runnable cannot throw a checked exception, so this is unreachable in practice;
+ // wrap defensively to preserve the void signature.
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Callable variant of {@link #runUnderExecutionAccount} that returns the body's result. Used to
+ * run Parallel branches on their own worker threads under the execution's account: the request
+ * scope (and thus {@link RequestContext}) is thread-bound, so a branch submitted to the executor
+ * pool would otherwise run with no active scope and resolve its Task integrations against the
+ * default account instead of the execution's. Each branch thread therefore activates its own
+ * scope here, mirroring how {@link #executeAsync}/{@link #executeSync} wrap {@code doExecute}.
+ */
+ private <T> T callUnderExecutionAccount(StateMachine sm, Callable<T> body) throws Exception {
+ String accountId = AwsArnUtils.accountOrDefault(sm.getStateMachineArn(), null);
+ ArcContainer container = Arc.container();
+ if (accountId == null || accountId.isBlank() || container == null || !container.isRunning()) {
+ return body.call();
+ }
+ ManagedContext requestContext = container.requestContext();
+ boolean alreadyActive = requestContext.isActive();
+ if (!alreadyActive) {
+ requestContext.activate();
+ }
+ // Execution runs on a background worker that normally has no active scope. If it did run
+ // inside an already-active scope, restore its previous account afterwards so we don't leave
+ // the execution's account behind on a reused thread.
+ RequestContext ctx = container.instance(RequestContext.class).get();
+ String previousAccountId = alreadyActive ? ctx.getAccountId() : null;
+ try {
+ ctx.setAccountId(accountId);
+ return body.call();
+ } finally {
+ if (!alreadyActive) {
+ requestContext.terminate();
+ } else {
+ ctx.setAccountId(previousAccountId);
+ }
+ }
+ }
+
private void doExecute(StateMachine sm, Execution exec, List<HistoryEvent> history,
BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
try {
@@ -963,7 +1031,11 @@ public class AslExecutor {
JsonNode branchStates = branch.path("States");
JsonNode capturedInput = input;
- futures.add(executor.submit(() -> executeBranch(startAt, branchStates, capturedInput, sm, topLevelQueryLanguage, context)));
+ // Run each branch on its own worker thread under the execution's account: the request
+ // scope is thread-bound, so without this a branch's Task integrations would resolve to
+ // the default account rather than the execution's.
+ futures.add(executor.submit(() -> callUnderExecutionAccount(sm,
+ () -> executeBranch(startAt, branchStates, capturedInput, sm, topLevelQueryLanguage, context))));
}
int timeoutSeconds = stateDef.path("TimeoutSeconds").asInt(0);
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsAccountContextIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsAccountContextIntegrationTest.java
new file mode 100644
index 0000000000..41df6a0f1f
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsAccountContextIntegrationTest.java
@@ -0,0 +1,273 @@
+package io.github.hectorvent.floci.services.stepfunctions;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.Response;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Verifies that a Step Functions execution started under a specific account runs its
+ * service integrations (and execution-store writes) under that same account — not the
+ * configured default — by exercising the optimized {@code dynamodb:putItem} integration
+ * against a table that exists only in the execution's account.
+ *
+ * <p>Without account propagation on the executor's worker thread, the integration would
+ * resolve to the default account, fail to find the table, and the execution would FAIL.
+ */
+@QuarkusTest
+class StepFunctionsAccountContextIntegrationTest {
+
+ private static final String SFN_CT = "application/x-amz-json-1.0";
+ private static final String DDB_CT = "application/x-amz-json-1.0";
+ private static final String ACCOUNT = "000000000111";
+ private static final String OTHER_ACCOUNT = "000000000222";
+ private static final String TABLE = "sfn-acct-ctx-table";
+ private static final String PARALLEL_TABLE = "sfn-acct-ctx-parallel-table";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ private static String auth(String account, String service) {
+ return "AWS4-HMAC-SHA256 Credential=" + account
+ + "/20260101/us-east-1/" + service + "/aws4_request, SignedHeaders=host, Signature=abc";
+ }
+
+ @Test
+ void executionRunsUnderItsOwnAccount() throws Exception {
+ // 1. Account ACCOUNT creates a DynamoDB table (exists only in this account).
+ given()
+ .header("Authorization", auth(ACCOUNT, "dynamodb"))
+ .header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
+ .contentType(DDB_CT)
+ .body("""
+ {
+ "TableName": "%s",
+ "AttributeDefinitions": [{"AttributeName": "id", "AttributeType": "S"}],
+ "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}],
+ "BillingMode": "PAY_PER_REQUEST"
+ }
+ """.formatted(TABLE))
+ .when().post("/")
+ .then().statusCode(200);
+
+ // 2. Account ACCOUNT creates a state machine that writes to that table.
+ String definition = """
+ {
+ "StartAt": "Put",
+ "States": {
+ "Put": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::dynamodb:putItem",
+ "Parameters": {
+ "TableName": "%s",
+ "Item": { "id": {"S": "k1"}, "v": {"S": "hello"} }
+ },
+ "End": true
+ }
+ }
+ }
+ """.formatted(TABLE);
+
+ Response create = given()
+ .header("Authorization", auth(ACCOUNT, "states"))
+ .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
+ .contentType(SFN_CT)
+ .body("""
+ { "name": "acct-ctx-sm-%s", "definition": %s, "roleArn": "arn:aws:iam::%s:role/sfn" }
+ """.formatted(System.currentTimeMillis(), quote(definition), ACCOUNT))
+ .when().post("/");
+ create.then().statusCode(200);
+ String smArn = create.jsonPath().getString("stateMachineArn");
+ // The state machine ARN must carry the caller's account.
+ assertTrue(smArn.contains(ACCOUNT), "SM ARN should embed the caller account: " + smArn);
+
+ // 3. Account ACCOUNT starts the execution.
+ Response start = given()
+ .header("Authorization", auth(ACCOUNT, "states"))
+ .header("X-Amz-Target", "AWSStepFunctions.StartExecution")
+ .contentType(SFN_CT)
+ .body("""
+ { "stateMachineArn": "%s", "input": "{}" }
+ """.formatted(smArn))
+ .when().post("/");
+ start.then().statusCode(200);
+ String execArn = start.jsonPath().getString("executionArn");
+
+ // 4. The execution must SUCCEED — the integration found ACCOUNT's table.
+ String status = waitForTerminal(execArn);
+ assertEquals("SUCCEEDED", status, "execution should run under " + ACCOUNT + " and find the table");
+
+ // 5. The item landed in ACCOUNT's table.
+ given()
+ .header("Authorization", auth(ACCOUNT, "dynamodb"))
+ .header("X-Amz-Target", "DynamoDB_20120810.GetItem")
+ .contentType(DDB_CT)
+ .body("""
+ { "TableName": "%s", "Key": { "id": {"S": "k1"} } }
+ """.formatted(TABLE))
+ .when().post("/")
+ .then().statusCode(200)
+ .body("Item.v.S", org.hamcrest.Matchers.equalTo("hello"));
+
+ // 6. Isolation: a different account has no such table at all.
+ given()
+ .header("Authorization", auth(OTHER_ACCOUNT, "dynamodb"))
+ .header("X-Amz-Target", "DynamoDB_20120810.GetItem")
+ .contentType(DDB_CT)
+ .body("""
+ { "TableName": "%s", "Key": { "id": {"S": "k1"} } }
+ """.formatted(TABLE))
+ .when().post("/")
+ .then().statusCode(400);
+ }
+
+ @Test
+ void executionRunsParallelBranchesUnderItsOwnAccount() throws Exception {
+ // Parallel branches run on the executor's worker threads, where the request scope is NOT
+ // inherited from the parent. Without per-branch account propagation, each branch's putItem
+ // would resolve to the default account, miss ACCOUNT's table, and the execution would FAIL.
+
+ // 1. Account ACCOUNT creates a table that exists only in this account.
+ given()
+ .header("Authorization", auth(ACCOUNT, "dynamodb"))
+ .header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
+ .contentType(DDB_CT)
+ .body("""
+ {
+ "TableName": "%s",
+ "AttributeDefinitions": [{"AttributeName": "id", "AttributeType": "S"}],
+ "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}],
+ "BillingMode": "PAY_PER_REQUEST"
+ }
+ """.formatted(PARALLEL_TABLE))
+ .when().post("/")
+ .then().statusCode(200);
+
+ // 2. A state machine whose Parallel state has two branches, each writing to that table.
+ String definition = """
+ {
+ "StartAt": "Fan",
+ "States": {
+ "Fan": {
+ "Type": "Parallel",
+ "End": true,
+ "Branches": [
+ {
+ "StartAt": "PutA",
+ "States": {
+ "PutA": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::dynamodb:putItem",
+ "Parameters": { "TableName": "%1$s", "Item": { "id": {"S": "a"}, "v": {"S": "A"} } },
+ "End": true
+ }
+ }
+ },
+ {
+ "StartAt": "PutB",
+ "States": {
+ "PutB": {
+ "Type": "Task",
+ "Resource": "arn:aws:states:::dynamodb:putItem",
+ "Parameters": { "TableName": "%1$s", "Item": { "id": {"S": "b"}, "v": {"S": "B"} } },
+ "End": true
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ """.formatted(PARALLEL_TABLE);
+
+ Response create = given()
+ .header("Authorization", auth(ACCOUNT, "states"))
+ .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
+ .contentType(SFN_CT)
+ .body("""
+ { "name": "acct-ctx-par-sm-%s", "definition": %s, "roleArn": "arn:aws:iam::%s:role/sfn" }
+ """.formatted(System.currentTimeMillis(), quote(definition), ACCOUNT))
+ .when().post("/");
+ create.then().statusCode(200);
+ String smArn = create.jsonPath().getString("stateMachineArn");
+ assertTrue(smArn.contains(ACCOUNT), "SM ARN should embed the caller account: " + smArn);
+
+ // 3. Start the execution under ACCOUNT.
+ Response start = given()
+ .header("Authorization", auth(ACCOUNT, "states"))
+ .header("X-Amz-Target", "AWSStepFunctions.StartExecution")
+ .contentType(SFN_CT)
+ .body("""
+ { "stateMachineArn": "%s", "input": "{}" }
+ """.formatted(smArn))
+ .when().post("/");
+ start.then().statusCode(200);
+ String execArn = start.jsonPath().getString("executionArn");
+
+ // 4. The execution must SUCCEED — both branches found ACCOUNT's table.
+ String status = waitForTerminal(execArn);
+ assertEquals("SUCCEEDED", status,
+ "parallel branches should run under " + ACCOUNT + " and find the table");
+
+ // 5. Both branch writes landed in ACCOUNT's table.
+ given()
+ .header("Authorization", auth(ACCOUNT, "dynamodb"))
+ .header("X-Amz-Target", "DynamoDB_20120810.GetItem")
+ .contentType(DDB_CT)
+ .body("""
+ { "TableName": "%s", "Key": { "id": {"S": "a"} } }
+ """.formatted(PARALLEL_TABLE))
+ .when().post("/")
+ .then().statusCode(200)
+ .body("Item.v.S", org.hamcrest.Matchers.equalTo("A"));
+ given()
+ .header("Authorization", auth(ACCOUNT, "dynamodb"))
+ .header("X-Amz-Target", "DynamoDB_20120810.GetItem")
+ .contentType(DDB_CT)
+ .body("""
+ { "TableName": "%s", "Key": { "id": {"S": "b"} } }
+ """.formatted(PARALLEL_TABLE))
+ .when().post("/")
+ .then().statusCode(200)
+ .body("Item.v.S", org.hamcrest.Matchers.equalTo("B"));
+ }
+
+ private String waitForTerminal(String execArn) throws InterruptedException {
+ for (int i = 0; i < 80; i++) {
+ Response resp = given()
+ .header("Authorization", auth(ACCOUNT, "states"))
+ .header("X-Amz-Target", "AWSStepFunctions.DescribeExecution")
+ .contentType(SFN_CT)
+ .body("""
+ {"executionArn": "%s"}
+ """.formatted(execArn))
+ .when().post("/");
+ String status = resp.jsonPath().getString("status");
+ if (!"RUNNING".equals(status)) {
+ if ("FAILED".equals(status) || "ABORTED".equals(status)) {
+ fail("Execution " + status + ": " + resp.body().asString());
+ }
+ return status;
+ }
+ Thread.sleep(100);
+ }
+ fail("Execution did not complete within timeout");
+ return null;
+ }
+
+ private static String quote(String raw) {
+ return "\"" + raw
+ .replace("\\", "\\\\")
+ .replace("\"", "\\\"")
+ .replace("\n", "\\n")
+ .replace("\r", "\\r")
+ .replace("\t", "\\t")
+ + "\"";
+ }
+}