diff --git a/src/main/java/io/github/hectorvent/floci/core/common/Pagination.java b/src/main/java/io/github/hectorvent/floci/core/common/Pagination.java index 16edc56049..af83141945 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/Pagination.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/Pagination.java @@ -53,7 +53,8 @@ public final class Pagination { } int limit = maxResults != null ? maxResults : defaultPageSize; return slice(all, cursorOf, limit, - decodeCursor(nextToken, "", token -> new AwsException(errorCode, "Invalid " + tokenName + ".", 400)), ""); + decodeCursor(nextToken, "", token -> new AwsException(errorCode, "Invalid " + tokenName + ".", 400)), + "", Pagination::encodeToken); } /** @@ -70,7 +71,26 @@ public final class Pagination { throw new IllegalArgumentException("limit must be at least 1, was " + limit); } String prefix = namespace + ":"; - return slice(all, cursorOf, limit, decodeCursor(nextToken, prefix, invalidToken), prefix); + return slice(all, cursorOf, limit, decodeCursor(nextToken, prefix, invalidToken), + prefix, Pagination::encodeToken); + } + + /** Paginates with instance-signed markers, optionally scoped by a prefix within the signed cursor. */ + public static PaginatedResult paginate(List all, Function cursorOf, + int limit, String marker, SignedMarkers markers, + String scope, Function invalidMarker) { + if (limit < 1) { + throw new IllegalArgumentException("limit must be at least 1, was " + limit); + } + String after = null; + if (marker != null) { + String cursor = markers.cursorOf(marker); + if (cursor == null || !cursor.startsWith(scope)) { + throw invalidMarker.apply(marker); + } + after = cursor.substring(scope.length()); + } + return slice(all, cursorOf, limit, after, scope, markers::issue); } /** Validates service-specific bounds before applying the existing namespaced cursor format. */ @@ -113,7 +133,8 @@ public final class Pagination { } private static PaginatedResult slice(List all, Function cursorOf, int limit, - String after, String tokenPrefix) { + String after, String tokenPrefix, + Function issueToken) { List sorted = all.stream().sorted(Comparator.comparing(cursorOf)).collect(Collectors.toList()); int start = 0; if (after != null) { @@ -128,7 +149,7 @@ public final class Pagination { List page = sorted.stream().skip(start).limit(limit).collect(Collectors.toList()); String token = null; if (limit < sorted.size() - start && !page.isEmpty()) { - token = encodeToken(tokenPrefix + cursorOf.apply(page.get(page.size() - 1))); + token = issueToken.apply(tokenPrefix + cursorOf.apply(page.get(page.size() - 1))); } return new PaginatedResult<>(page, token); } diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java index 4b662d4c13..8a785cfdc0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsArnUtils; 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.RegionResolver; import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping; import io.github.hectorvent.floci.services.lambda.model.InvocationType; @@ -142,15 +143,20 @@ public class LambdaController { @GET @Path("/functions") - public Response listFunctions(@Context HttpHeaders headers) { + public Response listFunctions(@Context HttpHeaders headers, + @QueryParam("MaxItems") String maxItems, + @QueryParam("Marker") String marker) { String region = regionResolver.resolveRegion(headers); - List functions = lambdaService.listFunctions(region); + PaginatedResult page = lambdaService.listFunctions(region, maxItems, marker); ObjectNode root = objectMapper.createObjectNode(); ArrayNode items = root.putArray("Functions"); - for (LambdaFunction fn : functions) { + for (LambdaFunction fn : page.items()) { items.add(objectMapper.valueToTree(buildFunctionConfiguration(fn))); } + if (page.nextToken() != null) { + root.put("NextMarker", page.nextToken()); + } return Response.ok(root).build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java index 58819e6d13..15fa668f89 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java @@ -27,7 +27,6 @@ import java.util.Base64; import java.util.Comparator; import java.util.List; import java.util.Map; -import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -52,7 +51,7 @@ public class LambdaLayerService { private static final int MAX_LAYER_VERSION_ARN_LENGTH = 140; private static final int MAX_ITEMS_LIMIT = 50; - /** Signs pagination markers; see {@link #decodeMarker}. */ + /** Signs pagination markers for both layer listing operations. */ private final SignedMarkers markers = new SignedMarkers(); private static final List COMPATIBLE_ARCHITECTURES = List.of("x86_64", "arm64"); @@ -232,7 +231,8 @@ public class LambdaLayerService { .filter(lv -> matchesFilters(lv, compatibleRuntime, compatibleArchitecture)) .toList(); // Zero-padded so the cursor's string ordering matches the numeric version ordering. - return page(versions, lv -> String.format("%019d", lv.getVersion()), limit, marker); + return LambdaPagination.paginate(versions, lv -> String.format("%019d", lv.getVersion()), + limit, MAX_ITEMS_LIMIT, marker, markers, ""); } /** @@ -253,7 +253,8 @@ public class LambdaLayerService { .orElseThrow()) .sorted(Comparator.comparing(LambdaLayerVersion::getLayerName)) .toList(); - return page(latestMatching, LambdaLayerVersion::getLayerName, limit, marker); + return LambdaPagination.paginate(latestMatching, LambdaLayerVersion::getLayerName, + limit, MAX_ITEMS_LIMIT, marker, markers, ""); } /** @@ -278,20 +279,6 @@ public class LambdaLayerService { return true; } - private PaginatedResult page(List items, Function cursorOf, - Integer maxItems, String marker) { - String after = decodeMarker(marker); - List remaining = after == null ? items - : items.stream().filter(i -> cursorOf.apply(i).compareTo(after) > 0).toList(); - List pageItems = remaining.stream() - .limit(maxItems != null ? maxItems : MAX_ITEMS_LIMIT) - .toList(); - String nextMarker = pageItems.size() < remaining.size() - ? markers.issue(cursorOf.apply(pageItems.get(pageItems.size() - 1))) - : null; - return new PaginatedResult<>(pageItems, nextMarker); - } - /** * Validates the three parseable list parameters and returns the effective MaxItems. * @@ -303,15 +290,8 @@ public class LambdaLayerService { */ private static Integer validateListParameters(String maxItems, String compatibleRuntime, String compatibleArchitecture) { - Integer parsed = parseMaxItems(maxItems); List errors = new ArrayList<>(); - if (parsed != null && parsed < 1) { - errors.add(constraintFailure(maxItems, "maxItems", - "Member must have value greater than or equal to 1")); - } else if (parsed != null && parsed > MAX_ITEMS_LIMIT) { - errors.add(constraintFailure(maxItems, "maxItems", - "Member must have value less than or equal to " + MAX_ITEMS_LIMIT)); - } + Integer parsed = LambdaPagination.parseMaxItems(maxItems, MAX_ITEMS_LIMIT, errors); if (compatibleRuntime != null && !COMPATIBLE_RUNTIMES.contains(compatibleRuntime)) { errors.add(constraintFailure(compatibleRuntime, "compatibleRuntime", "Member must satisfy enum value set: " + COMPATIBLE_RUNTIMES)); @@ -327,45 +307,11 @@ public class LambdaLayerService { return parsed; } - private static Integer parseMaxItems(String maxItems) { - if (maxItems == null || maxItems.isEmpty()) { - return null; - } - try { - return Integer.valueOf(maxItems); - } catch (NumberFormatException e) { - throw new AwsException("SerializationException", - "'" + maxItems + "' can not be converted to Integer", 400); - } - } - private static String constraintFailure(String value, String member, String requirement) { return "Value '" + value + "' at '" + member + "' failed to satisfy constraint: " + requirement; } - /** - * The live service's Marker is an encrypted token it rejects when it did not issue it. - * Floci signs the cursor instead, with a key generated at startup: a fabricated or edited - * marker fails the check, which is what makes an arbitrary string a 400 rather than a - * silently skipped or empty page. A marker from an earlier run is stale for the same - * reason, matching a client that replays an expired token against AWS. - */ - private String decodeMarker(String marker) { - if (marker == null) { - return null; - } - String cursor = markers.cursorOf(marker); - if (cursor == null) { - throw invalidPaginationKey(); - } - return cursor; - } - - private static AwsException invalidPaginationKey() { - return new AwsException("InvalidParameterValueException", "Invalid pagination key.", 400); - } - /** * Deletes a specific layer version. */ diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaPagination.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaPagination.java new file mode 100644 index 0000000000..74f42d638e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaPagination.java @@ -0,0 +1,41 @@ +package io.github.hectorvent.floci.services.lambda; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.core.common.Pagination; +import io.github.hectorvent.floci.core.common.SignedMarkers; + +import java.util.List; +import java.util.function.Function; + +final class LambdaPagination { + + private LambdaPagination() {} + + static Integer parseMaxItems(String raw, int maxAllowed, List errors) { + if (raw == null || raw.isEmpty()) { + return null; + } + int requested; + try { + requested = Integer.parseInt(raw); + } catch (NumberFormatException e) { + throw new AwsException("SerializationException", "'" + raw + "' can not be converted to Integer", 400); + } + if (requested < 1 || requested > maxAllowed) { + String bound = requested < 1 ? "greater than or equal to 1" + : "less than or equal to " + maxAllowed; + errors.add("Value '" + raw + "' at 'maxItems' failed to satisfy constraint: " + + "Member must have value " + bound); + } + return requested; + } + + static PaginatedResult paginate(List items, Function cursorOf, + Integer maxItems, int pageSize, String marker, + SignedMarkers markers, String scope) { + int limit = maxItems == null ? pageSize : Math.min(maxItems, pageSize); + return Pagination.paginate(items, cursorOf, limit, marker, markers, scope, + token -> new AwsException("InvalidParameterValueException", "Invalid pagination key.", 400)); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java index f9fb80efa7..744cd22448 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java @@ -11,8 +11,10 @@ import io.github.hectorvent.floci.core.common.AwsPartition; import io.github.hectorvent.floci.core.common.AwsPartitions; import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.CustomResourceLiveness; +import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.RequestScopes; +import io.github.hectorvent.floci.core.common.SignedMarkers; import io.github.hectorvent.floci.core.common.SmithyValidationErrors; import io.github.hectorvent.floci.core.resource.ExplorerResource; import io.github.hectorvent.floci.core.resource.ResourceProvider; @@ -99,6 +101,8 @@ public class LambdaService implements ResourceProvider { private static final int MAX_TOPIC_LENGTH = 249; private static final int MAX_TOPICS = 1; private static final int MAX_SOURCE_ACCESS_CONFIGURATIONS = 23; + private static final int LIST_FUNCTIONS_PAGE_SIZE = 50; + private static final int MAX_LIST_FUNCTIONS_ITEMS = 10_000; // UpdateFunctionCode S3Bucket (3-63 characters, [0-9A-Za-z\.\-_]*(? eventInvokeConfigs = new ConcurrentHashMap<>(); private final ConcurrentHashMap policyMutationLocks = new ConcurrentHashMap<>(); private final ConcurrentHashMap versionCounterLocks = new ConcurrentHashMap<>(); + private final SignedMarkers listFunctionMarkers = new SignedMarkers(); /** * Package-private constructor for testing without CDI. Config defaults @@ -731,6 +736,17 @@ public class LambdaService implements ResourceProvider { return functionStore.list(region); } + public PaginatedResult listFunctions(String region, String maxItems, String marker) { + List errors = new ArrayList<>(); + Integer requested = LambdaPagination.parseMaxItems(maxItems, MAX_LIST_FUNCTIONS_ITEMS, errors); + if (!errors.isEmpty()) { + throw SmithyValidationErrors.validationException(errors); + } + String scope = regionResolver.getAccountId() + "\n" + region + "\n"; + return LambdaPagination.paginate(listFunctions(region), LambdaFunction::getFunctionName, + requested, LIST_FUNCTIONS_PAGE_SIZE, marker, listFunctionMarkers, scope); + } + public LambdaFunction updateFunctionCode(String region, String functionName, Map request) { LambdaFunction fn = getFunction(region, functionName); // publishVersion copies roughly thirty fields off this same live object. Without the diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PaginationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PaginationTest.java index 19354d5c6e..86a8344ef3 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/PaginationTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/PaginationTest.java @@ -67,6 +67,34 @@ class PaginationTest { assertThrows(IllegalArgumentException.class, () -> page(0, null, "ns")); } + @Test + void signedPaging_resumesWithAnIssuedMarkerAndRejectsForeignOrChangedMarkers() { + SignedMarkers markers = new SignedMarkers(); + PaginatedResult first = signedPage(markers, 1, null, "account:region:"); + assertThat(first.items(), contains("a")); + assertEquals("account:region:a", markers.cursorOf(first.nextToken())); + + PaginatedResult second = signedPage(markers, 2, first.nextToken(), "account:region:"); + assertThat(second.items(), contains("b", "c")); + assertNull(second.nextToken()); + + assertSame(INVALID, assertThrows(AwsException.class, + () -> signedPage(markers, 1, first.nextToken(), "other:region:"))); + assertSame(INVALID, assertThrows(AwsException.class, + () -> signedPage(new SignedMarkers(), 1, first.nextToken(), "account:region:"))); + assertSame(INVALID, assertThrows(AwsException.class, + () -> signedPage(markers, 1, first.nextToken() + "x", "account:region:"))); + } + + @Test + void signedPaging_rejectsAnEmptyOrMalformedMarker() { + SignedMarkers markers = new SignedMarkers(); + assertSame(INVALID, assertThrows(AwsException.class, + () -> signedPage(markers, 1, "", ""))); + assertSame(INVALID, assertThrows(AwsException.class, + () -> signedPage(markers, 1, "!!!", ""))); + } + @Test void paging_aLimitNearIntMaxDoesNotReportAFurtherPage() { String afterFirst = page(1, null, "ns").nextToken(); @@ -196,6 +224,11 @@ class PaginationTest { return Pagination.paginate(ITEMS, Function.identity(), limit, token, namespace, INVALID_TOKEN); } + private static PaginatedResult signedPage(SignedMarkers markers, int limit, + String marker, String scope) { + return Pagination.paginate(ITEMS, Function.identity(), limit, marker, markers, scope, INVALID_TOKEN); + } + private static String decode(String token) { return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8); } diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaListFunctionsPaginationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaListFunctionsPaginationIntegrationTest.java new file mode 100644 index 0000000000..00752f2e1a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaListFunctionsPaginationIntegrationTest.java @@ -0,0 +1,109 @@ +package io.github.hectorvent.floci.services.lambda; + +import io.github.hectorvent.floci.core.common.RequestScopes; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; + +@QuarkusTest +class LambdaListFunctionsPaginationIntegrationTest { + + private static final String ACCOUNT = "000000006652"; + private static final String DEFAULT_ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + private static final String AUTHORIZATION = + "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20260101/us-east-1/lambda/aws4_request"; + + @Inject LambdaService service; + + @Test + void listFunctionsHonorsMaxItemsAndMarker() { + List names = new ArrayList<>(); + String suffix = UUID.randomUUID().toString(); + String unrelatedName = "000-page-" + suffix; + boolean unrelatedCreated = false; + try { + RequestScopes.runAs(DEFAULT_ACCOUNT, REGION, () -> service.createFunction(REGION, Map.of( + "FunctionName", unrelatedName, + "Runtime", "nodejs20.x", + "Role", "arn:aws:iam::000000000000:role/lambda-role", + "Handler", "index.handler"))); + unrelatedCreated = true; + for (String letter : List.of("b", "a", "c")) { + String name = "issue-page-" + suffix + "-" + letter; + lambdaRequest().contentType("application/json") + .body(""" + {"FunctionName":"%s","Runtime":"nodejs20.x", + "Role":"arn:aws:iam::%s:role/lambda-role", + "Handler":"index.handler"} + """.formatted(name, ACCOUNT)) + .post("/2015-03-31/functions").then().statusCode(201); + names.add(name); + } + String firstMarker = lambdaRequest().queryParam("MaxItems", 1) + .get("/2015-03-31/functions").then().statusCode(200) + .body("Functions.FunctionName", contains(names.get(1))) + .body("NextMarker", notNullValue()) + .extract().path("NextMarker"); + String secondMarker = lambdaRequest().queryParam("MaxItems", 1).queryParam("Marker", firstMarker) + .get("/2015-03-31/functions").then().statusCode(200) + .body("Functions.FunctionName", contains(names.get(0))) + .body("NextMarker", notNullValue()) + .extract().path("NextMarker"); + lambdaRequest().queryParam("MaxItems", 1).queryParam("Marker", secondMarker) + .get("/2015-03-31/functions").then().statusCode(200) + .body("Functions.FunctionName", contains(names.get(2))) + .body("$", not(hasKey("NextMarker"))); + } finally { + for (String name : names) { + RequestScopes.runAs(ACCOUNT, REGION, () -> service.deleteFunction(REGION, name)); + } + if (unrelatedCreated) { + RequestScopes.runAs(DEFAULT_ACCOUNT, REGION, + () -> service.deleteFunction(REGION, unrelatedName)); + } + } + } + + @Test + void listFunctionsRejectsAnUnknownMarker() { + lambdaRequest().queryParam("Marker", "not-an-issued-marker") + .get("/2015-03-31/functions").then().statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")) + .body("message", equalTo("Invalid pagination key.")); + } + + @Test + void listFunctionsRejectsOutOfRangeMaxItems() { + for (int maxItems : List.of(0, 10001)) { + lambdaRequest().queryParam("MaxItems", maxItems) + .get("/2015-03-31/functions").then().statusCode(400) + .body("__type", equalTo("ValidationException")); + } + } + + @Test + void listFunctionsReportsSerializationFailureBeforeMarkerValidation() { + lambdaRequest().queryParam("MaxItems", "abc").queryParam("Marker", "not-an-issued-marker") + .get("/2015-03-31/functions").then().statusCode(400) + .body("__type", equalTo("SerializationException")) + .body("message", equalTo("'abc' can not be converted to Integer")); + } + + private static RequestSpecification lambdaRequest() { + return given().header("Authorization", AUTHORIZATION); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java index a82bfaeebf..09d0b54a94 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.lambda; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.InMemoryStorage; @@ -514,6 +515,29 @@ class LambdaServiceTest { assertTrue(functions.stream().anyMatch(f -> f.getFunctionName().equals("fn-2"))); } + @Test + void listFunctionsCapsPagesAtFiftyAndScopesMarkersToRegion() { + for (int i = 51; i >= 0; i--) { + service.createFunction(REGION, baseRequest("page-fn-%03d".formatted(i))); + } + service.createFunction("eu-west-1", baseRequest("other-region-fn")); + + PaginatedResult first = service.listFunctions(REGION, "10000", null); + assertEquals(50, first.items().size()); + assertEquals("page-fn-000", first.items().getFirst().getFunctionName()); + assertEquals("page-fn-049", first.items().getLast().getFunctionName()); + assertNotNull(first.nextToken()); + + PaginatedResult second = service.listFunctions(REGION, "10000", first.nextToken()); + assertEquals(List.of("page-fn-050", "page-fn-051"), + second.items().stream().map(LambdaFunction::getFunctionName).toList()); + assertNull(second.nextToken()); + + AwsException invalid = assertThrows(AwsException.class, + () -> service.listFunctions("eu-west-1", "1", first.nextToken())); + assertEquals("InvalidParameterValueException", invalid.getErrorCode()); + } + @Test void deleteFunctionRemovesIt() { service.createFunction(REGION, baseRequest("del-fn"));