diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StepFunctionsExecutionHistoryTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StepFunctionsExecutionHistoryTest.java index c6b2435c39..a39c3e8361 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StepFunctionsExecutionHistoryTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/StepFunctionsExecutionHistoryTest.java @@ -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 ids = sfn.getExecutionHistoryPaginator(b -> b.executionArn(execArn).maxResults(25)) + .events().stream().map(HistoryEvent::id).toList(); + List 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)); diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md index 9e4252f2bd..9761105b2e 100644 --- a/docs/services/step-functions.md +++ b/docs/services/step-functions.md @@ -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`. diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonHandler.java index ad434c4544..c4b0ce625f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonHandler.java @@ -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 live = service.getExecutionHistory(arn); List 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 EXECUTION_DATA_FIELDS = Set.of("input", "inputDetails", "output", "outputDetails"); private static final List EXECUTION_STATUSES = diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsPaging.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsPaging.java new file mode 100644 index 0000000000..d6983f0f77 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsPaging.java @@ -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; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java index 142849dece..70d486a708 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java @@ -1198,13 +1198,7 @@ public class StepFunctionsService implements Resettable, ResourceProvider { } public PaginatedResult 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)); diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsExecutionHistoryPaginationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsExecutionHistoryPaginationIntegrationTest.java new file mode 100644 index 0000000000..e3174f49ec --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsExecutionHistoryPaginationIntegrationTest.java @@ -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 ids = new ArrayList<>(); + List pageSizes = new ArrayList<>(); + String nextToken = null; + do { + Response page = history(nextToken == null ? Map.of() : Map.of("nextToken", nextToken)); + List 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 ids = new ArrayList<>(); + String nextToken = null; + do { + Map 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 parameters) { + Map request = new HashMap<>(parameters); + request.put("executionArn", executionArn); + return sfn("GetExecutionHistory", request).then().statusCode(200).extract().response(); + } + + private static String error(Map parameters) { + Map request = new HashMap<>(parameters); + request.put("executionArn", executionArn); + return sfn("GetExecutionHistory", request).then().statusCode(400).extract().path("__type"); + } + + private static List ids(Response page) { + return page.jsonPath().getList("events.id", Long.class); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsExecutionHistoryTokenTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsExecutionHistoryTokenTest.java new file mode 100644 index 0000000000..58f03aa9a9 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsExecutionHistoryTokenTest.java @@ -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 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 events(int size) { + List 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 ids(JsonNode page) { + List 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()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsListExecutionsFilterTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsListExecutionsFilterTest.java index 702f32d417..1b3eff67f4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsListExecutionsFilterTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsListExecutionsFilterTest.java @@ -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 -> { diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsPageSizeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsPageSizeIntegrationTest.java new file mode 100644 index 0000000000..016bd0ad33 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsPageSizeIntegrationTest.java @@ -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 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 request : List.of(Map.of(), Map.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 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 parameters) { + return refused(action, parameters).path("__type"); + } + + private static Response refused(String action, Map parameters) { + Map body = new HashMap<>(parameters); + if ("GetExecutionHistory".equals(action)) { + body.put("executionArn", EXECUTION_ARN); + } + return sfn(action, body).then().statusCode(400).extract().response(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/testing/StepFunctionsRequests.java b/src/test/java/io/github/hectorvent/floci/testing/StepFunctionsRequests.java new file mode 100644 index 0000000000..6b48a236e5 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/testing/StepFunctionsRequests.java @@ -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 body) { + return given().contentType("application/x-amz-json-1.0") + .header("X-Amz-Target", "AWSStepFunctions." + action) + .body(body).when().post("/"); + } +}