fix(stepfunctions): scope callbacks and workers to execution region (#7633)

This commit is contained in:
Aniket Shukla authored and GitHub committed 2026-11-05 15:48:46 -04:00
1 parent 0c33083803
commit 36fbc33a2f
6 files changed
+169 -15

No files matched your search

+3 -3
View File
@@ -637,9 +637,9 @@ the wire and the task fails with `Sfn.StateMachineDoesNotExistException`.
| `arn:aws:states:::aws-sdk:scheduler:deleteSchedule` | `{}` | `Scheduler.ResourceNotFoundException` |
| `arn:aws:states:::aws-sdk:sns:publish` | `{MessageId}` | `Sns.NotFoundException` when the topic does not exist |
Callback tokens are owned by the execution account. Foreign callbacks return
`AccessDeniedException`; unknown tokens return `InvalidToken`. Recently closed tokens return
`TaskTimedOut`. Closed-token classification retains at most 1,024 tokens for five minutes; older
Callback tokens are owned by the execution account and region. Foreign-account callbacks return
`AccessDeniedException`; callbacks sent to another region and unknown tokens return `InvalidToken`.
Recently closed tokens return `TaskTimedOut`. Closed-token classification retains at most 1,024 tokens for five minutes; older
or evicted tokens return `InvalidToken`. Invalid JSON output leaves a pending token available
for a corrected callback. Token state remains in memory.
@@ -580,8 +580,8 @@ 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,
* Runs {@code body} on this worker thread under a CDI request scope whose account and region
* are 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.
@@ -610,14 +610,15 @@ public class AslExecutor {
* 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
* default account and region instead of the execution's. Each branch thread therefore activates its own
* scope here, mirroring how {@link #executeAsync}/{@link #executeSync} wrap {@code doExecute}.
* Delegates to {@link RequestScopes#callAsChecked}, which restores a previously active scope's
* account so a reused thread does not keep the execution's account.
* account and region so a reused thread does not keep the execution's scope.
*/
private <T> T callUnderExecutionAccount(StateMachine sm, Callable<T> body) throws Exception {
String accountId = AwsArnUtils.accountOrDefault(sm.getStateMachineArn(), null);
return RequestScopes.callAsChecked(accountId == null || accountId.isBlank() ? null : accountId, body);
String region = AwsArnUtils.regionOrDefault(sm.getStateMachineArn(), null);
return RequestScopes.callAsChecked(accountId == null || accountId.isBlank() ? null : accountId, region, body);
}
private void doExecute(StateMachine sm, Execution exec, List<HistoryEvent> history,
@@ -1321,22 +1321,26 @@ public class StepFunctionsService implements Resettable, ResourceProvider, Store
// The token selects one of the table's two resource kinds. Both lookups return that same ARN,
// so the reader deduplicates it without synthesizing a wildcard for the other kind.
return Optional.of(callbackResourceArn(names.size() == 1 ? names.getFirst() : null,
regionResolver.getAccountId()));
regionResolver.getAccountId(), region));
}
/**
* AWS authorizes activity callbacks on the activity and integration callbacks on the state machine.
* Retain that resource after completion so authorized retries still reach TaskTimedOut.
*/
public synchronized String callbackResourceArn(String token, String callerAccountId) {
public String callbackResourceArn(String token, String callerAccountId) {
return callbackResourceArn(token, callerAccountId, regionResolver.getRegion());
}
private synchronized String callbackResourceArn(String token, String callerAccountId, String region) {
PendingTask pending = token == null ? null : pendingTaskTokens.get(token);
if (pending != null) {
requireTokenOwner(pending.accountId(), callerAccountId);
requireTokenScope(pending.accountId(), pending.resourceArn(), callerAccountId, region);
return pending.resourceArn();
}
ClosedTask closed = token == null ? null : closedTaskTokens.get(token);
if (closed != null && System.nanoTime() - closed.closedAtNanos() < CLOSED_TOKEN_RETENTION_NANOS) {
requireTokenOwner(closed.accountId(), callerAccountId);
requireTokenScope(closed.accountId(), closed.resourceArn(), callerAccountId, region);
return closed.resourceArn();
}
throw new AwsException("InvalidToken", "Invalid Token: 'Invalid token'", 400);
@@ -1404,7 +1408,7 @@ public class StepFunctionsService implements Resettable, ResourceProvider, Store
String accountId = regionResolver.getAccountId();
PendingTask pending = token == null ? null : pendingTaskTokens.get(token);
if (pending != null) {
requireTokenOwner(pending.accountId(), accountId);
requireTokenScope(pending.accountId(), pending.resourceArn(), accountId, regionResolver.getRegion());
if (pending.result() != null) {
throw new AwsException("TaskTimedOut", "The associated task has already been closed.", 400);
}
@@ -1416,16 +1420,19 @@ public class StepFunctionsService implements Resettable, ResourceProvider, Store
closed = null;
}
if (closed != null) {
requireTokenOwner(closed.accountId(), accountId);
requireTokenScope(closed.accountId(), closed.resourceArn(), accountId, regionResolver.getRegion());
throw new AwsException("TaskTimedOut", "The associated task has already been closed.", 400);
}
throw new AwsException("InvalidToken", "Invalid Token: 'Invalid token'", 400);
}
private void requireTokenOwner(String owner, String caller) {
private void requireTokenScope(String owner, String resourceArn, String caller, String region) {
if (!owner.equals(caller)) {
throw new AwsException("AccessDeniedException", "Not authorized to access this resource.", 400);
}
if (!AwsArnUtils.isArnFor(resourceArn, "states") || !AwsArnUtils.parse(resourceArn).region().equals(region)) {
throw new AwsException("InvalidToken", "Invalid Token: 'Invalid token'", 400);
}
}
CompletableFuture<JsonNode> claimPendingTask(String token, TaskResult result) {
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsService.TaskResult;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
@@ -47,6 +48,11 @@ class AslExecutorTokenTimeoutTest {
resolver, mock(AslExecutor.class), mapper, mock(SfnMockLoader.class),
mock(StepFunctionsEventPublisher.class));
@BeforeEach
void defaultRegion() {
when(resolver.getRegion()).thenReturn("us-east-1");
}
@ParameterizedTest
@ValueSource(strings = {"execution", "task", "heartbeat"})
void timeoutClosesTokenBeforeCancellingFuture(String clock) throws Exception {
@@ -0,0 +1,82 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class StepFunctionsCallbackSdkRegionIntegrationTest {
private static final String ACCOUNT = "724600009876";
private static final String REGION = "us-west-2";
@Inject
StepFunctionsService states;
@Inject
ObjectMapper mapper;
@ParameterizedTest
@CsvSource({"sendTaskSuccess,us-west-2,true,Task", "sendTaskFailure,us-west-2,true,Task",
"sendTaskSuccess,us-east-1,false,Task", "sendTaskFailure,us-east-1,false,Task",
"sendTaskSuccess,us-west-2,true,Parallel", "sendTaskFailure,us-west-2,true,Parallel",
"sendTaskSuccess,us-east-1,false,Parallel", "sendTaskFailure,us-east-1,false,Parallel",
"sendTaskSuccess,us-west-2,true,Map", "sendTaskFailure,us-west-2,true,Map",
"sendTaskSuccess,us-east-1,false,Map", "sendTaskFailure,us-east-1,false,Map"})
void sdkCallbacksUseTheExecutionRegionRatherThanTheDefault(String operation, String tokenRegion,
boolean sameRegion, String worker) throws Exception {
String suffix = UUID.randomUUID().toString();
String token = "regional-" + suffix;
String resource = "arn:aws:states:" + tokenRegion + ":" + ACCOUNT + ":stateMachine:waiter";
CompletableFuture<JsonNode> waiting = states.registerPendingToken(token, ACCOUNT, resource);
Map<String, Object> parameters = new HashMap<>();
parameters.put("TaskToken", token);
if ("sendTaskSuccess".equals(operation)) {
parameters.put("Output", "{}");
} else {
parameters.put("Error", "Rejected");
parameters.put("Cause", "test");
}
Map<String, Object> callback = Map.of("Type", "Task", "Resource", "arn:aws:states:::aws-sdk:sfn:" + operation,
"Parameters", parameters, "End", true);
Map<String, Object> branch = Map.of("StartAt", "Send", "States", Map.of("Send", callback));
Map<String, Object> entry = switch (worker) {
case "Parallel" -> Map.of("Type", "Parallel", "Branches", List.of(branch), "End", true);
case "Map" -> Map.of("Type", "Map", "ItemsPath", "$", "MaxConcurrency", 2, "Iterator", branch, "End", true);
default -> callback;
};
String definition = mapper.writeValueAsString(Map.of("StartAt", "Send", "States", Map.of("Send", entry)));
StateMachine machine = RequestScopes.callAs(ACCOUNT, REGION, () -> states.createStateMachine(
"regional-" + suffix, definition, "arn:aws:iam::" + ACCOUNT + ":role/test", "STANDARD", REGION, Map.of()));
try {
Execution execution = RequestScopes.callAs(ACCOUNT, REGION,
() -> states.startExecution(machine.getStateMachineArn(), "sender", "Map".equals(worker) ? "[{}]" : "{}", REGION));
await().atMost(Duration.ofSeconds(10)).until(() -> RequestScopes.callAs(ACCOUNT, REGION,
() -> !"RUNNING".equals(states.describeExecution(execution.getExecutionArn()).getStatus())));
Execution result = RequestScopes.callAs(ACCOUNT, REGION, () -> states.describeExecution(execution.getExecutionArn()));
assertEquals(sameRegion ? "SUCCEEDED" : "FAILED", result.getStatus());
assertEquals(sameRegion, waiting.isDone());
if (!sameRegion && "Task".equals(worker)) {
assertEquals("Sfn.InvalidTokenException", result.getError());
}
} finally {
states.discardPendingToken(token);
RequestScopes.runAs(ACCOUNT, REGION, () -> states.deleteStateMachine(machine.getStateMachineArn()));
}
}
}
@@ -2,9 +2,11 @@ package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
@@ -36,6 +38,61 @@ class StepFunctionsCallbackTokenTest {
resolver, mock(AslExecutor.class), new ObjectMapper(), mock(SfnMockLoader.class),
mock(StepFunctionsEventPublisher.class));
@BeforeEach
void defaultRegion() {
when(resolver.getRegion()).thenReturn("us-east-1");
}
@ParameterizedTest
@ValueSource(strings = {"success", "failure", "heartbeat", "resource"})
void callbacksCannotUseATokenFromAnotherRegion(String operation) {
when(resolver.getAccountId()).thenReturn(OWNER);
when(resolver.getRegion()).thenReturn("us-west-2");
CompletableFuture<JsonNode> future = service.registerPendingToken("regional", OWNER, RESOURCE);
long heartbeat = service.lastTaskHeartbeatNanos("regional");
refuses("InvalidToken", () -> {
switch (operation) {
case "success" -> service.sendTaskSuccess("regional", "{}");
case "failure" -> service.sendTaskFailure("regional", "cause", "error");
case "heartbeat" -> service.sendTaskHeartbeat("regional");
default -> service.callbackResourceArn("regional", OWNER);
}
});
assertFalse(future.isDone());
assertEquals(heartbeat, service.lastTaskHeartbeatNanos("regional"));
when(resolver.getRegion()).thenReturn("us-east-1");
assertTrue(service.sendTaskSuccess("regional", "{}"));
assertTrue(future.isDone());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void completedAndRetiredTokensKeepTheirRegionBoundary(boolean retired) {
when(resolver.getAccountId()).thenReturn(OWNER);
service.registerPendingToken("completed-regional", OWNER, RESOURCE);
service.sendTaskSuccess("completed-regional", "{}");
if (retired) {
service.discardPendingToken("completed-regional");
}
when(resolver.getRegion()).thenReturn("us-west-2");
refuses("InvalidToken", () -> service.sendTaskSuccess("completed-regional", "{}"));
refuses("InvalidToken", () -> service.sendTaskFailure("completed-regional", "cause", "error"));
refuses("InvalidToken", () -> service.sendTaskHeartbeat("completed-regional"));
refuses("InvalidToken", () -> service.callbackResourceArn("completed-regional", OWNER));
refuses("InvalidToken", () -> service.findByMembers("statemachine", List.of("completed-regional"), "us-west-2"));
when(resolver.getRegion()).thenReturn("us-east-1");
assertEquals(RESOURCE, service.callbackResourceArn("completed-regional", OWNER));
refuses("TaskTimedOut", () -> service.sendTaskHeartbeat("completed-regional"));
}
@Test
void iamTokenLookupHonorsItsExplicitRegion() {
when(resolver.getAccountId()).thenReturn(OWNER);
when(resolver.getRegion()).thenReturn("us-east-1");
service.registerPendingToken("regional", OWNER, RESOURCE);
refuses("InvalidToken", () -> service.findByMembers("statemachine", List.of("regional"), "us-west-2"));
}
@ParameterizedTest
@CsvSource({
"arn:aws:states:us-east-1:111111111111:stateMachine:callback,arn:aws:states:us-east-1:111111111111:stateMachine:callback",
@@ -43,6 +100,7 @@ class StepFunctionsCallbackTokenTest {
"arn:aws-cn:states:cn-north-1:111111111111:activity:callback,arn:aws-cn:states:cn-north-1:111111111111:activity:callback"
})
void callbackResourceSurvivesCompletionAndRetirementWithoutClaimingTheToken(String resource, String expected) {
when(resolver.getRegion()).thenReturn(AwsArnUtils.parse(resource).region());
when(resolver.getAccountId()).thenReturn(OWNER);
CompletableFuture<JsonNode> future = service.registerPendingToken("resource", OWNER, resource);
assertEquals(expected, service.callbackResourceArn("resource", OWNER));