fix(stepfunctions): page GetExecutionHistory and honor reverseOrder (#6555)

* fix(stepfunctions): page GetExecutionHistory and honor reverseOrder

GetExecutionHistory read only executionArn and includeExecutionData.
Every call returned the whole history, oldest event first: maxResults
and nextToken were ignored, and reverseOrder=true still listed
ExecutionStarted first, so a caller asking for the newest event with
reverseOrder and maxResults=1 got the oldest one instead. The API
reference pages the history by 100 events unless maxResults says
otherwise, allows at most 1,000, returns a nextToken while events
remain, and lists the newest event first under reverseOrder.

Page the history by event id. Ids rise in the order events are
recorded, so a page starts after the last event the previous page
returned, even while the execution is still recording events. An
omitted or zero maxResults uses 100; a maxResults outside 0 to 1,000
or a nextToken outside 1 to 1,024 characters is a ValidationException,
as for ListActivities. A token names its execution and its
reverseOrder, so it is refused with InvalidToken for any other, while
maxResults and includeExecutionData may change from one page to the
next.

Tokens are signed with SignedMarkers and carry their issue time. An
edited token, one issued before a restart, or one issued more than 24
hours earlier is refused with InvalidToken; the 24-hour expiry is the
one the API reference documents. The execution is named in the token
by the SHA-256 of its ARN, so a token stays under 200 characters
however long the state machine and execution names are.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(stepfunctions): page execution history with the SDK paginator

Run a 60-state execution, whose history of 122 events is longer than
one default page, and read it with the AWS SDK for Java: a plain call
returns 100 events and a nextToken, the paginator at 25 events a page
returns every event once, oldest first or with reverseOrder newest
first, and reverseOrder with maxResults=1 returns ExecutionSucceeded
with a token for the rest.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(stepfunctions): give the ListExecutions filter test a clock

StepFunctionsListExecutionsFilterTest, merged from upstream main, built
the handler with the two-argument constructor. On this branch the
handler takes the application Clock for the lifetime of execution
history tokens, so the merged tree did not compile. Pass the system
clock, which ListExecutions does not read.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(stepfunctions): pin the page-size checks of ListActivities and history

ListActivities and GetExecutionHistory each check maxResults and
nextToken on their own, with the same bounds and messages, and page by
100 when maxResults is omitted or 0. Pin the messages of both and the
ListActivities default before the two move onto one helper.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* refactor(stepfunctions): share the page-size checks of ListActivities and history

ListActivities and GetExecutionHistory each checked that maxResults is
0 to 1,000 and nextToken 1 to 1,024 characters, with the same messages,
and turned an omitted or zero maxResults into 100. Move that into
StepFunctionsPaging.pageSize, which validates the pair and returns the
page size, so the other Step Functions list operations can use it
later. Behaviour, messages and the order of the checks are unchanged.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(stepfunctions): say why the paginator test ignores cleanup failures

The SDK paginator test deleted its state machine in a catch-all that
neither logged nor explained the failure it ignored. Say why it is
safe: the state machine has a unique name, and a cleanup failure must
not hide the test's own result.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(stepfunctions): pin the page-size bounds and the order of the checks

Pin that ListActivities and GetExecutionHistory accept the bounds
themselves (a 1- or 1,024-character nextToken reaches the token
lookup, and ListActivities takes maxResults=1000), and that both read
maxResults and nextToken before bounding either. The test's cleanup
deletes its activities without asserting, so a failed delete can no
longer hide the test's own failure.

The last check is the one place where the shared helper changed
behaviour, which the commit that added it wrongly said it did not. A
history request with maxResults=1001 and a non-string nextToken used
to report the maxResults bound; it now reports "nextToken must be a
string.", as ListActivities always has. The new test fails that way
on the commit before the helper and passes after it.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* docs(stepfunctions): describe StepFunctionsPaging by its two callers

The class comment said every Step Functions list operation shares this
page request. Only ListActivities and GetExecutionHistory do;
ListStateMachineAliases still checks its own bounds. Name the two
callers and say that both fields are read before either is bounded.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(stepfunctions): share one request helper between the paging tests

StepFunctionsPageSizeIntegrationTest and
StepFunctionsExecutionHistoryPaginationIntegrationTest each carried
the same private call() and content type. Add StepFunctionsRequests in
the testing package, as CfnRequests and EmrRequests serve their
services, and move both tests onto its sfn(action, body). The requests
they send are unchanged.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(stepfunctions): take the request body of sfn() as a map

sfn() took any Object and said it serializes the body as JSON, which
holds for a map but not for a string, which RestAssured sends as is.
Both callers pass maps, as the private helpers it replaced took, so
type the parameter as Map<String, ?>.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

---------

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-25 22:37:10 -04:00
1 parent c5e873ff84
commit 47226f76d1
10 files changed
+629 -10

No files matched your search

@@ -270,6 +270,59 @@ class StepFunctionsExecutionHistoryTest {
}
}
/**
* GetExecutionHistory pages by 100 events unless maxResults says otherwise, and reverseOrder
* starts from the newest event. The SDK paginator follows nextToken to the last page in either
* order.
*/
@Test
void historyPagesThroughTheSdkPaginatorInBothOrders() throws Exception {
StringBuilder states = new StringBuilder();
for (int index = 0; index < 60; index++) {
states.append(index == 0 ? "" : ",").append("\"S%02d\": {\"Type\": \"Pass\", %s}".formatted(
index, index < 59 ? "\"Next\": \"S%02d\"".formatted(index + 1) : "\"End\": true"));
}
String smArn = sfn.createStateMachine(b -> b
.name(TestFixtures.uniqueName("sfn-history-pages-sm"))
.definition("{\"StartAt\": \"S00\", \"States\": {" + states + "}}")
.roleArn(ROLE_ARN)).stateMachineArn();
try {
String execArn = sfn.startExecution(b -> b.stateMachineArn(smArn).input("{}")).executionArn();
assertThat(pollUntilDone(execArn).status()).isEqualTo(ExecutionStatus.SUCCEEDED);
GetExecutionHistoryResponse firstPage = sfn.getExecutionHistory(b -> b.executionArn(execArn));
assertThat(firstPage.events()).hasSize(100);
assertThat(firstPage.nextToken()).isNotNull();
List<Long> ids = sfn.getExecutionHistoryPaginator(b -> b.executionArn(execArn).maxResults(25))
.events().stream().map(HistoryEvent::id).toList();
List<Long> reversed = sfn.getExecutionHistoryPaginator(b -> b
.executionArn(execArn).reverseOrder(true).maxResults(25))
.events().stream().map(HistoryEvent::id).toList();
assertThat(ids).hasSize(122);
assertThat(reversed).hasSize(122);
for (int i = 0; i < ids.size(); i++) {
assertThat(ids.get(i)).isEqualTo(i + 1L);
assertThat(reversed.get(i)).isEqualTo(122L - i);
}
GetExecutionHistoryResponse newest = sfn.getExecutionHistory(b -> b
.executionArn(execArn).reverseOrder(true).maxResults(1));
assertThat(newest.events()).extracting(HistoryEvent::type)
.containsExactly(HistoryEventType.EXECUTION_SUCCEEDED);
assertThat(newest.events().get(0).id()).isEqualTo(122L);
assertThat(newest.nextToken()).isNotNull();
} finally {
try {
sfn.deleteStateMachine(b -> b.stateMachineArn(smArn));
} catch (Exception ignored) {
// Cleanup only: the state machine has a unique name, so one left behind cannot
// affect another test, and a failure here must not hide the test's own result.
}
}
}
private DescribeExecutionResponse pollUntilDone(String execArn) throws InterruptedException {
for (int i = 0; i < 120; i++) {
DescribeExecutionResponse resp = sfn.describeExecution(b -> b.executionArn(execArn));
+10
View File
@@ -166,6 +166,16 @@ records it for. A Distributed `Map` that declares no tolerance reports a failed
rather than AWS's `States.ExceedToleratedFailureThreshold`, and emits `MapRunFailed` with that
error. A `Map` that declares one reports `States.ExceedToleratedFailureThreshold`, as AWS does.
### Pages of history
`GetExecutionHistory` returns one page per call: `maxResults` events, 100 when it is omitted or
`0`, and at most 1,000. A `nextToken` comes back while events remain, and `reverseOrder` lists the
newest event first. A token belongs to its execution and its `reverseOrder`: used with another
execution or the other order it is refused with `InvalidToken`, while `maxResults` and
`includeExecutionData` may change from one page to the next. Each token expires 24 hours after it
was issued, as on AWS. Floci signs its tokens with a key it generates at startup, so an edited
token, or one issued before a restart, is refused with `InvalidToken` as well.
## Map concurrency
Map states honor `MaxConcurrency` and, for JSONPath state machines, `MaxConcurrencyPath`.
@@ -6,7 +6,9 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.SignedMarkers;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import io.github.hectorvent.floci.services.stepfunctions.model.Activity;
import io.github.hectorvent.floci.services.stepfunctions.model.ActivityTask;
@@ -21,7 +23,10 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import java.time.Clock;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
@@ -31,13 +36,18 @@ import java.util.Set;
@ApplicationScoped
public class StepFunctionsJsonHandler {
private static final Duration HISTORY_TOKEN_LIFETIME = Duration.ofHours(24);
private final StepFunctionsService service;
private final ObjectMapper objectMapper;
private final Clock clock;
private final SignedMarkers historyTokens = new SignedMarkers();
@Inject
public StepFunctionsJsonHandler(StepFunctionsService service, ObjectMapper objectMapper) {
public StepFunctionsJsonHandler(StepFunctionsService service, ObjectMapper objectMapper, Clock clock) {
this.service = service;
this.objectMapper = objectMapper;
this.clock = clock;
}
public Response handle(String action, JsonNode request, String region) {
@@ -481,6 +491,11 @@ public class StepFunctionsJsonHandler {
private Response handleGetExecutionHistory(JsonNode request) {
String arn = request.path("executionArn").asText();
boolean includeExecutionData = request.path("includeExecutionData").asBoolean(true);
boolean reverseOrder = parseOptionalBoolean(request, "reverseOrder", false);
Integer maxResults = parseOptionalInt(request, "maxResults");
String nextToken = optionalText(request, "nextToken");
int pageSize = StepFunctionsPaging.pageSize(maxResults, nextToken);
Long lastReturnedId = nextToken == null ? null : historyTokenPosition(nextToken, arn, reverseOrder);
List<HistoryEvent> live = service.getExecutionHistory(arn);
List<HistoryEvent> events;
@@ -488,9 +503,20 @@ public class StepFunctionsJsonHandler {
synchronized (live) {
events = new ArrayList<>(live);
}
if (reverseOrder) {
Collections.reverse(events);
}
// Ids rise in the order events were recorded, so a page starts at the first event listed
// after the last one the previous page returned, however many were recorded in between.
int start = 0;
while (lastReturnedId != null && start < events.size()
&& !listedAfter(events.get(start), lastReturnedId, reverseOrder)) {
start++;
}
int end = Math.min(events.size(), start + pageSize);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode array = response.putArray("events");
for (HistoryEvent e : events) {
for (HistoryEvent e : events.subList(start, end)) {
ObjectNode item = array.addObject();
item.put("id", e.getId());
item.put("timestamp", e.getTimestamp());
@@ -506,9 +532,49 @@ public class StepFunctionsJsonHandler {
item.set(historyEventDetailsField(e.getType()), objectMapper.valueToTree(details));
}
}
if (end < events.size()) {
response.put("nextToken", issueHistoryToken(arn, reverseOrder, events.get(end - 1).getId()));
}
return Response.ok(response).build();
}
private static boolean listedAfter(HistoryEvent event, long id, boolean reverseOrder) {
return reverseOrder ? event.getId() < id : event.getId() > id;
}
/**
* A history token names its execution, its order and the last event its page returned, and
* may be used with any page size and includeExecutionData. The execution is named by the
* SHA-256 of its ARN, so the token stays far below the 1,024 characters AWS allows however long
* the ARN is. Tokens are signed, so an edited one, or one issued before a restart, is refused,
* and each expires 24 hours after it was issued, as on AWS.
*/
private String issueHistoryToken(String arn, boolean reverseOrder, long lastReturnedId) {
return historyTokens.issue(
clock.millis() + ":" + historyTokenScope(arn, reverseOrder) + ":" + lastReturnedId);
}
private long historyTokenPosition(String nextToken, String arn, boolean reverseOrder) {
String issued = historyTokens.cursorOf(nextToken);
if (issued == null) {
throw invalidHistoryToken();
}
String[] fields = issued.split(":");
if (!fields[1].equals(historyTokenScope(arn, reverseOrder))
|| clock.millis() - Long.parseLong(fields[0]) > HISTORY_TOKEN_LIFETIME.toMillis()) {
throw invalidHistoryToken();
}
return Long.parseLong(fields[2]);
}
private static String historyTokenScope(String arn, boolean reverseOrder) {
return Digests.sha256Hex(arn) + (reverseOrder ? "-reverse" : "-forward");
}
private static AwsException invalidHistoryToken() {
return new AwsException("InvalidToken", "The provided token is not valid.", 400);
}
private static final Set<String> EXECUTION_DATA_FIELDS =
Set.of("input", "inputDetails", "output", "outputDetails");
private static final List<String> EXECUTION_STATUSES =
@@ -0,0 +1,29 @@
package io.github.hectorvent.floci.services.stepfunctions;
import io.github.hectorvent.floci.core.common.AwsException;
/**
* The page request ListActivities and GetExecutionHistory check: a {@code maxResults} of 0 to 1000,
* where 0 or none means 100, and a {@code nextToken} of 1 to 1024 characters. Callers read both
* fields before calling it, so a wrongly typed field is reported before either bound.
*/
final class StepFunctionsPaging {
private static final int DEFAULT_PAGE_SIZE = 100;
private static final int MAX_PAGE_SIZE = 1000;
private static final int MAX_TOKEN_LENGTH = 1024;
private StepFunctionsPaging() {
}
/** Validates the pair and returns the number of items a page holds. */
static int pageSize(Integer maxResults, String nextToken) {
if (maxResults != null && (maxResults < 0 || maxResults > MAX_PAGE_SIZE)) {
throw new AwsException("ValidationException", "maxResults must be between 0 and 1000.", 400);
}
if (nextToken != null && (nextToken.isEmpty() || nextToken.length() > MAX_TOKEN_LENGTH)) {
throw new AwsException("ValidationException", "nextToken length must be between 1 and 1024.", 400);
}
return maxResults == null || maxResults == 0 ? DEFAULT_PAGE_SIZE : maxResults;
}
}
@@ -1198,13 +1198,7 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
}
public PaginatedResult<Activity> listActivities(String region, Integer maxResults, String nextToken) {
if (maxResults != null && (maxResults < 0 || maxResults > 1000)) {
throw new AwsException("ValidationException", "maxResults must be between 0 and 1000.", 400);
}
if (nextToken != null && (nextToken.isEmpty() || nextToken.length() > 1024)) {
throw new AwsException("ValidationException", "nextToken length must be between 1 and 1024.", 400);
}
int pageSize = maxResults == null || maxResults == 0 ? 100 : maxResults;
int pageSize = StepFunctionsPaging.pageSize(maxResults, nextToken);
return Pagination.paginate(listActivities(region), Activity::getActivityArn, pageSize, nextToken,
"states:activities:" + region,
token -> new AwsException("InvalidToken", "Invalid nextToken.", 400));
@@ -0,0 +1,184 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
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.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.LongStream;
import static io.github.hectorvent.floci.testing.StepFunctionsRequests.sfn;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
@QuarkusTest
class StepFunctionsExecutionHistoryPaginationIntegrationTest {
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role";
private static final ObjectMapper MAPPER = new ObjectMapper();
// Sixty Pass states: ExecutionStarted, an Entered and an Exited event per state, and
// ExecutionSucceeded, so the history is longer than one default page of 100.
private static final int PASS_STATES = 60;
private static final int EVENTS = 2 * PASS_STATES + 2;
private static String executionArn;
private static String otherExecutionArn;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
// RestAssured is pointed at the test server per test, so the executions are started from the
// first test that runs rather than from @BeforeAll.
@BeforeEach
void runTwoLongExecutionsOnce() {
if (executionArn != null) {
return;
}
ObjectNode definition = MAPPER.createObjectNode().put("StartAt", step(0));
ObjectNode states = definition.putObject("States");
for (int index = 0; index < PASS_STATES; index++) {
ObjectNode state = states.putObject(step(index)).put("Type", "Pass");
if (index + 1 < PASS_STATES) {
state.put("Next", step(index + 1));
} else {
state.put("End", true);
}
}
String stateMachineArn = sfn("CreateStateMachine", Map.of(
"name", "history-pages-" + UUID.randomUUID(),
"definition", definition.toString(),
"roleArn", ROLE_ARN))
.then().statusCode(200).extract().path("stateMachineArn");
executionArn = runToCompletion(stateMachineArn);
otherExecutionArn = runToCompletion(stateMachineArn);
}
@Test
void defaultPagesCoverTheWholeHistoryOnceInOrder() {
List<Long> ids = new ArrayList<>();
List<Integer> pageSizes = new ArrayList<>();
String nextToken = null;
do {
Response page = history(nextToken == null ? Map.of() : Map.of("nextToken", nextToken));
List<Long> pageIds = ids(page);
pageSizes.add(pageIds.size());
ids.addAll(pageIds);
nextToken = page.path("nextToken");
} while (nextToken != null);
assertEquals(List.of(100, EVENTS - 100), pageSizes, "an omitted maxResults pages by 100");
assertEquals(LongStream.rangeClosed(1, EVENTS).boxed().toList(), ids);
}
@Test
void reverseOrderPagesFromTheNewestEvent() {
List<Long> ids = new ArrayList<>();
String nextToken = null;
do {
Map<String, Object> request = new HashMap<>(Map.of("reverseOrder", true, "maxResults", 50));
if (nextToken != null) {
request.put("nextToken", nextToken);
}
Response page = history(request);
if (ids.isEmpty()) {
assertEquals("ExecutionSucceeded", page.path("events[0].type"));
}
ids.addAll(ids(page));
nextToken = page.path("nextToken");
} while (nextToken != null);
assertEquals(LongStream.rangeClosed(1, EVENTS).map(id -> EVENTS + 1 - id).boxed().toList(), ids);
}
@Test
void maxResultsOfZeroUsesTheDefaultAndOneThousandIsTheMaximum() {
assertEquals(100, ids(history(Map.of("maxResults", 0))).size());
Response everything = history(Map.of("maxResults", 1000));
assertEquals(EVENTS, ids(everything).size());
assertNull(everything.path("nextToken"));
for (Object maxResults : List.of(-1, 1001, 4294967296L, "1")) {
assertEquals("ValidationException", error(Map.of("maxResults", maxResults)));
}
}
@Test
void aTokenKeepsItsPlaceWhenThePageSizeOrExecutionDataChanges() {
String nextToken = history(Map.of("maxResults", 1)).path("nextToken");
assertNotNull(nextToken, "a page shorter than the history carries a token");
Response next = history(Map.of("nextToken", nextToken, "maxResults", 3, "includeExecutionData", false));
assertEquals(List.of(2L, 3L, 4L), ids(next));
assertEquals("PassStateEntered", next.path("events[0].type"));
assertFalse(next.jsonPath().getMap("events[0].stateEnteredEventDetails").containsKey("input"));
assertEquals(step(0), next.path("events[0].stateEnteredEventDetails.name"));
}
@Test
void aTokenIsBoundToItsExecutionAndDirection() {
String nextToken = history(Map.of("maxResults", 1)).path("nextToken");
assertNotNull(nextToken, "a page shorter than the history carries a token");
assertEquals("InvalidToken", error(Map.of("nextToken", nextToken, "reverseOrder", true)));
assertEquals("InvalidToken", sfn("GetExecutionHistory",
Map.of("executionArn", otherExecutionArn, "nextToken", nextToken))
.then().statusCode(400).extract().path("__type"));
}
@Test
void malformedTokensAreRejected() {
assertEquals("ValidationException", error(Map.of("nextToken", "")));
assertEquals("ValidationException", error(Map.of("nextToken", "x".repeat(1025))));
assertEquals("InvalidToken", error(Map.of("nextToken", "not-a-valid-token")));
String nextToken = history(Map.of("maxResults", 1)).path("nextToken");
// A middle character: the last one may carry only padding bits, which decoding ignores.
int middle = nextToken.length() / 2;
String edited = nextToken.substring(0, middle) + (nextToken.charAt(middle) == 'A' ? 'B' : 'A')
+ nextToken.substring(middle + 1);
assertEquals("InvalidToken", error(Map.of("nextToken", edited)));
}
private static String runToCompletion(String stateMachineArn) {
String arn = sfn("StartExecution", Map.of(
"stateMachineArn", stateMachineArn, "input", "{\"payload\":\"visible\"}"))
.then().statusCode(200).extract().path("executionArn");
await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100)).until(() ->
"SUCCEEDED".equals(sfn("DescribeExecution", Map.of("executionArn", arn))
.then().statusCode(200).extract().path("status")));
return arn;
}
private static String step(int index) {
return "Step%02d".formatted(index);
}
private static Response history(Map<String, Object> parameters) {
Map<String, Object> request = new HashMap<>(parameters);
request.put("executionArn", executionArn);
return sfn("GetExecutionHistory", request).then().statusCode(200).extract().response();
}
private static String error(Map<String, Object> parameters) {
Map<String, Object> request = new HashMap<>(parameters);
request.put("executionArn", executionArn);
return sfn("GetExecutionHistory", request).then().statusCode(400).extract().path("__type");
}
private static List<Long> ids(Response page) {
return page.jsonPath().getList("events.id", Long.class);
}
}
@@ -0,0 +1,152 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Base64Url;
import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class StepFunctionsExecutionHistoryTokenTest {
private static final String ARN = "arn:aws:states:us-east-1:000000000000:execution:tokens:run";
private static final long ISSUED = 1_790_000_000_000L;
private static final long DAY = Duration.ofHours(24).toMillis();
private final ObjectMapper mapper = new ObjectMapper();
private final StepFunctionsService service = mock(StepFunctionsService.class);
private final Clock clock = mock(Clock.class);
private StepFunctionsJsonHandler handler;
@BeforeEach
void setUp() {
when(service.getExecutionHistory(ARN)).thenReturn(events(5));
when(clock.millis()).thenReturn(ISSUED);
handler = new StepFunctionsJsonHandler(service, mapper, clock);
}
@Test
void aTokenExpiresTwentyFourHoursAfterItWasIssued() {
String token = firstPageToken();
when(clock.millis()).thenReturn(ISSUED + DAY);
assertEquals(2, page(token).path("events").get(0).path("id").asLong());
when(clock.millis()).thenReturn(ISSUED + DAY + 1);
assertInvalid(handler, token);
}
@Test
void eachTokenCountsItsLifetimeFromItsOwnPage() {
String first = firstPageToken();
when(clock.millis()).thenReturn(ISSUED + Duration.ofHours(20).toMillis());
String second = page(first).path("nextToken").asText();
when(clock.millis()).thenReturn(ISSUED + Duration.ofHours(30).toMillis());
assertInvalid(handler, first);
assertEquals(3, page(second).path("events").get(0).path("id").asLong());
}
@Test
void aTokenIssuedBeforeARestartIsRefused() {
String token = firstPageToken();
assertInvalid(new StepFunctionsJsonHandler(service, mapper, clock), token);
}
@Test
void aTokenWhoseIssueTimeWasMovedForwardIsRefused() {
String token = firstPageToken();
String decoded = new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);
String refreshed = Base64Url.encode(decoded.replaceFirst("^" + ISSUED, String.valueOf(ISSUED + DAY)));
when(clock.millis()).thenReturn(ISSUED + DAY + 1);
assertInvalid(handler, refreshed);
}
@Test
void pagesResumeAfterTheirLastEventWhileTheExecutionRecordsMore() {
List<HistoryEvent> recording = new ArrayList<>(events(5));
when(service.getExecutionHistory(ARN)).thenReturn(recording);
String forward = history(handler, request().put("maxResults", 2)).path("nextToken").asText();
String reverse = history(handler, request().put("maxResults", 2).put("reverseOrder", true))
.path("nextToken").asText();
recording.addAll(events(7).subList(5, 7));
JsonNode forwardRest = history(handler, request().put("maxResults", 10).put("nextToken", forward));
assertEquals(List.of(3L, 4L, 5L, 6L, 7L), ids(forwardRest));
assertFalse(forwardRest.has("nextToken"));
JsonNode reverseRest = history(handler, request().put("maxResults", 10).put("reverseOrder", true)
.put("nextToken", reverse));
assertEquals(List.of(3L, 2L, 1L), ids(reverseRest));
assertFalse(reverseRest.has("nextToken"));
}
@Test
void aTokenStaysShortForTheLongestNames() {
// A state machine or an execution name may be 80 characters long, and each of these takes
// three bytes in UTF-8.
String arn = "arn:aws:states:us-east-1:000000000000:execution:" + "\u3042".repeat(80) + ":"
+ "\u3044".repeat(80);
when(service.getExecutionHistory(arn)).thenReturn(events(5));
ObjectNode request = mapper.createObjectNode().put("executionArn", arn).put("maxResults", 1);
String token = history(handler, request).path("nextToken").asText();
assertTrue(token.length() < 256, "token of " + token.length() + " characters");
assertEquals(List.of(2L), ids(history(handler, request.put("nextToken", token))));
}
private static List<HistoryEvent> events(int size) {
List<HistoryEvent> events = new ArrayList<>();
for (long id = 1; id <= size; id++) {
HistoryEvent event = new HistoryEvent();
event.setId(id);
event.setType("PassStateEntered");
events.add(event);
}
return events;
}
private String firstPageToken() {
return history(handler, request().put("maxResults", 1)).path("nextToken").asText();
}
private JsonNode page(String token) {
return history(handler, request().put("maxResults", 1).put("nextToken", token));
}
private ObjectNode request() {
return mapper.createObjectNode().put("executionArn", ARN);
}
private static List<Long> ids(JsonNode page) {
List<Long> ids = new ArrayList<>();
page.path("events").forEach(event -> ids.add(event.path("id").asLong()));
return ids;
}
private static JsonNode history(StepFunctionsJsonHandler target, ObjectNode request) {
return (JsonNode) target.handle("GetExecutionHistory", request, "us-east-1").getEntity();
}
private void assertInvalid(StepFunctionsJsonHandler target, String token) {
AwsException error = assertThrows(AwsException.class,
() -> history(target, request().put("nextToken", token)));
assertEquals("InvalidToken", error.getErrorCode());
}
}
@@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.time.Clock;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -28,7 +29,7 @@ class StepFunctionsListExecutionsFilterTest {
@BeforeEach
void setUp() {
service = mock(StepFunctionsService.class);
handler = new StepFunctionsJsonHandler(service, mapper);
handler = new StepFunctionsJsonHandler(service, mapper, Clock.systemUTC());
when(service.listExecutions(ARN)).thenReturn(
List.of("RUNNING", "SUCCEEDED", "FAILED", "TIMED_OUT", "ABORTED").stream()
.map(status -> {
@@ -0,0 +1,111 @@
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 org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.github.hectorvent.floci.testing.StepFunctionsRequests.sfn;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* ListActivities and GetExecutionHistory bound maxResults and nextToken the same way, with the
* same length messages and in the same order, and page by 100 when maxResults is omitted or 0.
* The history's default page is pinned by StepFunctionsExecutionHistoryPaginationIntegrationTest.
*/
@QuarkusTest
class StepFunctionsPageSizeIntegrationTest {
// Validation comes before the execution is looked up, so no execution needs to exist.
private static final String EXECUTION_ARN =
"arn:aws:states:us-east-1:000000000000:execution:page-size:" + UUID.randomUUID();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@ParameterizedTest
@ValueSource(strings = {"ListActivities", "GetExecutionHistory"})
void maxResultsOutsideZeroToOneThousandIsRefused(String action) {
for (int maxResults : List.of(-1, 1001)) {
assertRefused(action, Map.of("maxResults", maxResults), "maxResults must be between 0 and 1000.");
}
}
@ParameterizedTest
@ValueSource(strings = {"ListActivities", "GetExecutionHistory"})
void nextTokenOutsideOneToOneThousandTwentyFourCharactersIsRefused(String action) {
for (String nextToken : List.of("", "x".repeat(1025))) {
assertRefused(action, Map.of("nextToken", nextToken), "nextToken length must be between 1 and 1024.");
}
}
@ParameterizedTest
@ValueSource(strings = {"ListActivities", "GetExecutionHistory"})
void theBoundsThemselvesAreAccepted(String action) {
// A token of 1 or 1,024 characters passes the length check and is then refused as unknown.
for (String nextToken : List.of("x", "x".repeat(1024))) {
assertEquals("InvalidToken", errorType(action, Map.of("nextToken", nextToken)));
}
if ("ListActivities".equals(action)) {
sfn(action, Map.of("maxResults", 1000)).then().statusCode(200);
}
}
@ParameterizedTest
@ValueSource(strings = {"ListActivities", "GetExecutionHistory"})
void bothFieldsAreReadBeforeEitherIsBounded(String action) {
assertRefused(action, Map.of("maxResults", 1001, "nextToken", 5), "nextToken must be a string.");
}
@Test
void listActivitiesPagesByOneHundredWhenMaxResultsIsOmittedOrZero() {
List<String> arns = new ArrayList<>();
try {
for (int index = 0; index < 101; index++) {
arns.add(sfn("CreateActivity", Map.of("name", "page-size-" + UUID.randomUUID()))
.then().statusCode(200).extract().path("activityArn"));
}
for (Map<String, Object> request : List.of(Map.<String, Object>of(), Map.<String, Object>of("maxResults", 0))) {
Response page = sfn("ListActivities", request).then().statusCode(200).extract().response();
assertEquals(100, page.jsonPath().getList("activities").size());
assertNotNull(page.path("nextToken"));
}
} finally {
// Best effort, unasserted, so a failed delete can neither hide the test's own failure
// nor stop the remaining deletes.
for (String arn : arns) {
sfn("DeleteActivity", Map.of("activityArn", arn));
}
}
}
private static void assertRefused(String action, Map<String, Object> parameters, String message) {
Response response = refused(action, parameters);
assertEquals("ValidationException", response.path("__type"));
assertEquals(message, response.path("message"));
}
private static String errorType(String action, Map<String, Object> parameters) {
return refused(action, parameters).path("__type");
}
private static Response refused(String action, Map<String, Object> parameters) {
Map<String, Object> body = new HashMap<>(parameters);
if ("GetExecutionHistory".equals(action)) {
body.put("executionArn", EXECUTION_ARN);
}
return sfn(action, body).then().statusCode(400).extract().response();
}
}
@@ -0,0 +1,19 @@
package io.github.hectorvent.floci.testing;
import io.restassured.response.Response;
import java.util.Map;
import static io.restassured.RestAssured.given;
/** One Step Functions JSON-protocol call in the default Region. */
public final class StepFunctionsRequests {
private StepFunctionsRequests() {}
/** Posts {@code body}, serialized as a JSON object, as the {@code action} request. */
public static Response sfn(String action, Map<String, ?> body) {
return given().contentType("application/x-amz-json-1.0")
.header("X-Amz-Target", "AWSStepFunctions." + action)
.body(body).when().post("/");
}
}