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

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

AslExecutor runs each execution on a worker-thread pool with no active CDI
request scope, so service integrations (Lambda, DynamoDB, SQS, …) and the
execution-store writes fell back to the configured default account. An
execution started under account B therefore had its integrations run
against account A's resources — e.g. a dynamodb:putItem targeting a table
that exists only in account B would fail with ResourceNotFound.

Wrap doExecute in a synthetic request scope whose account is the one
encoded in the state machine ARN (mirroring CurEmissionScheduler's
runUnderAccount), so integrations and store writes resolve to the
execution's own account. Falls back to running directly when Arc is not
running (plain unit tests that construct AslExecutor without a container).

Test: an execution started under a non-default account writes to a table
that exists only in that account; the execution succeeds, the item is
readable in that account, and a different account has no such table.

* fix(stepfunctions): restore previous account after runUnderExecutionAccount

Greptile review on #1566: when execution ran inside an already-active request
scope, runUnderExecutionAccount overwrote the account ID without restoring it.
Save and restore the previous account in finally so a reused thread isn't left
with the execution's account. (Executions run on background workers with no
active scope, so this hardens the already-active path.)

* fix(stepfunctions): run Parallel branches under the execution's account

executeParallelState submitted each branch to the executor pool without
re-establishing the execution's CDI request scope. RequestContext is
@RequestScoped (thread-bound), so a branch running on a worker thread had no
active scope: its Task integrations resolved via RegionResolver.getAccountId(),
which falls back to the default account on ContextNotActiveException. Branch
Task states therefore ran against the default account's resources instead of
the execution's.

Extract the scope-activation logic into a Callable-returning
callUnderExecutionAccount (runUnderExecutionAccount now delegates to it) and wrap
each branch submission with it, so every branch worker thread activates its own
request scope for the execution's account — mirroring how executeAsync/executeSync
wrap doExecute. Map states already run executeBranch synchronously on the parent
thread, so they were unaffected.

Adds a Parallel-branch case to StepFunctionsAccountContextIntegrationTest whose
branches dynamodb:putItem into a table that exists only in the execution's
account; it FAILs without per-branch propagation and SUCCEEDs with it.
This commit is contained in:
Alex Banna authored and GitHub committed 2026-06-30 22:17:52 -05:00
1 parent d54a307ca9
commit f558472a4d
2 files changed
+348 -3

No files matched your search

@@ -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);