mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix(lambda): honour ListLayers and ListLayerVersions query parameters (#2817)
* fix(lambda): honour ListLayers and ListLayerVersions query parameters CompatibleRuntime, CompatibleArchitecture, MaxItems and Marker were accepted and ignored, and NextMarker was never emitted, so a client paginating with MaxItems saw a single page and silently got the whole list, while a runtime or architecture filter returned layers that do not match it. Both actions now filter, paginate and emit NextMarker. Validation follows the live service rather than the API reference: range and enum failures accumulate into one ValidationException in a fixed member order, a non-integer MaxItems is a SerializationException that short-circuits validation, and a Marker the service did not issue is InvalidParameterValueException "Invalid pagination key.". Under a filter, LatestMatchingVersion is the newest version that matches rather than the newest overall, so ListLayers needs every version of each layer rather than the latest of each. Closes #2808 * fix(lambda): sign layer pagination markers The tag identifying a Marker as Floci's was a fixed string, so a caller could base64 a cursor of their own with the same prefix and have it accepted. That cursor was then applied to the page, silently skipping results or emptying the list where AWS rejects an unissued token. Markers now carry an HMAC over the cursor, keyed per process, so a fabricated or edited token fails the check. A marker from an earlier run is stale for the same reason, which is what AWS does with an expired one. * test(lambda): cover layer listing parameters through the AWS SDK AGENTS.md prefers SDK clients over raw HTTP for management-plane validation. The integration test covers the parameters through the wire protocol; this adds the same filtering, pagination and enum rejection through @aws-sdk/client-lambda, so a marshalling regression that only the SDK would notice does not pass unseen.
This commit is contained in:
1 parent
afe26c6ad1
commit
44629631ca
6 files changed
+882
-12
No files matched your search
+26
-5
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -21,7 +22,6 @@ import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
@@ -68,14 +68,20 @@ public class LambdaLayerController {
|
||||
@GET
|
||||
@Path("/layers/{layerName}/versions")
|
||||
public Response listLayerVersions(@PathParam("layerName") String layerName,
|
||||
@QueryParam("CompatibleRuntime") String compatibleRuntime,
|
||||
@QueryParam("CompatibleArchitecture") String compatibleArchitecture,
|
||||
@QueryParam("MaxItems") String maxItems,
|
||||
@QueryParam("Marker") String marker,
|
||||
@Context HttpHeaders headers) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<LambdaLayerVersion> versions = layerService.listLayerVersions(region, layerName);
|
||||
PaginatedResult<LambdaLayerVersion> result = layerService.listLayerVersions(
|
||||
region, layerName, compatibleRuntime, compatibleArchitecture, maxItems, marker);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode arr = root.putArray("LayerVersions");
|
||||
for (LambdaLayerVersion lv : versions) {
|
||||
for (LambdaLayerVersion lv : result.items()) {
|
||||
arr.add(buildLayerVersionSummary(lv));
|
||||
}
|
||||
putNextMarker(root, result.nextToken());
|
||||
return Response.ok(root).build();
|
||||
}
|
||||
|
||||
@@ -109,6 +115,10 @@ public class LambdaLayerController {
|
||||
@Path("/layers")
|
||||
public Response listLayers(@QueryParam("find") String find,
|
||||
@QueryParam("Arn") String arn,
|
||||
@QueryParam("CompatibleRuntime") String compatibleRuntime,
|
||||
@QueryParam("CompatibleArchitecture") String compatibleArchitecture,
|
||||
@QueryParam("MaxItems") String maxItems,
|
||||
@QueryParam("Marker") String marker,
|
||||
@Context HttpHeaders headers,
|
||||
@Context UriInfo uriInfo) {
|
||||
if (FIND_LAYER_VERSION.equals(find)) {
|
||||
@@ -118,10 +128,11 @@ public class LambdaLayerController {
|
||||
return Response.ok(buildLayerVersionResponse(lv, layerRegion, uriInfo)).build();
|
||||
}
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<LambdaLayerVersion> layers = layerService.listLayers(region);
|
||||
PaginatedResult<LambdaLayerVersion> result = layerService.listLayers(
|
||||
region, compatibleRuntime, compatibleArchitecture, maxItems, marker);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode arr = root.putArray("Layers");
|
||||
for (LambdaLayerVersion lv : layers) {
|
||||
for (LambdaLayerVersion lv : result.items()) {
|
||||
ObjectNode layerNode = objectMapper.createObjectNode();
|
||||
layerNode.put("LayerName", lv.getLayerName());
|
||||
layerNode.put("LayerArn", lv.getLayerArn());
|
||||
@@ -141,9 +152,19 @@ public class LambdaLayerController {
|
||||
}
|
||||
arr.add(layerNode);
|
||||
}
|
||||
putNextMarker(root, result.nextToken());
|
||||
return Response.ok(root).build();
|
||||
}
|
||||
|
||||
/** AWS always emits NextMarker, null on the last page rather than omitting the field. */
|
||||
private static void putNextMarker(ObjectNode root, String nextMarker) {
|
||||
if (nextMarker == null) {
|
||||
root.putNull("NextMarker");
|
||||
} else {
|
||||
root.put("NextMarker", nextMarker);
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectNode buildLayerVersionResponse(LambdaLayerVersion lv, String region, UriInfo uriInfo) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("LayerArn", lv.getLayerArn());
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.lambda;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
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.services.lambda.model.LambdaLayerVersion;
|
||||
import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;
|
||||
@@ -10,13 +11,18 @@ import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
@@ -25,7 +31,9 @@ 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;
|
||||
|
||||
/**
|
||||
* Business logic for Lambda Layer management.
|
||||
@@ -46,6 +54,39 @@ public class LambdaLayerService {
|
||||
+ "|(arn:[a-zA-Z0-9-]+:lambda:::awslayer:[a-zA-Z0-9-_]+))";
|
||||
private static final Pattern LAYER_VERSION_ARN = Pattern.compile(LAYER_VERSION_ARN_PATTERN);
|
||||
private static final int MAX_LAYER_VERSION_ARN_LENGTH = 140;
|
||||
private static final int MAX_ITEMS_LIMIT = 50;
|
||||
|
||||
private static final char MARKER_SEPARATOR = '.';
|
||||
|
||||
/** Signing key for pagination markers, per process; see {@link #encodeMarker}. */
|
||||
private static final byte[] MARKER_KEY = newMarkerKey();
|
||||
|
||||
private static final List<String> COMPATIBLE_ARCHITECTURES = List.of("x86_64", "arm64");
|
||||
|
||||
/**
|
||||
* Runtime identifiers accepted for CompatibleRuntime, taken from the live service's own
|
||||
* ValidationException rather than the API reference: it accepts values the reference omits
|
||||
* (java8.al2023, java17.al2023, python3.15, nodejs26.x, the greengrass runtime ARNs) and
|
||||
* rejects everything else, case-sensitively. Rendered into the error message as-is, so the
|
||||
* order is fixed here; the live service's own ordering varies between responses.
|
||||
*/
|
||||
private static final List<String> COMPATIBLE_RUNTIMES = List.of(
|
||||
"nodejs", "nodejs4.3", "nodejs4.3-edge", "nodejs6.10", "nodejs8.9", "nodejs8.10",
|
||||
"nodejs8.x", "nodejs10.x", "nodejs12.x", "nodejs14.x", "nodejs16.x", "nodejs18.x",
|
||||
"nodejs20.x", "nodejs22.x", "nodejs24.x", "nodejs26.x",
|
||||
"java8", "java8.al2", "java8.al2023", "java11", "java11.al2023", "java17",
|
||||
"java17.al2023", "java21", "java25",
|
||||
"python2.7", "python2.7-greengrass", "python3.4", "python3.6", "python3.7",
|
||||
"python3.8", "python3.9", "python3.10", "python3.11", "python3.12", "python3.13",
|
||||
"python3.14", "python3.15",
|
||||
"dotnetcore1.0", "dotnetcore2.0", "dotnetcore2.1", "dotnetcore3.1", "dotnet6",
|
||||
"dotnet8", "dotnet10",
|
||||
"ruby2.5", "ruby2.6", "ruby2.7", "ruby3.2", "ruby3.3", "ruby3.4", "ruby4.0",
|
||||
"go1.x", "go1.9", "provided", "provided.al2", "provided.al2023",
|
||||
"byol", "custom", "nasa",
|
||||
"arn:aws:greengrass:::runtime/function/executable",
|
||||
"arn:aws-cn:greengrass:::runtime/function/executable",
|
||||
"arn:aws-us-gov:greengrass:::runtime/function/executable");
|
||||
|
||||
private final LambdaLayerStore layerStore;
|
||||
private final ZipExtractor zipExtractor;
|
||||
@@ -162,17 +203,187 @@ public class LambdaLayerService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists all versions of a layer.
|
||||
* Lists the versions of a layer, honouring the documented CompatibleRuntime,
|
||||
* CompatibleArchitecture, MaxItems and Marker parameters. An unknown layer name is an
|
||||
* empty page, not a 404 — the live service answers 200 for a layer that never existed.
|
||||
*/
|
||||
public List<LambdaLayerVersion> listLayerVersions(String region, String layerName) {
|
||||
return layerStore.listVersions(region, layerName);
|
||||
public PaginatedResult<LambdaLayerVersion> listLayerVersions(String region, String layerName,
|
||||
String compatibleRuntime,
|
||||
String compatibleArchitecture,
|
||||
String maxItems, String marker) {
|
||||
Integer limit = validateListParameters(maxItems, compatibleRuntime, compatibleArchitecture);
|
||||
List<LambdaLayerVersion> versions = layerStore.listVersions(region, layerName).stream()
|
||||
.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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists all layers in a region (returns the latest version of each).
|
||||
* Lists the layers in a region, honouring the same four parameters. Under a filter,
|
||||
* LatestMatchingVersion is the newest version that matches rather than the newest overall,
|
||||
* and a layer with no matching version drops out of the list entirely.
|
||||
*/
|
||||
public List<LambdaLayerVersion> listLayers(String region) {
|
||||
return layerStore.listLayers(region);
|
||||
public PaginatedResult<LambdaLayerVersion> listLayers(String region, String compatibleRuntime,
|
||||
String compatibleArchitecture,
|
||||
String maxItems, String marker) {
|
||||
Integer limit = validateListParameters(maxItems, compatibleRuntime, compatibleArchitecture);
|
||||
List<LambdaLayerVersion> latestMatching = layerStore.listAllVersions(region).stream()
|
||||
.filter(lv -> matchesFilters(lv, compatibleRuntime, compatibleArchitecture))
|
||||
.collect(Collectors.groupingBy(LambdaLayerVersion::getLayerName))
|
||||
.values().stream()
|
||||
.map(versions -> versions.stream()
|
||||
.max(Comparator.comparingLong(LambdaLayerVersion::getVersion))
|
||||
.orElseThrow())
|
||||
.sorted(Comparator.comparing(LambdaLayerVersion::getLayerName))
|
||||
.toList();
|
||||
return page(latestMatching, LambdaLayerVersion::getLayerName, limit, marker);
|
||||
}
|
||||
|
||||
/**
|
||||
* A layer version matches a filter only by listing the value explicitly: one published
|
||||
* without CompatibleArchitectures is absent from both x86_64 and arm64 results rather than
|
||||
* defaulting to x86_64 the way a function's Architectures does.
|
||||
*/
|
||||
private static boolean matchesFilters(LambdaLayerVersion lv, String compatibleRuntime,
|
||||
String compatibleArchitecture) {
|
||||
if (compatibleRuntime != null) {
|
||||
List<String> runtimes = lv.getCompatibleRuntimes();
|
||||
if (runtimes == null || !runtimes.contains(compatibleRuntime)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (compatibleArchitecture != null) {
|
||||
List<String> architectures = lv.getCompatibleArchitectures();
|
||||
if (architectures == null || !architectures.contains(compatibleArchitecture)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static <T> PaginatedResult<T> page(List<T> items, Function<T, String> cursorOf,
|
||||
Integer maxItems, String marker) {
|
||||
String after = decodeMarker(marker);
|
||||
List<T> remaining = after == null ? items
|
||||
: items.stream().filter(i -> cursorOf.apply(i).compareTo(after) > 0).toList();
|
||||
List<T> pageItems = remaining.stream()
|
||||
.limit(maxItems != null ? maxItems : MAX_ITEMS_LIMIT)
|
||||
.toList();
|
||||
String nextMarker = pageItems.size() < remaining.size()
|
||||
? encodeMarker(cursorOf.apply(pageItems.get(pageItems.size() - 1)))
|
||||
: null;
|
||||
return new PaginatedResult<>(pageItems, nextMarker);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the three parseable list parameters and returns the effective MaxItems.
|
||||
*
|
||||
* <p>Mirrors the live service's ordering, measured rather than documented: a MaxItems that
|
||||
* is not an integer is a SerializationException that short-circuits everything else, while
|
||||
* range and enum failures accumulate into one ValidationException in a fixed member order
|
||||
* (maxItems, compatibleRuntime, compatibleArchitecture) regardless of query-string order.
|
||||
* An empty MaxItems is treated as omitted; a blank one is not.
|
||||
*/
|
||||
private static Integer validateListParameters(String maxItems, String compatibleRuntime,
|
||||
String compatibleArchitecture) {
|
||||
Integer parsed = parseMaxItems(maxItems);
|
||||
List<String> 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));
|
||||
}
|
||||
if (compatibleRuntime != null && !COMPATIBLE_RUNTIMES.contains(compatibleRuntime)) {
|
||||
errors.add(constraintFailure(compatibleRuntime, "compatibleRuntime",
|
||||
"Member must satisfy enum value set: " + COMPATIBLE_RUNTIMES));
|
||||
}
|
||||
if (compatibleArchitecture != null
|
||||
&& !COMPATIBLE_ARCHITECTURES.contains(compatibleArchitecture)) {
|
||||
errors.add(constraintFailure(compatibleArchitecture, "compatibleArchitecture",
|
||||
"Member must satisfy enum value set: " + COMPATIBLE_ARCHITECTURES));
|
||||
}
|
||||
if (!errors.isEmpty()) {
|
||||
throw new AwsException("ValidationException",
|
||||
errors.size() + (errors.size() == 1 ? " validation error" : " validation errors")
|
||||
+ " detected: " + String.join("; ", errors), 400);
|
||||
}
|
||||
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 static String encodeMarker(String cursor) {
|
||||
String signed = cursor + MARKER_SEPARATOR + sign(cursor);
|
||||
return Base64.getUrlEncoder().withoutPadding()
|
||||
.encodeToString(signed.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String decodeMarker(String marker) {
|
||||
if (marker == null) {
|
||||
return null;
|
||||
}
|
||||
String decoded;
|
||||
try {
|
||||
decoded = new String(Base64.getUrlDecoder().decode(marker), StandardCharsets.UTF_8);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw invalidPaginationKey();
|
||||
}
|
||||
int separator = decoded.lastIndexOf(MARKER_SEPARATOR);
|
||||
if (separator < 0) {
|
||||
throw invalidPaginationKey();
|
||||
}
|
||||
String cursor = decoded.substring(0, separator);
|
||||
byte[] presented = decoded.substring(separator + 1).getBytes(StandardCharsets.UTF_8);
|
||||
if (!MessageDigest.isEqual(presented, sign(cursor).getBytes(StandardCharsets.UTF_8))) {
|
||||
throw invalidPaginationKey();
|
||||
}
|
||||
return cursor;
|
||||
}
|
||||
|
||||
private static String sign(String cursor) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(MARKER_KEY, "HmacSHA256"));
|
||||
return Base64.getUrlEncoder().withoutPadding()
|
||||
.encodeToString(mac.doFinal(cursor.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("HmacSHA256 is required to paginate layers", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] newMarkerKey() {
|
||||
byte[] key = new byte[32];
|
||||
new SecureRandom().nextBytes(key);
|
||||
return key;
|
||||
}
|
||||
|
||||
private static AwsException invalidPaginationKey() {
|
||||
return new AwsException("InvalidParameterValueException", "Invalid pagination key.", 400);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -58,6 +58,20 @@ public class LambdaLayerStore {
|
||||
.orElse(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns every version of every layer in a region, ordered by layer name then version
|
||||
* ascending. ListLayers needs all versions, not just the latest of each: under a
|
||||
* CompatibleRuntime or CompatibleArchitecture filter, LatestMatchingVersion is the newest
|
||||
* version that matches, which may not be the newest version overall.
|
||||
*/
|
||||
public List<LambdaLayerVersion> listAllVersions(String region) {
|
||||
String prefix = "layer::" + region + "::";
|
||||
return backend.scan(k -> k.startsWith(prefix)).stream()
|
||||
.sorted(java.util.Comparator.comparing(LambdaLayerVersion::getLayerName)
|
||||
.thenComparingLong(LambdaLayerVersion::getVersion))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all distinct layers in a region (latest version of each).
|
||||
*/
|
||||
|
||||
Reference in new issue
Block a user