mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(stepfunctions): authorize task callbacks against their resource (#7277)
* fix(stepfunctions): authorize callbacks with generated resource lookups Preserve measured callback resource authorization, token ownership and closed-token behavior. Use explicit generated member lookups, retaining ordinary name resolution and invalid-token precedence. Preserve current main Redshift session-through lookups, generator type validation and payment alias consumers. Signed-off-by: Andre Kurait <akurait@amazon.com> * test(stepfunctions): reuse the SQS callback queue fixture Create callback queues through SqsTestQueue and await token JSON with the shared in-process helper. Retain the existing callback authorization matrix, token error precedence and cleanup registration. Signed-off-by: Andre Kurait <akurait@amazon.com> --------- Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
1 parent
67b408aa22
commit
bbe23ed550
13 files changed
+515
-39
No files matched your search
@@ -60,6 +60,23 @@ its version does not discard its pool identity. Unqualified invocation retains
|
||||
the normal on-demand path, and existing authorization checks still precede
|
||||
execution.
|
||||
|
||||
## Task-token IAM resources
|
||||
|
||||
With IAM enforcement enabled, `SendTaskSuccess`, `SendTaskFailure`, and
|
||||
`SendTaskHeartbeat` authorize against the resource associated with the token:
|
||||
the activity ARN for an activity task, or the unqualified state-machine ARN
|
||||
for a `.waitForTaskToken` service integration, including versioned executions.
|
||||
A grant on only the version ARN does not match. A wildcard grant also matches, and
|
||||
an explicit deny on the matching resource wins. An execution ARN or an
|
||||
unrelated resource does not grant callback access.
|
||||
|
||||
This distinction was verified with signed SDK calls against AWS using both
|
||||
Lambda callback integrations and activities. Recent completed tokens retain
|
||||
their resource so a permitted retry receives `TaskTimedOut`. Unknown tokens
|
||||
return `InvalidToken` before IAM resource evaluation. Resource lookup
|
||||
does not consume the token. The caller must own the token before its resource
|
||||
is used for IAM evaluation, including for recent completed tokens.
|
||||
|
||||
## Nested task credentials
|
||||
|
||||
Nested `states:startExecution` tasks, including `.sync` and `.sync:2`, and the SDK
|
||||
|
||||
@@ -362,12 +362,15 @@ public final class RequestResources {
|
||||
for (RequestResourceMembers.Member member : resource.find()) {
|
||||
List<String> values = values(form, body, member);
|
||||
if (isNull(body, member) || values.size() != 1) {
|
||||
if (stored != null) {
|
||||
stored.findByMembers(resource.types().getFirst(), List.of(), region);
|
||||
}
|
||||
return;
|
||||
}
|
||||
names.add(values.getFirst());
|
||||
}
|
||||
String type = resource.types().getFirst();
|
||||
Optional<String> found = stored == null ? Optional.empty() : stored.find(type, names, region);
|
||||
Optional<String> found = stored == null ? Optional.empty() : stored.findByMembers(type, names, region);
|
||||
arns.add(found.orElseGet(() -> render(formats.get(type).format(), Map.of(), partition, region, accountId)));
|
||||
}
|
||||
|
||||
|
||||
@@ -42,4 +42,13 @@ public interface StoredResourceArns {
|
||||
default Optional<String> through(String member, String value, String region) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves an explicit {@code find} selector. An empty list indicates an incomplete selector, which a service
|
||||
* may reject before IAM evaluation. This is distinct from an ordinary name filling an ARN's variables:
|
||||
* callback tokens require validation, but state-machine names do not name callback tokens.
|
||||
*/
|
||||
default Optional<String> findByMembers(String type, List<String> names, String region) {
|
||||
return find(type, names, region);
|
||||
}
|
||||
}
|
||||
@@ -976,7 +976,8 @@ public class AslExecutor {
|
||||
|
||||
// Registered after the input template resolved, so a template failure leaves no token behind.
|
||||
CompletableFuture<JsonNode> tokenFuture = needsToken ? sfnService.get().registerPendingToken(taskToken,
|
||||
AwsArnUtils.parse(sm.getStateMachineArn()).accountId()) : null;
|
||||
AwsArnUtils.parse(sm.getStateMachineArn()).accountId(),
|
||||
isActivity ? resource : sm.getStateMachineArn()) : null;
|
||||
TaskEventProfile profile = taskEventProfile(resource, isActivity);
|
||||
JsonNode taskResult;
|
||||
// Read before the scheduled event is built, so a large input or a slow history callback
|
||||
|
||||
+55
-11
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.common.SignedMarkers;
|
||||
import io.github.hectorvent.floci.core.common.StoredResourceArns;
|
||||
import io.github.hectorvent.floci.core.resource.ExplorerResource;
|
||||
import io.github.hectorvent.floci.core.resource.ResourceProvider;
|
||||
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
|
||||
@@ -55,7 +56,7 @@ import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
public class StepFunctionsService implements Resettable, ResourceProvider, StoredResourceArns {
|
||||
private static final int LIST_EXECUTIONS_MAX_TOKEN_LENGTH = 3096;
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(StepFunctionsService.class);
|
||||
@@ -78,7 +79,8 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
private static final long CLOSED_TOKEN_RETENTION_NANOS = TimeUnit.MINUTES.toNanos(5);
|
||||
private static final int MAX_CLOSED_TOKENS = 1024;
|
||||
|
||||
private record PendingTask(String accountId, CompletableFuture<JsonNode> future, TaskResult result) {}
|
||||
private record PendingTask(String accountId, String resourceArn,
|
||||
CompletableFuture<JsonNode> future, TaskResult result) {}
|
||||
|
||||
record TaskResult(JsonNode output, AslExecutor.FailStateException failure) {
|
||||
JsonNode get() {
|
||||
@@ -98,7 +100,7 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
|
||||
record TokenWait(TokenTimeout timeout, TaskResult result) {}
|
||||
private record ClosedTask(String accountId, long closedAtNanos) {}
|
||||
private record ClosedTask(String accountId, String resourceArn, long closedAtNanos) {}
|
||||
// When each pending token last showed progress, so a Task's HeartbeatSeconds can bound the gap
|
||||
// between heartbeats instead of the whole wait.
|
||||
private final Map<String, Long> taskHeartbeatNanos = new ConcurrentHashMap<>();
|
||||
@@ -204,7 +206,7 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
synchronized (this) {
|
||||
tokenResetsInProgress++;
|
||||
pendingTaskTokens.replaceAll((token, task) -> task.result() != null ? task
|
||||
: new PendingTask(task.accountId(), task.future(), new TaskResult(null,
|
||||
: new PendingTask(task.accountId(), task.resourceArn(), task.future(), new TaskResult(null,
|
||||
new AslExecutor.FailStateException("States.TaskFailed", "StepFunctionsService cleared"))));
|
||||
pending = new HashMap<>(pendingTaskTokens);
|
||||
closedTaskTokens.clear();
|
||||
@@ -1285,12 +1287,14 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
queue.add(new ActivityTask(taskToken, input));
|
||||
}
|
||||
|
||||
public CompletableFuture<JsonNode> registerPendingToken(String token, String accountId) {
|
||||
public CompletableFuture<JsonNode> registerPendingToken(String token, String accountId, String resourceArn) {
|
||||
Objects.requireNonNull(accountId);
|
||||
QualifiedStateMachineArn qualified = parseQualifiedStateMachineArn(Objects.requireNonNull(resourceArn));
|
||||
String authorizationArn = qualified == null ? resourceArn : qualified.baseArn();
|
||||
CompletableFuture<JsonNode> future = new CompletableFuture<>();
|
||||
synchronized (this) {
|
||||
if (tokenResetsInProgress == 0) {
|
||||
pendingTaskTokens.put(token, new PendingTask(accountId, future, null));
|
||||
pendingTaskTokens.put(token, new PendingTask(accountId, authorizationArn, future, null));
|
||||
taskHeartbeatNanos.put(token, System.nanoTime());
|
||||
return future;
|
||||
}
|
||||
@@ -1299,6 +1303,45 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
return future;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String namespace() {
|
||||
return "states";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> findByMembers(String type, List<String> names, String region) {
|
||||
if (!Set.of("activity", "statemachine").contains(type)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
// 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()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
PendingTask pending = token == null ? null : pendingTaskTokens.get(token);
|
||||
if (pending != null) {
|
||||
requireTokenOwner(pending.accountId(), callerAccountId);
|
||||
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);
|
||||
return closed.resourceArn();
|
||||
}
|
||||
throw new AwsException("InvalidToken", "Invalid Token: 'Invalid token'", 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* When the token last showed progress: the moment its task was scheduled, then every
|
||||
* SendTaskHeartbeat that named it. A token that is no longer pending reads as having just
|
||||
@@ -1342,16 +1385,16 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
PendingTask pending = pendingTaskTokens.remove(taskToken);
|
||||
taskHeartbeatNanos.remove(taskToken);
|
||||
if (pending != null) {
|
||||
rememberClosed(taskToken, pending.accountId());
|
||||
rememberClosed(taskToken, pending);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void rememberClosed(String token, String accountId) {
|
||||
private void rememberClosed(String token, PendingTask pending) {
|
||||
long now = System.nanoTime();
|
||||
closedTaskTokens.entrySet().removeIf(entry -> now - entry.getValue().closedAtNanos()
|
||||
>= CLOSED_TOKEN_RETENTION_NANOS);
|
||||
closedTaskTokens.put(token, new ClosedTask(accountId, now));
|
||||
closedTaskTokens.put(token, new ClosedTask(pending.accountId(), pending.resourceArn(), now));
|
||||
while (closedTaskTokens.size() > MAX_CLOSED_TOKENS) {
|
||||
closedTaskTokens.remove(closedTaskTokens.keySet().iterator().next());
|
||||
}
|
||||
@@ -1388,9 +1431,10 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
CompletableFuture<JsonNode> claimPendingTask(String token, TaskResult result) {
|
||||
synchronized (this) {
|
||||
PendingTask pending = requirePendingTask(token);
|
||||
pendingTaskTokens.put(token, new PendingTask(pending.accountId(), pending.future(), result));
|
||||
pendingTaskTokens.put(token, new PendingTask(pending.accountId(), pending.resourceArn(),
|
||||
pending.future(), result));
|
||||
taskHeartbeatNanos.remove(token);
|
||||
rememberClosed(token, pending.accountId());
|
||||
rememberClosed(token, pending);
|
||||
return pending.future();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1023,9 +1023,9 @@
|
||||
"states:ListTagsForResource": {"action": "states:ListTagsForResource", "types": ["activity", "statemachine"], "resources": [{"types": ["activity", "statemachine"], "arn": "resourceArn"}]},
|
||||
"states:PublishStateMachineVersion": {"action": "states:PublishStateMachineVersion", "types": ["statemachine"], "resources": [{"types": ["statemachine"], "arn": "stateMachineArn"}]},
|
||||
"states:RedriveExecution": {"action": "states:RedriveExecution", "types": ["execution"], "resources": [{"types": ["execution"], "arn": "executionArn"}]},
|
||||
"states:SendTaskFailure": {"action": "states:SendTaskFailure", "types": [], "resources": []},
|
||||
"states:SendTaskHeartbeat": {"action": "states:SendTaskHeartbeat", "types": [], "resources": []},
|
||||
"states:SendTaskSuccess": {"action": "states:SendTaskSuccess", "types": [], "resources": []},
|
||||
"states:SendTaskFailure": {"action": "states:SendTaskFailure", "types": [], "resources": [{"type": "activity", "fill": {}, "find": ["taskToken"]}, {"type": "statemachine", "fill": {}, "find": ["taskToken"]}]},
|
||||
"states:SendTaskHeartbeat": {"action": "states:SendTaskHeartbeat", "types": [], "resources": [{"type": "activity", "fill": {}, "find": ["taskToken"]}, {"type": "statemachine", "fill": {}, "find": ["taskToken"]}]},
|
||||
"states:SendTaskSuccess": {"action": "states:SendTaskSuccess", "types": [], "resources": [{"type": "activity", "fill": {}, "find": ["taskToken"]}, {"type": "statemachine", "fill": {}, "find": ["taskToken"]}]},
|
||||
"states:StartExecution": {"action": "states:StartExecution", "types": ["statemachine"], "resources": [{"types": ["statemachine"], "arn": "stateMachineArn", "before": "#"}], "creates": [{"type": "execution", "parent": "statemachine", "arn": "stateMachineArn"}]},
|
||||
"states:StartSyncExecution": {"action": "states:StartSyncExecution", "types": ["statemachine"], "resources": [{"types": ["statemachine"], "arn": "stateMachineArn", "before": "#"}], "creates": [{"type": "execution", "parent": "statemachine", "arn": "stateMachineArn"}]},
|
||||
"states:StopExecution": {"action": "states:StopExecution", "types": ["execution"], "resources": [{"types": ["execution"], "arn": "executionArn"}]},
|
||||
|
||||
+8
-5
@@ -256,9 +256,9 @@ class RequestResourceMembersTest {
|
||||
|
||||
/**
|
||||
* Each resource alone, from a request naming it and nothing else, gives exactly its ARN, in the account its
|
||||
* account member names when it has one, with those of the operation's resources every request names, a create's
|
||||
* new resource no member names (Cloud Map's {@code CreateService}); one named through another resource of its
|
||||
* service's own, the ARN its service gives for that.
|
||||
* account member names when it has one, with those sharing its explicit member selector and those the operation
|
||||
* always names, such as a create's new resource (Cloud Map's {@code CreateService}); one named through another
|
||||
* resource of its service's own, the ARN its service gives for that.
|
||||
*/
|
||||
@TestFactory
|
||||
Stream<DynamicTest> everyResourceOfTheTableIsReadFromAJsonBodyAndAForm() {
|
||||
@@ -292,8 +292,11 @@ class RequestResourceMembersTest {
|
||||
form.append('&').append(parameter(member)).append('=').append(encoded(value));
|
||||
});
|
||||
List<String> named = operation.getValue().stream()
|
||||
.filter(other -> other == resource || named(other) && (other.endpoint() == null
|
||||
|| resource.endpoint() == null || other.endpoint().equals(resource.endpoint())))
|
||||
.filter(other -> (other == resource || named(other)
|
||||
|| !other.find().isEmpty() && other.find().equals(resource.find())
|
||||
&& other.when().equals(resource.when()) && other.unless().equals(resource.unless()))
|
||||
&& (other.endpoint() == null || resource.endpoint() == null
|
||||
|| other.endpoint().equals(resource.endpoint())))
|
||||
.map(other -> other == resource ? expected : expected(
|
||||
table.formats().get(namespace).get(other.types().getFirst()).format(), other,
|
||||
"000000000000"))
|
||||
|
||||
@@ -13,6 +13,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -392,6 +393,30 @@ class RequestResourcesTest {
|
||||
assertEquals(List.of(v2Bus), of("events:DeleteEventBus", v2(withV2Arn)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void incompleteStoredSelectorsRetainNoResourceThroughTheDefaultLookup() {
|
||||
for (String operation : List.of("events:DescribeConnection", "application-autoscaling:DeleteScalingPolicy",
|
||||
"redshift-data:ListSchemas")) {
|
||||
AtomicInteger lookups = new AtomicInteger();
|
||||
StoredResourceArns stored = new StoredResourceArns() {
|
||||
@Override
|
||||
public String namespace() {
|
||||
return operation.substring(0, operation.indexOf(':'));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> find(String type, List<String> names, String region) {
|
||||
assertEquals(List.of(), names);
|
||||
lookups.incrementAndGet();
|
||||
return Optional.empty();
|
||||
}
|
||||
};
|
||||
assertEquals(List.of(), RequestResources.of(operation, json("{}"), "aws", "us-east-1",
|
||||
"000000000000", stored), operation);
|
||||
assertEquals(operation.startsWith("events:") ? 0 : 1, lookups.get(), operation);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A connection or an API destination, whose ARN EventBridge follows with an id it mints after the name, is the
|
||||
* one stored under the name the request gives, and has that id open when none is or nothing looks it up.
|
||||
|
||||
+10
-9
@@ -40,6 +40,7 @@ import static org.mockito.Mockito.when;
|
||||
class AslExecutorTokenTimeoutTest {
|
||||
|
||||
private static final String OWNER = "111111111111";
|
||||
private static final String RESOURCE = "arn:aws:states:us-east-1:" + OWNER + ":stateMachine:callback";
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final RegionResolver resolver = mock(RegionResolver.class);
|
||||
private final StepFunctionsService service = new StepFunctionsService(mock(StorageFactory.class),
|
||||
@@ -50,7 +51,7 @@ class AslExecutorTokenTimeoutTest {
|
||||
@ValueSource(strings = {"execution", "task", "heartbeat"})
|
||||
void timeoutClosesTokenBeforeCancellingFuture(String clock) throws Exception {
|
||||
when(resolver.getAccountId()).thenReturn(OWNER);
|
||||
CompletableFuture<JsonNode> future = service.registerPendingToken("expired", OWNER);
|
||||
CompletableFuture<JsonNode> future = service.registerPendingToken("expired", OWNER, RESOURCE);
|
||||
long now = service.lastTaskHeartbeatNanos("expired") + TimeUnit.SECONDS.toNanos(2);
|
||||
List<String> callbackResults = new ArrayList<>();
|
||||
future.whenComplete((result, error) -> {
|
||||
@@ -79,7 +80,7 @@ class AslExecutorTokenTimeoutTest {
|
||||
@Test
|
||||
void callbackClaimedBeforeTimeoutDecisionKeepsItsResult() throws Exception {
|
||||
when(resolver.getAccountId()).thenReturn(OWNER);
|
||||
CompletableFuture<JsonNode> future = service.registerPendingToken("winner", OWNER);
|
||||
CompletableFuture<JsonNode> future = service.registerPendingToken("winner", OWNER, RESOURCE);
|
||||
AtomicInteger clockReads = new AtomicInteger();
|
||||
AslExecutor executor = executor(() -> {
|
||||
if (clockReads.incrementAndGet() == 2) {
|
||||
@@ -97,7 +98,7 @@ class AslExecutorTokenTimeoutTest {
|
||||
@Test
|
||||
void heartbeatBeforeTimeoutDecisionExtendsTheWait() throws Exception {
|
||||
when(resolver.getAccountId()).thenReturn(OWNER);
|
||||
CompletableFuture<JsonNode> future = service.registerPendingToken("heartbeat", OWNER);
|
||||
CompletableFuture<JsonNode> future = service.registerPendingToken("heartbeat", OWNER, RESOURCE);
|
||||
long now = service.lastTaskHeartbeatNanos("heartbeat") + TimeUnit.SECONDS.toNanos(1);
|
||||
AtomicInteger clockReads = new AtomicInteger();
|
||||
AslExecutor executor = executor(() -> {
|
||||
@@ -123,7 +124,7 @@ class AslExecutorTokenTimeoutTest {
|
||||
void claimedResultDoesNotWaitForCallbackCompletion(boolean failure) throws Exception {
|
||||
when(resolver.getAccountId()).thenReturn(OWNER);
|
||||
StepFunctionsService callbackService = spy(service);
|
||||
CompletableFuture<JsonNode> future = callbackService.registerPendingToken("stalled", OWNER);
|
||||
CompletableFuture<JsonNode> future = callbackService.registerPendingToken("stalled", OWNER, RESOURCE);
|
||||
CountDownLatch claimed = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
doAnswer(invocation -> {
|
||||
@@ -168,7 +169,7 @@ class AslExecutorTokenTimeoutTest {
|
||||
|
||||
@Test
|
||||
void discardedTokenDoesNotLookLikeAnAcceptedCallback() throws Exception {
|
||||
CompletableFuture<JsonNode> future = service.registerPendingToken("discarded", OWNER);
|
||||
CompletableFuture<JsonNode> future = service.registerPendingToken("discarded", OWNER, RESOURCE);
|
||||
service.discardPendingToken("discarded");
|
||||
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(1), () -> assertThrows(AslExecutor.TaskTimedOutException.class,
|
||||
@@ -180,7 +181,7 @@ class AslExecutorTokenTimeoutTest {
|
||||
@ValueSource(booleans = {false, true})
|
||||
void clearPreservesClaimedOutcomeAndCompletesOutsideLock(boolean failure) throws Exception {
|
||||
when(resolver.getAccountId()).thenReturn(OWNER);
|
||||
CompletableFuture<JsonNode> future = service.registerPendingToken("cleared", OWNER);
|
||||
CompletableFuture<JsonNode> future = service.registerPendingToken("cleared", OWNER, RESOURCE);
|
||||
JsonNode output = mapper.readTree("{\"accepted\":true}");
|
||||
AslExecutor.FailStateException error = new AslExecutor.FailStateException("CallbackError", "cause");
|
||||
service.claimPendingTask("cleared", failure ? new TaskResult(null, error) : new TaskResult(output, null));
|
||||
@@ -202,7 +203,7 @@ class AslExecutorTokenTimeoutTest {
|
||||
@ValueSource(booleans = {false, true})
|
||||
void registrationDuringResetIsRetiredUntilAllResetsFinish(boolean overlappingReset) throws Exception {
|
||||
when(resolver.getAccountId()).thenReturn(OWNER);
|
||||
CompletableFuture<JsonNode> first = service.registerPendingToken("first", OWNER);
|
||||
CompletableFuture<JsonNode> first = service.registerPendingToken("first", OWNER, RESOURCE);
|
||||
CountDownLatch completing = new CountDownLatch(1);
|
||||
CompletableFuture<Void> release = new CompletableFuture<>();
|
||||
List<Boolean> completionLocks = new ArrayList<>();
|
||||
@@ -218,14 +219,14 @@ class AslExecutorTokenTimeoutTest {
|
||||
if (overlappingReset) {
|
||||
service.clear();
|
||||
}
|
||||
CompletableFuture<JsonNode> duringReset = service.registerPendingToken("during-reset", OWNER);
|
||||
CompletableFuture<JsonNode> duringReset = service.registerPendingToken("during-reset", OWNER, RESOURCE);
|
||||
assertTrue(duringReset.isCompletedExceptionally());
|
||||
assertEquals("InvalidToken", callbackResult(() -> service.sendTaskSuccess("during-reset", "{}")));
|
||||
release.complete(null);
|
||||
reset.get(5, TimeUnit.SECONDS);
|
||||
assertEquals(List.of(false), completionLocks);
|
||||
|
||||
CompletableFuture<JsonNode> afterReset = service.registerPendingToken("after-reset", OWNER);
|
||||
CompletableFuture<JsonNode> afterReset = service.registerPendingToken("after-reset", OWNER, RESOURCE);
|
||||
service.sendTaskSuccess("after-reset", "{}");
|
||||
assertEquals(mapper.readTree("{}"), afterReset.get(5, TimeUnit.SECONDS));
|
||||
} finally {
|
||||
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.model.AccessKey;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.SignedIamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.SignedIamUsers;
|
||||
import io.github.hectorvent.floci.testing.SqsTestQueue;
|
||||
import io.github.hectorvent.floci.testutil.AwsRequestSigner;
|
||||
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 jakarta.inject.Inject;
|
||||
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 software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.iam.IamClient;
|
||||
import software.amazon.awssdk.services.sfn.SfnClient;
|
||||
import software.amazon.awssdk.services.sfn.model.CreateStateMachineResponse;
|
||||
import software.amazon.awssdk.services.sfn.model.SfnException;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(SignedIamEnforcementProfile.class)
|
||||
class StepFunctionsCallbackIamIntegrationTest {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@TestHTTPResource
|
||||
URI endpoint;
|
||||
|
||||
@Inject
|
||||
IamService iam;
|
||||
|
||||
@Inject
|
||||
SqsService sqsService;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"integration,exact,true", "integration,wrong,false", "integration,wildcard,true",
|
||||
"integration,deny-exact,false", "integration,deny-wrong,true",
|
||||
"integration,deny-all,false", "integration,deny-other-type,true", "integration,execution,false",
|
||||
"integration-version,exact,true", "integration-version,wrong,false",
|
||||
"integration-version,deny-exact,false",
|
||||
"integration-version,qualified,false", "integration-version,deny-qualified,true",
|
||||
"activity,exact,true", "activity,wrong,false", "activity,wildcard,true",
|
||||
"activity,deny-exact,false", "activity,deny-wrong,true",
|
||||
"activity,deny-all,false", "activity,deny-other-type,true", "activity,execution,false",
|
||||
"activity,state-machine,false"
|
||||
})
|
||||
void signedCallbacksAuthorizeTheTokensResource(String mode, String policy, boolean allowed) throws Exception {
|
||||
SfnClient admin = client("test", "test");
|
||||
String name = "callback-iam-" + UUID.randomUUID();
|
||||
String role = executionRole(name);
|
||||
SqsTestQueue queue = SqsTestQueue.create(sqsService, "000000000000", "us-east-1", "callback-iam-");
|
||||
cleanup.register(queue::delete);
|
||||
String activity = admin.createActivity(request -> request.name(name)).activityArn();
|
||||
cleanup.register(() -> admin.deleteActivity(request -> request.activityArn(activity)));
|
||||
boolean isActivity = "activity".equals(mode);
|
||||
Map<String, Object> task = isActivity
|
||||
? Map.of("Type", "Task", "Resource", activity, "TimeoutSeconds", 60, "End", true)
|
||||
: Map.of("Type", "Task", "Resource", "arn:aws:states:::sqs:sendMessage.waitForTaskToken",
|
||||
"Parameters", Map.of("QueueUrl", queue.url(), "MessageBody", Map.of("token.$", "$$.Task.Token")),
|
||||
"TimeoutSeconds", 60, "End", true);
|
||||
String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Callback", "States", Map.of("Callback", task)));
|
||||
boolean versioned = "integration-version".equals(mode);
|
||||
CreateStateMachineResponse created = admin.createStateMachine(request -> request.name(name).roleArn(role)
|
||||
.publish(versioned).definition(definition));
|
||||
String machine = created.stateMachineArn();
|
||||
String startMachine = versioned ? created.stateMachineVersionArn() : machine;
|
||||
cleanup.register(() -> admin.deleteStateMachine(request -> request.stateMachineArn(machine)));
|
||||
String resource = isActivity ? activity : machine;
|
||||
String policyResource = switch (policy) {
|
||||
case "wildcard", "deny-all" -> "*";
|
||||
case "wrong", "deny-wrong" -> resource + "-other";
|
||||
case "execution" -> machine.replace(":stateMachine:", ":execution:") + ":*";
|
||||
case "state-machine" -> machine;
|
||||
case "deny-other-type" -> (isActivity ? machine : activity).replace(name, "*");
|
||||
case "qualified", "deny-qualified" -> startMachine;
|
||||
default -> resource;
|
||||
};
|
||||
List<Map<String, Object>> statements = policy.startsWith("deny-")
|
||||
? List.of(statement("Allow", "deny-other-type".equals(policy) ? resource : "*"),
|
||||
statement("Deny", policyResource))
|
||||
: List.of(statement("Allow", policyResource));
|
||||
SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "callback-", "callback",
|
||||
MAPPER.writeValueAsString(Map.of("Version", "2012-10-17", "Statement", statements)));
|
||||
cleanup.register(() -> {
|
||||
try {
|
||||
user.close();
|
||||
} catch (Exception error) {
|
||||
throw new AssertionError("callback user cleanup failed", error);
|
||||
}
|
||||
});
|
||||
SfnClient actor = client(user.accessKeyId(), user.secretAccessKey());
|
||||
|
||||
for (String action : List.of("heartbeat", "success", "failure")) {
|
||||
SfnException invalid = assertThrows(SfnException.class, () -> callback(actor, action, "invalid-token"));
|
||||
assertEquals("InvalidToken", invalid.awsErrorDetails().errorCode());
|
||||
String execution = admin.startExecution(request -> request.stateMachineArn(startMachine)).executionArn();
|
||||
cleanup.register(() -> {
|
||||
if ("RUNNING".equals(admin.describeExecution(request -> request.executionArn(execution)).statusAsString())) {
|
||||
admin.stopExecution(request -> request.executionArn(execution));
|
||||
}
|
||||
});
|
||||
String token = isActivity
|
||||
? admin.getActivityTask(request -> request.activityArn(activity)).taskToken()
|
||||
: queue.awaitJson(Duration.ofSeconds(10)).path("token").asText();
|
||||
if (allowed) {
|
||||
callback(actor, action, token);
|
||||
if (!"heartbeat".equals(action)) {
|
||||
assertEquals("success".equals(action) ? "SUCCEEDED" : "FAILED", terminal(admin, execution));
|
||||
SfnException closed = assertThrows(SfnException.class, () -> callback(actor, action, token));
|
||||
assertEquals("TaskTimedOut", closed.awsErrorDetails().errorCode());
|
||||
}
|
||||
} else {
|
||||
SfnException denied = assertThrows(SfnException.class, () -> callback(actor, action, token));
|
||||
assertEquals("AccessDeniedException", denied.awsErrorDetails().errorCode());
|
||||
assertEquals("RUNNING", admin.describeExecution(request -> request.executionArn(execution)).statusAsString());
|
||||
admin.sendTaskSuccess(request -> request.taskToken(token).output("{}"));
|
||||
assertEquals("SUCCEEDED", terminal(admin, execution), "denial must not consume the token");
|
||||
}
|
||||
if ("RUNNING".equals(admin.describeExecution(request -> request.executionArn(execution)).statusAsString())) {
|
||||
admin.stopExecution(request -> request.executionArn(execution));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void signedNamedResourcesDoNotUseTheCallbackTokenSelector() throws Exception {
|
||||
SfnClient admin = client("test", "test");
|
||||
String name = "named-" + UUID.randomUUID();
|
||||
String role = executionRole(name);
|
||||
String prefix = "arn:aws:states:us-east-1:000000000000:";
|
||||
List<Map<String, Object>> statements = List.of(
|
||||
Map.of("Effect", "Allow", "Action", "states:*", "Resource",
|
||||
List.of(prefix + "activity:" + name, prefix + "stateMachine:" + name)),
|
||||
Map.of("Effect", "Allow", "Action", "iam:PassRole", "Resource", role));
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "named-", "named",
|
||||
MAPPER.writeValueAsString(Map.of("Version", "2012-10-17", "Statement", statements)))) {
|
||||
SfnClient actor = client(user.accessKeyId(), user.secretAccessKey());
|
||||
String activity = actor.createActivity(request -> request.name(name)).activityArn();
|
||||
cleanup.register(() -> admin.deleteActivity(request -> request.activityArn(activity)));
|
||||
assertEquals(name, actor.describeActivity(request -> request.activityArn(activity)).name());
|
||||
String definition = "{\"StartAt\":\"Done\",\"States\":{\"Done\":{\"Type\":\"Succeed\"}}}";
|
||||
String machine = actor.createStateMachine(request -> request.name(name).roleArn(role)
|
||||
.definition(definition)).stateMachineArn();
|
||||
cleanup.register(() -> admin.deleteStateMachine(request -> request.stateMachineArn(machine)));
|
||||
assertEquals(name, actor.describeStateMachine(request -> request.stateMachineArn(machine)).name());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"{}", "{\"taskToken\":null}", "{\"taskToken\":\"\"}",
|
||||
"{\"taskToken\":\" \"}", "{\"taskToken\":42}", "{\"taskToken\":true}",
|
||||
"{\"taskToken\":{}}", "{\"taskToken\":[]}"})
|
||||
void invalidOperandsKeepTokenErrorPrecedence(String body) throws Exception {
|
||||
for (String mode : List.of("none", "deny", "allow")) {
|
||||
Map<String, Object> policy = Map.of("Effect", "deny".equals(mode) ? "Deny" : "Allow", "Resource", "*", "Action",
|
||||
"none".equals(mode) ? "states:DescribeExecution" : "states:*");
|
||||
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "operand-", "callback",
|
||||
MAPPER.writeValueAsString(Map.of("Version", "2012-10-17", "Statement", List.of(policy))))) {
|
||||
for (String operation : List.of("SendTaskHeartbeat", "SendTaskSuccess", "SendTaskFailure")) {
|
||||
Response response = given().filter(AwsRequestSigner.signedAs(
|
||||
user.accessKeyId(), user.secretAccessKey(), "states"))
|
||||
.contentType("application/x-amz-json-1.0")
|
||||
.header("X-Amz-Target", "AWSStepFunctions." + operation)
|
||||
.body(body.getBytes(StandardCharsets.UTF_8)).post(endpoint);
|
||||
assertEquals(400, response.statusCode(), operation + ": " + response.asString());
|
||||
assertTrue(response.jsonPath().getString("__type").endsWith("InvalidToken"),
|
||||
operation + ": " + response.asString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"matching", "wrong", "wildcard"})
|
||||
void foreignCallbacksDoNotRevealTheTokensResource(String policy) throws Exception {
|
||||
SfnClient owner = client("test", "test");
|
||||
String name = "foreign-callback-" + UUID.randomUUID();
|
||||
String role = executionRole(name);
|
||||
String activity = owner.createActivity(request -> request.name(name)).activityArn();
|
||||
cleanup.register(() -> owner.deleteActivity(request -> request.activityArn(activity)));
|
||||
String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Callback", "States", Map.of("Callback",
|
||||
Map.of("Type", "Task", "Resource", activity, "TimeoutSeconds", 60, "End", true))));
|
||||
String machine = owner.createStateMachine(request -> request.name(name).roleArn(role)
|
||||
.definition(definition)).stateMachineArn();
|
||||
cleanup.register(() -> owner.deleteStateMachine(request -> request.stateMachineArn(machine)));
|
||||
String resource = switch (policy) {
|
||||
case "matching" -> activity;
|
||||
case "wrong" -> activity + "-other";
|
||||
default -> "*";
|
||||
};
|
||||
AccessKey key = foreignUser(name, MAPPER.writeValueAsString(Map.of("Version", "2012-10-17",
|
||||
"Statement", List.of(statement("Allow", resource)))));
|
||||
SfnClient foreign = client(key.getAccessKeyId(), key.getSecretAccessKey());
|
||||
String execution = owner.startExecution(request -> request.stateMachineArn(machine)).executionArn();
|
||||
cleanup.register(() -> {
|
||||
if ("RUNNING".equals(owner.describeExecution(request -> request.executionArn(execution)).statusAsString())) {
|
||||
owner.stopExecution(request -> request.executionArn(execution));
|
||||
}
|
||||
});
|
||||
String token = owner.getActivityTask(request -> request.activityArn(activity)).taskToken();
|
||||
for (boolean completed : List.of(false, true)) {
|
||||
if (completed) {
|
||||
owner.sendTaskSuccess(request -> request.taskToken(token).output("{}"));
|
||||
assertEquals("SUCCEEDED", terminal(owner, execution));
|
||||
}
|
||||
for (String action : List.of("heartbeat", "success", "failure")) {
|
||||
SfnException denied = assertThrows(SfnException.class, () -> callback(foreign, action, token));
|
||||
assertEquals("AccessDeniedException", denied.awsErrorDetails().errorCode());
|
||||
assertEquals("Not authorized to access this resource.", denied.awsErrorDetails().errorMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private AccessKey foreignUser(String name, String policy) {
|
||||
String account = "111111111111";
|
||||
RequestScopes.runAs(account, () -> iam.createUser(name, "/"));
|
||||
cleanup.register(() -> RequestScopes.runAs(account, () -> iam.deleteUser(name)));
|
||||
RequestScopes.runAs(account, () -> iam.putUserPolicy(name, "callback", policy));
|
||||
cleanup.register(() -> RequestScopes.runAs(account, () -> iam.deleteUserPolicy(name, "callback")));
|
||||
AccessKey key = RequestScopes.callAs(account, () -> iam.createAccessKey(name));
|
||||
cleanup.register(() -> RequestScopes.runAs(account, () -> iam.deleteAccessKey(name, key.getAccessKeyId())));
|
||||
return key;
|
||||
}
|
||||
|
||||
private SfnClient client(String access, String secret) {
|
||||
SfnClient client = SfnClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.httpClientBuilder(UrlConnectionHttpClient.builder())
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(access, secret))).build();
|
||||
cleanup.register(client::close);
|
||||
return client;
|
||||
}
|
||||
|
||||
private String executionRole(String name) {
|
||||
IamClient iam = IamClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.httpClientBuilder(UrlConnectionHttpClient.builder())
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))).build();
|
||||
cleanup.register(iam::close);
|
||||
String role = iam.createRole(request -> request.roleName(name).assumeRolePolicyDocument("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole",
|
||||
"Principal":{"Service":"states.amazonaws.com"}}]}""")).role().arn();
|
||||
cleanup.register(() -> iam.deleteRole(request -> request.roleName(name)));
|
||||
iam.putRolePolicy(request -> request.roleName(name).policyName("queue").policyDocument("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sqs:SendMessage","Resource":"*"}]}"""));
|
||||
cleanup.register(() -> iam.deleteRolePolicy(request -> request.roleName(name).policyName("queue")));
|
||||
return role;
|
||||
}
|
||||
|
||||
private static Map<String, Object> statement(String effect, String resource) {
|
||||
return Map.of("Effect", effect, "Resource", resource,
|
||||
"Action", List.of("states:SendTaskHeartbeat", "states:SendTaskSuccess", "states:SendTaskFailure"));
|
||||
}
|
||||
|
||||
private static void callback(SfnClient actor, String action, String token) {
|
||||
switch (action) {
|
||||
case "heartbeat" -> actor.sendTaskHeartbeat(request -> request.taskToken(token));
|
||||
case "success" -> actor.sendTaskSuccess(request -> request.taskToken(token).output("{}"));
|
||||
case "failure" -> actor.sendTaskFailure(request -> request.taskToken(token).error("ExpectedFailure"));
|
||||
default -> throw new IllegalArgumentException(action);
|
||||
}
|
||||
}
|
||||
|
||||
private static String terminal(SfnClient admin, String execution) throws InterruptedException {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
|
||||
while (System.nanoTime() < deadline) {
|
||||
String status = admin.describeExecution(request -> request.executionArn(execution)).statusAsString();
|
||||
if (!"RUNNING".equals(status)) {
|
||||
return status;
|
||||
}
|
||||
Thread.sleep(10);
|
||||
}
|
||||
return fail("callback did not finish its execution");
|
||||
}
|
||||
}
|
||||
+53
-8
@@ -7,8 +7,11 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
@@ -27,15 +30,52 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
class StepFunctionsCallbackTokenTest {
|
||||
private static final String OWNER = "111111111111";
|
||||
private static final String RESOURCE = "arn:aws:states:us-east-1:" + OWNER + ":stateMachine:callback";
|
||||
private final RegionResolver resolver = mock(RegionResolver.class);
|
||||
private final StepFunctionsService service = new StepFunctionsService(mock(StorageFactory.class),
|
||||
resolver, mock(AslExecutor.class), new ObjectMapper(), mock(SfnMockLoader.class),
|
||||
mock(StepFunctionsEventPublisher.class));
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"arn:aws:states:us-east-1:111111111111:stateMachine:callback,arn:aws:states:us-east-1:111111111111:stateMachine:callback",
|
||||
"arn:aws:states:us-east-1:111111111111:stateMachine:callback:7,arn:aws:states:us-east-1:111111111111:stateMachine:callback",
|
||||
"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.getAccountId()).thenReturn(OWNER);
|
||||
CompletableFuture<JsonNode> future = service.registerPendingToken("resource", OWNER, resource);
|
||||
assertEquals(expected, service.callbackResourceArn("resource", OWNER));
|
||||
assertFalse(future.isDone());
|
||||
service.sendTaskSuccess("resource", "{}");
|
||||
assertEquals(expected, service.callbackResourceArn("resource", OWNER));
|
||||
service.discardPendingToken("resource");
|
||||
assertEquals(expected, service.callbackResourceArn("resource", OWNER));
|
||||
service.clear();
|
||||
refuses("InvalidToken", () -> service.callbackResourceArn("resource", OWNER));
|
||||
refuses("InvalidToken", () -> service.callbackResourceArn(null, OWNER));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"activity", "statemachine"})
|
||||
void storedLookupSelectsTheTokenResourceAndEnforcesItsOwner(String type) {
|
||||
when(resolver.getAccountId()).thenReturn(OWNER);
|
||||
service.registerPendingToken("stored", OWNER, RESOURCE);
|
||||
assertEquals("states", service.namespace());
|
||||
assertEquals(Optional.empty(), service.find(type, List.of("new-resource"), "us-east-1"));
|
||||
refuses("InvalidToken", () -> service.findByMembers(type, List.of(), "us-east-1"));
|
||||
assertEquals(Optional.of(RESOURCE), service.findByMembers(type, List.of("stored"), "us-east-1"));
|
||||
assertEquals(Optional.empty(), service.findByMembers("execution", List.of("stored"), "us-east-1"));
|
||||
refuses("InvalidToken", () -> service.findByMembers(type, List.of("unknown"), "us-east-1"));
|
||||
when(resolver.getAccountId()).thenReturn("222222222222");
|
||||
refuses("AccessDeniedException", () -> service.findByMembers(type, List.of("stored"), "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void foreignCallbacksCannotClaimOrRefreshAnOwnedToken() throws Exception {
|
||||
CompletableFuture<JsonNode> future = service.registerPendingToken("owned", OWNER);
|
||||
CompletableFuture<JsonNode> future = service.registerPendingToken("owned", OWNER, RESOURCE);
|
||||
long heartbeat = service.lastTaskHeartbeatNanos("owned");
|
||||
refuses("AccessDeniedException", () -> service.callbackResourceArn("owned", "222222222222"));
|
||||
when(resolver.getAccountId()).thenReturn("222222222222");
|
||||
refuses("AccessDeniedException", () -> service.sendTaskSuccess("owned", "{}"));
|
||||
refuses("AccessDeniedException", () -> service.sendTaskFailure("owned", "cause", "error"));
|
||||
@@ -52,16 +92,19 @@ class StepFunctionsCallbackTokenTest {
|
||||
refuses("TaskTimedOut", () -> service.sendTaskHeartbeat("owned"));
|
||||
when(resolver.getAccountId()).thenReturn("222222222222");
|
||||
refuses("AccessDeniedException", () -> service.sendTaskHeartbeat("owned"));
|
||||
refuses("AccessDeniedException", () -> service.callbackResourceArn("owned", "222222222222"));
|
||||
service.discardPendingToken("owned");
|
||||
refuses("AccessDeniedException", () -> service.callbackResourceArn("owned", "222222222222"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failureAndDiscardCloseTokensAndUnknownTokensRefuse() {
|
||||
when(resolver.getAccountId()).thenReturn(OWNER);
|
||||
CompletableFuture<JsonNode> failed = service.registerPendingToken("failed", OWNER);
|
||||
CompletableFuture<JsonNode> failed = service.registerPendingToken("failed", OWNER, RESOURCE);
|
||||
service.sendTaskFailure("failed", "cause", "error");
|
||||
assertTrue(failed.isCompletedExceptionally());
|
||||
refuses("TaskTimedOut", () -> service.sendTaskSuccess("failed", "{}"));
|
||||
service.registerPendingToken("expired", OWNER);
|
||||
service.registerPendingToken("expired", OWNER, RESOURCE);
|
||||
service.discardPendingToken("expired");
|
||||
refuses("TaskTimedOut", () -> service.sendTaskHeartbeat("expired"));
|
||||
refuses("InvalidToken", () -> service.sendTaskHeartbeat(null));
|
||||
@@ -72,7 +115,7 @@ class StepFunctionsCallbackTokenTest {
|
||||
@Test
|
||||
void racingCallbacksCompleteExactlyOnce() throws Exception {
|
||||
when(resolver.getAccountId()).thenReturn(OWNER);
|
||||
CompletableFuture<JsonNode> future = service.registerPendingToken("race", OWNER);
|
||||
CompletableFuture<JsonNode> future = service.registerPendingToken("race", OWNER, RESOURCE);
|
||||
CountDownLatch ready = new CountDownLatch(2);
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
AtomicInteger accepted = new AtomicInteger();
|
||||
@@ -121,8 +164,8 @@ class StepFunctionsCallbackTokenTest {
|
||||
assertTrue(finishParsing.await(5, TimeUnit.SECONDS));
|
||||
return new ObjectMapper().readTree("{}");
|
||||
});
|
||||
CompletableFuture<JsonNode> slow = callbacks.registerPendingToken("slow", OWNER);
|
||||
callbacks.registerPendingToken("other", OWNER);
|
||||
CompletableFuture<JsonNode> slow = callbacks.registerPendingToken("slow", OWNER, RESOURCE);
|
||||
callbacks.registerPendingToken("other", OWNER, RESOURCE);
|
||||
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
|
||||
Future<?> success = executor.submit(() -> callbacks.sendTaskSuccess("slow", "{}"));
|
||||
try {
|
||||
@@ -145,7 +188,7 @@ class StepFunctionsCallbackTokenTest {
|
||||
@ValueSource(strings = {"{invalid", "", "[1,"})
|
||||
void rejectedOutputDoesNotConsumeTheToken(String output) throws Exception {
|
||||
when(resolver.getAccountId()).thenReturn(OWNER);
|
||||
CompletableFuture<JsonNode> future = service.registerPendingToken("output", OWNER);
|
||||
CompletableFuture<JsonNode> future = service.registerPendingToken("output", OWNER, RESOURCE);
|
||||
refuses("InvalidOutput", () -> service.sendTaskSuccess("output", output));
|
||||
assertFalse(future.isDone());
|
||||
service.sendTaskHeartbeat("output");
|
||||
@@ -159,11 +202,13 @@ class StepFunctionsCallbackTokenTest {
|
||||
when(resolver.getAccountId()).thenReturn(OWNER);
|
||||
for (int index = 0; index <= 1024; index++) {
|
||||
String token = "closed-" + index;
|
||||
service.registerPendingToken(token, OWNER);
|
||||
service.registerPendingToken(token, OWNER, RESOURCE);
|
||||
service.discardPendingToken(token);
|
||||
}
|
||||
refuses("InvalidToken", () -> service.sendTaskHeartbeat("closed-0"));
|
||||
refuses("TaskTimedOut", () -> service.sendTaskHeartbeat("closed-1024"));
|
||||
refuses("InvalidToken", () -> service.callbackResourceArn("closed-0", OWNER));
|
||||
assertEquals(RESOURCE, service.callbackResourceArn("closed-1024", OWNER));
|
||||
service.clear();
|
||||
refuses("InvalidToken", () -> service.sendTaskHeartbeat("closed-1024"));
|
||||
}
|
||||
|
||||
@@ -261,6 +261,12 @@ NOT_COVERED: dict[str, str] = {
|
||||
# them apart (EventBridge's `events` and EventBridge V2's `eventsv2`): Floci applies it only to a request the service
|
||||
# of that endpoint serves, never by a member a caller could add to a request of the other.
|
||||
CORRECTIONS: dict[str, tuple[list[dict], str]] = {
|
||||
**{f"states:{operation}": ([{"type": kind, "fill": {}, "find": ["taskToken"]}
|
||||
for kind in ("activity", "statemachine")],
|
||||
"AWS callback policy probes on 2026-11-02 authorize an activity token against its "
|
||||
"activity and an integration token against its unqualified state machine, despite "
|
||||
"the action table listing no resource types; the token's service resolves the ARN")
|
||||
for operation in ("SendTaskSuccess", "SendTaskFailure", "SendTaskHeartbeat")},
|
||||
"elasticloadbalancing:CreateLoadBalancer": ([
|
||||
{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}},
|
||||
{"type": "loadbalancer/app/", "fill": {"LoadBalancerName": "Name"}, "when": {"Type": ["application", None]}},
|
||||
@@ -1072,7 +1078,8 @@ def _resource_problems(operation: str, resource: object, types: set[str], format
|
||||
return [f"{operation} reads its members before {before!r}, which is no one character"]
|
||||
named = resource.get("types") or [resource.get("type")]
|
||||
kinds = _kinds(resource)
|
||||
if len(kinds) != len(named) or not all(kind in types and kind in formats for kind in kinds):
|
||||
corrected = resource in CORRECTIONS.get(operation, ([], ""))[0]
|
||||
if len(kinds) != len(named) or not all((kind in types or corrected) and kind in formats for kind in kinds):
|
||||
return [f"{operation} names {named}, not resource types its action acts on with an ARN format"]
|
||||
if "arn" in resource:
|
||||
if not isinstance(resource["arn"], str) or not ARN_PATH_RE.match(resource["arn"]):
|
||||
|
||||
@@ -652,3 +652,22 @@ def test_the_vendored_file_is_well_formed():
|
||||
# The v2 API's Type picks the load balancer it creates, application when it gives none.
|
||||
assert operations["elasticloadbalancing:CreateLoadBalancer"]["resources"][1] == {
|
||||
"type": "loadbalancer/app/", "fill": {"LoadBalancerName": "Name"}, "when": {"Type": ["application", None]}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation", ["SendTaskSuccess", "SendTaskFailure", "SendTaskHeartbeat"])
|
||||
def test_callback_resources_are_resolved_from_the_token(operation):
|
||||
resources, reason = r.CORRECTIONS[f"states:{operation}"]
|
||||
assert resources == [{"type": kind, "fill": {}, "find": ["taskToken"]}
|
||||
for kind in ("activity", "statemachine")]
|
||||
assert "2026-11-02" in reason
|
||||
assert "no resource types" in reason
|
||||
|
||||
|
||||
def test_measured_callback_correction_retains_action_metadata_and_rejects_unlisted_resources():
|
||||
formats = {"activity": "arn:${Partition}:states:${Region}:${Account}:activity:${ActivityName}",
|
||||
"statemachine": "arn:${Partition}:states:${Region}:${Account}:stateMachine:${StateMachineName}"}
|
||||
resource = {"type": "activity", "fill": {}, "find": ["taskToken"]}
|
||||
assert not r._resource_problems("states:SendTaskSuccess", resource, [], formats)
|
||||
assert r._resource_problems("states:SendTaskSuccess", {**resource, "find": ["otherToken"]}, [], formats)
|
||||
assert r._resource_problems("states:OtherOperation", resource, [], formats)
|
||||
assert r._resource_problems("states:SendTaskSuccess", resource, [], {})
|
||||
Reference in new issue
Block a user