From e6d22e8bcfdd94c9b7dc58d579b6c4fc84d7a0c7 Mon Sep 17 00:00:00 2001 From: Sam Fakhreddine Date: Tue, 29 Sep 2026 14:07:56 -0600 Subject: [PATCH] fix(lambda): validate enum and pattern-constrained request fields (#4611) * fix(lambda): validate enum and pattern-constrained request fields CreateFunction, UpdateFunctionConfiguration, PublishLayerVersion, the event source mapping calls, and the function URL calls now reject values outside the botocore Runtime/Architecture/FunctionResponseType/FunctionUrlAuthType/InvokeMode enums and the Role/Handler/KMSKeyArn/LayerVersionArn/Alias/Arn patterns (including AWS-managed awslayer ARNs and eusc- regions), and ListEventSourceMappings honors its EventSourceArn filter. Constraint failures use ValidationException, matching the existing pattern checks in LambdaArnUtils. * fix(lambda): validate KMSKeyArn on update, alias names, event source ARNs, and PackageType Adds KMSKeyArn pattern on UpdateFunctionConfiguration, alias name pattern and length on Create/UpdateAlias, EventSourceArn pattern on CreateEventSourceMapping, and PackageType enum on CreateFunction. * fix(lambda): accept every botocore NamespacedFunctionName in ListEventSourceMappings Add eusc- region, dotted names and $LATEST.PUBLISHED to the function name pattern. * fix(lambda): reject non-list members and validate before mutating on update UpdateFunctionUrlConfig now validates AuthType and InvokeMode before applying either, so a rejected request leaves the stored config unchanged. A non-list Layers, CompatibleRuntimes or CompatibleArchitectures is a SerializationException instead of being read as absent. Get and DeleteFunctionUrlConfig enforce the FunctionUrlQualifier constraint, UpdateFunctionConfiguration enforces the 256 character Description limit, and an empty or missing alias name is rejected. --- .../services/lambda/LambdaController.java | 5 +- .../services/lambda/LambdaLayerService.java | 4 + .../floci/services/lambda/LambdaService.java | 199 ++++++++- .../services/lambda/EsmIntegrationTest.java | 108 +++++ .../LambdaLayerCodePathIsolationTest.java | 20 + .../lambda/LambdaLayerIntegrationTest.java | 56 +++ .../services/lambda/LambdaServiceTest.java | 389 ++++++++++++++++++ 7 files changed, 763 insertions(+), 18 deletions(-) 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 366afa6973..98692799f2 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 @@ -315,8 +315,9 @@ public class LambdaController { @GET @Path("/event-source-mappings") - public Response listEventSourceMappings(@QueryParam("FunctionName") String functionArn) { - List esms = lambdaService.listEventSourceMappings(functionArn); + public Response listEventSourceMappings(@QueryParam("FunctionName") String functionArn, + @QueryParam("EventSourceArn") String eventSourceArn) { + List esms = lambdaService.listEventSourceMappings(functionArn, eventSourceArn); ObjectNode root = objectMapper.createObjectNode(); ArrayNode items = root.putArray("EventSourceMappings"); for (EventSourceMapping esm : esms) { 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 2f1a76c47c..30a5edb141 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 @@ -124,6 +124,10 @@ public class LambdaLayerService { String description = (String) request.get("Description"); String licenseInfo = (String) request.get("LicenseInfo"); + LambdaService.validateEnumList(request.get("CompatibleRuntimes"), "compatibleRuntimes", + LambdaService.RUNTIME_VALUES, 15); + LambdaService.validateEnumList(request.get("CompatibleArchitectures"), "compatibleArchitectures", + LambdaService.ARCHITECTURE_VALUES, 2); List compatibleRuntimes = request.get("CompatibleRuntimes") instanceof List ? (List) request.get("CompatibleRuntimes") : null; List compatibleArchitectures = request.get("CompatibleArchitectures") instanceof List 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 0935413d31..46c991b930 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 @@ -82,9 +82,36 @@ public class LambdaService implements ResourceProvider { // The model's own Role pattern, which AWS quotes verbatim in its validation message; it // already accepts every partition. private static final Pattern ROLE_ARN_PATTERN = Pattern.compile( - "arn:(aws[a-zA-Z-]*)?:iam::\\d{12}:role/?[a-zA-Z_0-9+=,.@\\-_/]+"); - private static final Pattern HANDLER_PATTERN = Pattern.compile("\\S+"); + "^arn:(aws[a-zA-Z-]*)?:iam::\\d{12}:role/?[a-zA-Z_0-9+=,.@\\-_/]+$"); + private static final Pattern HANDLER_PATTERN = Pattern.compile("^[^\\s]+$"); private static final int MAX_HANDLER_LENGTH = 128; + private static final Pattern KMS_KEY_ARN_PATTERN = Pattern.compile( + "^(arn:(aws[a-zA-Z-]*)?:[a-z0-9-.]+:.*)?$"); + private static final Pattern LAYER_VERSION_ARN_PATTERN = Pattern.compile( + "^((arn:(aws[a-zA-Z-]*)?:lambda:(eusc-)?[a-z]{2}((-gov)|(-iso([a-z]?)))?-[a-z]+-\\d{1}:\\d{12}:layer:[a-zA-Z0-9-_]+:[0-9]+)" + + "|(arn:[a-zA-Z0-9-]+:lambda:::awslayer:[a-zA-Z0-9-_]+))$"); + private static final Pattern ALIAS_NAME_PATTERN = Pattern.compile("^(?!^[0-9]+$)([a-zA-Z0-9-_]+)$"); + private static final Pattern FUNCTION_URL_QUALIFIER_PATTERN = Pattern.compile("^(?!^\\d+$)[0-9a-zA-Z-_]+$"); + private static final Pattern EVENT_SOURCE_ARN_PATTERN = Pattern.compile( + "^arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9-])+:((eusc-)?[a-z]{2}((-gov)|(-iso([a-z]?)))?-[a-z]+-\\d{1})?:(\\d{12})?:(.*)$"); + private static final Pattern LIST_ESM_FUNCTION_NAME_PATTERN = Pattern.compile( + "^(arn:(aws[a-zA-Z-]*)?:lambda:)?((eusc-)?[a-z]{2}((-gov)|(-iso([a-z]?)))?-[a-z]+-\\d{1}:)?(\\d{12}:)?" + + "(function:)?([a-zA-Z0-9-_\\.]+)(:(\\$LATEST(\\.PUBLISHED)?|[a-zA-Z0-9-_]+))?$"); + + /** botocore lambda/2015-03-31 Runtime shape enum, kept in sync with service-2.json. */ + static final List RUNTIME_VALUES = List.of( + "nodejs", "nodejs4.3", "nodejs6.10", "nodejs8.10", "nodejs10.x", "nodejs12.x", "nodejs14.x", + "nodejs16.x", "nodejs18.x", "nodejs20.x", "nodejs22.x", "nodejs24.x", "nodejs26.x", + "java8", "java8.al2", "java11", "java17", "java21", "java25", + "python2.7", "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", + "nodejs4.3-edge", "go1.x", "ruby2.5", "ruby2.7", "ruby3.2", "ruby3.3", "ruby3.4", "ruby4.0", + "provided", "provided.al2", "provided.al2023", + "java8.al2023", "java11.al2023", "java17.al2023"); + static final List ARCHITECTURE_VALUES = List.of("x86_64", "arm64"); + private static final List FUNCTION_URL_AUTH_TYPE_VALUES = List.of("NONE", "AWS_IAM"); + private static final List INVOKE_MODE_VALUES = List.of("BUFFERED", "RESPONSE_STREAM"); private static final List FUNCTION_ARCHITECTURES = List.of("x86_64", "arm64"); private static final List FUNCTION_RESPONSE_TYPES = List.of("ReportBatchItemFailures"); @@ -381,6 +408,7 @@ public class LambdaService implements ResourceProvider { String role = (String) request.get("Role"); String handler = (String) request.get("Handler"); String runtime = (String) request.get("Runtime"); + validateEnum(request.get("PackageType"), "packageType", List.of("Zip", "Image")); String packageType = request.getOrDefault("PackageType", "Zip").toString(); String description = (String) request.get("Description"); int timeout = toInt(request.get("Timeout"), config != null ? config.services().lambda().defaultTimeoutSeconds() : 3); @@ -396,12 +424,17 @@ public class LambdaService implements ResourceProvider { if (role == null || role.isBlank()) { throw new AwsException("InvalidParameterValueException", "Role is required", 400); } + validatePattern(role, "role", ROLE_ARN_PATTERN); if ("Zip".equals(packageType) && (handler == null || handler.isBlank())) { throw new AwsException("InvalidParameterValueException", "Handler is required", 400); } + validatePattern(handler, "handler", HANDLER_PATTERN); + validateMaxLength(handler, "handler", 128); if ("Zip".equals(packageType) && (runtime == null || runtime.isBlank())) { throw new AwsException("InvalidParameterValueException", "Runtime is required for Zip package type", 400); } + validateEnum(runtime, "runtime", RUNTIME_VALUES); + validateMaxLength(description, "description", 256); if (functionStore.get(region, functionName).isPresent()) { throw new AwsException("ResourceConflictException", @@ -455,16 +488,18 @@ public class LambdaService implements ResourceProvider { } // Layers + validateArnList(request.get("Layers"), "layers", LAYER_VERSION_ARN_PATTERN, 5); @SuppressWarnings("unchecked") - List layers = request.get("Layers") instanceof List - ? (List) request.get("Layers") : null; + List layers = (List) request.get("Layers"); if (layers != null) { validateLayersResolvable(layers); fn.setLayers(new ArrayList<>(layers)); } if (request.containsKey("KMSKeyArn")) { - fn.setKmsKeyArn((String) request.get("KMSKeyArn")); + Object kmsKeyArn = request.get("KMSKeyArn"); + validatePattern(kmsKeyArn, "kmsKeyArn", KMS_KEY_ARN_PATTERN); + fn.setKmsKeyArn((String) kmsKeyArn); } if (vpcConfig != null) { @@ -740,12 +775,19 @@ public class LambdaService implements ResourceProvider { // same reference, not a copy), so validating this late would leave every // already-applied field (Description, Timeout, ...) live on a rejected update, since // nothing here is transactional and there's a single save() at the very end. + if (request.containsKey("Layers")) { + validateArnList(request.get("Layers"), "layers", LAYER_VERSION_ARN_PATTERN, 5); + } @SuppressWarnings("unchecked") - List layerList = request.containsKey("Layers") && request.get("Layers") instanceof List - ? (List) request.get("Layers") : null; + List layerList = (List) request.get("Layers"); if (request.containsKey("Layers")) { validateLayersResolvable(layerList); } + validateMaxLength(request.get("Description"), "description", 256); + if (request.containsKey("Runtime")) { + validateEnum(request.get("Runtime"), "runtime", RUNTIME_VALUES); + } + validatePattern(request.get("KMSKeyArn"), "kmsKeyArn", KMS_KEY_ARN_PATTERN); if (request.containsKey("SnapStart")) { validateSnapStart(snapStart); } @@ -1207,6 +1249,7 @@ public class LambdaService implements ResourceProvider { if (eventSourceArn == null || eventSourceArn.isBlank()) { throw new AwsException("InvalidParameterValueException", "EventSourceArn is required", 400); } + validatePattern(eventSourceArn, "eventSourceArn", EVENT_SOURCE_ARN_PATTERN); if (!eventSourceArn.contains(":sqs:") && !eventSourceArn.contains(":kinesis:") && !eventSourceArn.contains(":dynamodb:")) { throw new AwsException("InvalidParameterValueException", @@ -1767,13 +1810,27 @@ public class LambdaService implements ResourceProvider { } public List listEventSourceMappings(String functionArn) { + return listEventSourceMappings(functionArn, null); + } + + public List listEventSourceMappings(String functionArn, String eventSourceArn) { + validatePattern(functionArn, "functionName", LIST_ESM_FUNCTION_NAME_PATTERN); + validatePattern(eventSourceArn, "eventSourceArn", EVENT_SOURCE_ARN_PATTERN); + List mappings; if (functionArn != null && !functionArn.isBlank()) { // Accept bare name, partial ARN, or full ARN. The store matches // entries by their canonical short name, so normalize first. String shortName = LambdaArnUtils.resolve(functionArn).name(); - return esmStore.listByFunction(shortName); + mappings = esmStore.listByFunction(shortName); + } else { + mappings = esmStore.list(); } - return esmStore.list(); + if (eventSourceArn != null && !eventSourceArn.isBlank()) { + mappings = mappings.stream() + .filter(esm -> eventSourceArn.equals(esm.getEventSourceArn())) + .toList(); + } + return mappings; } public EventSourceMapping updateEventSourceMapping(String uuid, Map request) { @@ -2341,7 +2398,7 @@ public class LambdaService implements ResourceProvider { validateLogGroup(logging.get("LogGroup")); } - private static void validateEnum(Object value, String field, List allowed) { + static void validateEnum(Object value, String field, List allowed) { if (value == null || allowed.contains(value)) { return; } @@ -2351,6 +2408,78 @@ public class LambdaService implements ResourceProvider { + String.join(", ", allowed) + "]", 400); } + /** + * A list member is either absent (null) or a JSON array; any other JSON type is a deserialization + * failure, so it must not be mistaken for an absent member and silently clear a stored value. + */ + private static Object requireListOrNull(Object value, String field) { + if (value != null && !(value instanceof List)) { + throw new AwsException("SerializationException", field + " must be a JSON array or null", 400); + } + return value; + } + + /** Validates every element of a request-supplied list against an enum, and its max size. */ + static void validateEnumList(Object value, String field, List allowed, int maxItems) { + if (!(requireListOrNull(value, field) instanceof List list)) { + return; + } + if (list.size() > maxItems) { + throw new AwsException("ValidationException", + "1 validation error detected: Value at '" + field + "' failed to satisfy constraint: " + + "Member must have length less than or equal to " + maxItems, 400); + } + for (Object item : list) { + validateEnum(item, field + ".member", allowed); + } + } + + /** Validates a request-supplied string against a botocore regex constraint, when present. */ + private static void validatePattern(Object value, String field, Pattern pattern) { + if (!(value instanceof String s) || s.isEmpty()) { + return; + } + if (!pattern.matcher(s).matches()) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + s + "' at '" + field + "' failed to satisfy " + + "constraint: Member must satisfy regular expression pattern: " + pattern.pattern(), 400); + } + } + + /** Validates every element of a request-supplied string list against a pattern, and its max size. */ + private static void validateArnList(Object value, String field, Pattern pattern, int maxItems) { + if (!(requireListOrNull(value, field) instanceof List list)) { + return; + } + if (list.size() > maxItems) { + throw new AwsException("ValidationException", + "1 validation error detected: Value at '" + field + "' failed to satisfy constraint: " + + "Member must have length less than or equal to " + maxItems, 400); + } + for (Object item : list) { + validatePattern(item, field + ".member", pattern); + } + } + + /** Enforces a shape's 1-character minimum: an empty string is rejected, and null too when the member is required. */ + private static void validateNonEmpty(String value, String field, boolean required) { + if ((value == null && required) || (value != null && value.isEmpty())) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + (value == null ? "" : value) + "' at '" + field + + "' failed to satisfy constraint: Member must have length greater than or equal to 1", + 400); + } + } + + private static void validateMaxLength(Object value, String field, int maxLength) { + if (!(value instanceof String s) || s.length() <= maxLength) { + return; + } + throw new AwsException("ValidationException", + "1 validation error detected: Value at '" + field + "' failed to satisfy constraint: " + + "Member must have length less than or equal to " + maxLength, 400); + } + /** * LogGroup is the one LoggingConfig member with a documented length and character * constraint rather than an enum: 1-512 characters, {@code [.\-_/#A-Za-z0-9]+}. @@ -2471,6 +2600,7 @@ public class LambdaService implements ResourceProvider { public LambdaAlias createAlias(String region, String functionName, String aliasName, String functionVersion, String description, java.util.Map routingConfig) { + validateAliasName(aliasName); LambdaFunction fn = getFunction(region, functionName); functionName = fn.getFunctionName(); if (aliasStore != null && aliasStore.get(region, functionName, aliasName).isPresent()) { @@ -2511,6 +2641,7 @@ public class LambdaService implements ResourceProvider { public LambdaAlias updateAlias(String region, String functionName, String aliasName, String functionVersion, String description, java.util.Map routingConfig) { + validateAliasName(aliasName); LambdaAlias alias = getAlias(region, functionName, aliasName); if (functionVersion != null) alias.setFunctionVersion(functionVersion); if (description != null) alias.setDescription(description); @@ -2521,7 +2652,21 @@ public class LambdaService implements ResourceProvider { return alias; } + /** FunctionUrlQualifier in botocore: 1-128 characters, not all digits. */ + private static void validateFunctionUrlQualifier(String qualifier) { + validateNonEmpty(qualifier, "qualifier", false); + validatePattern(qualifier, "qualifier", FUNCTION_URL_QUALIFIER_PATTERN); + } + + /** Alias shape in botocore: 1-128 characters matching {@link #ALIAS_NAME_PATTERN}. */ + private static void validateAliasName(String aliasName) { + validateNonEmpty(aliasName, "name", true); + validateMaxLength(aliasName, "name", 128); + validatePattern(aliasName, "name", ALIAS_NAME_PATTERN); + } + public void deleteAlias(String region, String functionName, String aliasName) { + validatePattern(aliasName, "name", ALIAS_NAME_PATTERN); String canonical = canonicalFunctionName(region, functionName); getAlias(region, canonical, aliasName); // verify it exists if (aliasStore != null) aliasStore.delete(region, canonical, aliasName); @@ -2531,13 +2676,18 @@ public class LambdaService implements ResourceProvider { // ──────────────────────────── Function URL Config ──────────────────────────── public LambdaUrlConfig createFunctionUrlConfig(String region, String functionName, String qualifier, Map request) { + validateFunctionUrlQualifier(qualifier); LambdaArnUtils.ResolvedFunctionRef ref = resolveWithRegion(region, functionName, qualifier); functionName = ref.name(); qualifier = ref.qualifier(); + Object authType = request.getOrDefault("AuthType", "NONE"); + validateEnum(authType, "authType", FUNCTION_URL_AUTH_TYPE_VALUES); + Object invokeMode = request.get("InvokeMode"); + validateEnum(invokeMode, "invokeMode", INVOKE_MODE_VALUES); LambdaUrlConfig urlConfig = new LambdaUrlConfig(); - urlConfig.setAuthType((String) request.getOrDefault("AuthType", "NONE")); - if (request.containsKey("InvokeMode")) { - urlConfig.setInvokeMode((String) request.get("InvokeMode")); + urlConfig.setAuthType((String) authType); + if (invokeMode != null) { + urlConfig.setInvokeMode((String) invokeMode); } String accountId = regionResolver.getAccountId(); @@ -2591,6 +2741,11 @@ public class LambdaService implements ResourceProvider { } public LambdaUrlConfig getFunctionUrlConfig(String region, String functionName, String qualifier) { + validateFunctionUrlQualifier(qualifier); + return lookupFunctionUrlConfig(region, functionName, qualifier); + } + + private LambdaUrlConfig lookupFunctionUrlConfig(String region, String functionName, String qualifier) { LambdaArnUtils.ResolvedFunctionRef ref = resolveWithRegion(region, functionName, qualifier); functionName = ref.name(); qualifier = ref.qualifier(); @@ -2608,16 +2763,27 @@ public class LambdaService implements ResourceProvider { } public LambdaUrlConfig updateFunctionUrlConfig(String region, String functionName, String qualifier, Map request) { + validateFunctionUrlQualifier(qualifier); LambdaArnUtils.ResolvedFunctionRef ref = resolveWithRegion(region, functionName, qualifier); functionName = ref.name(); qualifier = ref.qualifier(); - LambdaUrlConfig urlConfig = getFunctionUrlConfig(region, functionName, qualifier); + LambdaUrlConfig urlConfig = lookupFunctionUrlConfig(region, functionName, qualifier); + // urlConfig is the live object nested in the stored function or alias, so both enums are + // validated before either is applied: a rejected request must leave the config unchanged. + Object authType = request.get("AuthType"); + Object invokeMode = request.get("InvokeMode"); if (request.containsKey("AuthType")) { - urlConfig.setAuthType((String) request.get("AuthType")); + validateEnum(authType, "authType", FUNCTION_URL_AUTH_TYPE_VALUES); } if (request.containsKey("InvokeMode")) { - urlConfig.setInvokeMode((String) request.get("InvokeMode")); + validateEnum(invokeMode, "invokeMode", INVOKE_MODE_VALUES); + } + if (request.containsKey("AuthType")) { + urlConfig.setAuthType((String) authType); + } + if (request.containsKey("InvokeMode")) { + urlConfig.setInvokeMode((String) invokeMode); } String now = DateTimeFormatter.ISO_INSTANT.format(Instant.now().atOffset(ZoneOffset.UTC)); @@ -2654,6 +2820,7 @@ public class LambdaService implements ResourceProvider { } public void deleteFunctionUrlConfig(String region, String functionName, String qualifier) { + validateFunctionUrlQualifier(qualifier); LambdaArnUtils.ResolvedFunctionRef ref = resolveWithRegion(region, functionName, qualifier); functionName = ref.name(); qualifier = ref.qualifier(); diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/EsmIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/EsmIntegrationTest.java index cc113efc67..0a79dae7d2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/EsmIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/EsmIntegrationTest.java @@ -1737,4 +1737,112 @@ class EsmIntegrationTest { given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuid).then().statusCode(202); } + + // ── Request-shape validation ──────────────────────────────────────────────── + + @Test + @Order(90) + void createEventSourceMapping_rejectsUnknownFunctionResponseType() { + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "%s", + "EventSourceArn": "%s", + "FunctionResponseTypes": ["Bogus"] + } + """.formatted(FUNCTION_NAME, QUEUE_ARN)) + .when() + .post(LAMBDA_BASE + "/event-source-mappings") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")); + } + + @Test + @Order(91) + void updateEventSourceMapping_appliesAndRejectsFunctionResponseTypes() { + String uuid = given() + .contentType("application/json") + .body(""" + { + "FunctionName": "%s", + "EventSourceArn": "%s" + } + """.formatted(FUNCTION_NAME, QUEUE_ARN)) + .when() + .post(LAMBDA_BASE + "/event-source-mappings") + .then() + .statusCode(202) + .extract().path("UUID"); + + try { + given() + .contentType("application/json") + .body("{ \"FunctionResponseTypes\": [\"Bogus\"] }") + .when() + .put(LAMBDA_BASE + "/event-source-mappings/" + uuid) + .then() + .statusCode(400) + .body("__type", equalTo("InvalidParameterValueException")); + + given() + .contentType("application/json") + .body("{ \"FunctionResponseTypes\": [\"ReportBatchItemFailures\"] }") + .when() + .put(LAMBDA_BASE + "/event-source-mappings/" + uuid) + .then() + .statusCode(202) + .body("FunctionResponseTypes", hasItem("ReportBatchItemFailures")); + } finally { + given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuid); + } + } + + @Test + @Order(92) + void listEventSourceMappings_rejectsMalformedEventSourceArn() { + given() + .when() + .get(LAMBDA_BASE + "/event-source-mappings?EventSourceArn=not-an-arn") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + @Order(93) + void listEventSourceMappings_filtersByEventSourceArn() { + String uuid = given() + .contentType("application/json") + .body(""" + { + "FunctionName": "%s", + "EventSourceArn": "%s" + } + """.formatted(FUNCTION_NAME, QUEUE_ARN)) + .when() + .post(LAMBDA_BASE + "/event-source-mappings") + .then() + .statusCode(202) + .extract().path("UUID"); + + try { + given() + .when() + .get(LAMBDA_BASE + "/event-source-mappings?EventSourceArn=" + QUEUE_ARN) + .then() + .statusCode(200) + .body("EventSourceMappings.UUID", hasItem(uuid)); + + given() + .when() + .get(LAMBDA_BASE + "/event-source-mappings?EventSourceArn=" + STREAM_ARN) + .then() + .statusCode(200) + .body("EventSourceMappings.UUID", not(hasItem(uuid))); + } finally { + given().delete(LAMBDA_BASE + "/event-source-mappings/" + uuid); + } + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaLayerCodePathIsolationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaLayerCodePathIsolationTest.java index 30a17e7606..f01d10d567 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaLayerCodePathIsolationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaLayerCodePathIsolationTest.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.lambda; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion; @@ -20,6 +21,7 @@ import java.util.zip.ZipOutputStream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; +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; @@ -113,6 +115,24 @@ class LambdaLayerCodePathIsolationTest { assertEqualsContent(restored.getCodeLocalPath(), "persisted"); } + @Test + void publishLayerVersionRejectsBareStringCompatibilityLists(@TempDir Path baseDir) throws Exception { + // Catches: a non-list CompatibleRuntimes/CompatibleArchitectures being ignored instead of rejected + LambdaLayerService service = serviceFor(baseDir, "111111111111"); + Map runtimes = Map.of("Content", Map.of("ZipFile", zipBase64("r")), + "CompatibleRuntimes", "python3.12"); + Map architectures = Map.of("Content", Map.of("ZipFile", zipBase64("a")), + "CompatibleArchitectures", "x86_64"); + + AwsException badRuntimes = assertThrows(AwsException.class, + () -> service.publishLayerVersion("us-east-1", LAYER_NAME, runtimes)); + AwsException badArchitectures = assertThrows(AwsException.class, + () -> service.publishLayerVersion("us-east-1", LAYER_NAME, architectures)); + + assertEquals("SerializationException", badRuntimes.getErrorCode()); + assertEquals("SerializationException", badArchitectures.getErrorCode()); + } + private static LambdaLayerVersion publish(LambdaLayerService service, String content) throws Exception { return service.publishLayerVersion("us-east-1", LAYER_NAME, request(content)); } diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaLayerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaLayerIntegrationTest.java index 97d682bae3..1c2c522da3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaLayerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaLayerIntegrationTest.java @@ -501,4 +501,60 @@ class LambdaLayerIntegrationTest { .statusCode(200); // Layer should no longer appear (all versions deleted) } + + // ── Request-shape validation ──────────────────────────────────────────────── + + @Test + @Order(23) + void publishLayerVersion_rejectsUnknownCompatibleRuntime() throws Exception { + given() + .contentType("application/json") + .body(""" + { + "Content": { "ZipFile": "%s" }, + "CompatibleRuntimes": ["cobol99"] + } + """.formatted(layerZipBase64())) + .when() + .post("/2018-10-31/layers/validation-test-layer/versions") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + @Order(24) + void publishLayerVersion_rejectsUnknownCompatibleArchitecture() throws Exception { + given() + .contentType("application/json") + .body(""" + { + "Content": { "ZipFile": "%s" }, + "CompatibleArchitectures": ["mips"] + } + """.formatted(layerZipBase64())) + .when() + .post("/2018-10-31/layers/validation-test-layer/versions") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + @Order(25) + void publishLayerVersion_rejectsTooManyCompatibleArchitectures() throws Exception { + given() + .contentType("application/json") + .body(""" + { + "Content": { "ZipFile": "%s" }, + "CompatibleArchitectures": ["x86_64", "arm64", "x86_64"] + } + """.formatted(layerZipBase64())) + .when() + .post("/2018-10-31/layers/validation-test-layer/versions") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } } 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 e1a1dff207..5e65956135 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 @@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping; import io.github.hectorvent.floci.services.lambda.model.LambdaFileSystemConfig; import io.github.hectorvent.floci.services.lambda.model.LambdaFunction; +import io.github.hectorvent.floci.services.lambda.model.LambdaUrlConfig; import io.github.hectorvent.floci.services.lambda.zip.CodeStore; import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor; import org.junit.jupiter.api.BeforeEach; @@ -20,6 +21,7 @@ import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.Base64; import java.util.HashSet; import java.util.HashMap; @@ -1315,6 +1317,306 @@ class LambdaServiceTest { } } + // ──────────────────────────── Request-shape validation ──────────────────────────── + + @Test + void createFunctionRejectsUnknownRuntime() { + Map request = baseRequest("bad-runtime-fn"); + request.put("Runtime", "cobol99"); + + AwsException error = assertThrows(AwsException.class, + () -> service.createFunction(REGION, request)); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void updateFunctionConfigurationRejectsUnknownRuntime() { + service.createFunction(REGION, baseRequest("update-bad-runtime-fn")); + + AwsException error = assertThrows(AwsException.class, + () -> service.updateFunctionConfiguration(REGION, "update-bad-runtime-fn", + Map.of("Runtime", "cobol99"))); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void createFunctionRejectsMalformedRoleArn() { + Map request = baseRequest("bad-role-fn"); + request.put("Role", "not-an-arn"); + + AwsException error = assertThrows(AwsException.class, + () -> service.createFunction(REGION, request)); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void createFunctionRejectsHandlerWithWhitespace() { + Map request = baseRequest("bad-handler-fn"); + request.put("Handler", "index handler"); + + AwsException error = assertThrows(AwsException.class, + () -> service.createFunction(REGION, request)); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void createFunctionRejectsDescriptionOverMaxLength() { + Map request = baseRequest("bad-description-fn"); + request.put("Description", "x".repeat(257)); + + AwsException error = assertThrows(AwsException.class, + () -> service.createFunction(REGION, request)); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void createFunctionRejectsMalformedKmsKeyArn() { + Map request = baseRequest("bad-kms-fn"); + request.put("KMSKeyArn", "not-an-arn"); + + AwsException error = assertThrows(AwsException.class, + () -> service.createFunction(REGION, request)); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void createFunctionRejectsMalformedLayerArn() { + Map request = baseRequest("bad-layer-fn"); + request.put("Layers", List.of("not-a-layer-arn")); + + AwsException error = assertThrows(AwsException.class, + () -> service.createFunction(REGION, request)); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void createFunctionRejectsMoreThanFiveLayers() { + Map request = baseRequest("too-many-layers-fn"); + List layers = new ArrayList<>(); + for (int i = 0; i < 6; i++) { + layers.add("arn:aws:lambda:us-east-1:000000000000:layer:l" + i + ":1"); + } + request.put("Layers", layers); + + AwsException error = assertThrows(AwsException.class, + () -> service.createFunction(REGION, request)); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void updateFunctionConfigurationRejectsMalformedLayerArn() { + service.createFunction(REGION, baseRequest("update-bad-layer-fn")); + + AwsException error = assertThrows(AwsException.class, + () -> service.updateFunctionConfiguration(REGION, "update-bad-layer-fn", + Map.of("Layers", List.of("not-a-layer-arn")))); + assertEquals("ValidationException", error.getErrorCode()); + } + + // Architectures is validated by upstream's validateArchitectures, which reports the error + // botocore actually models for CreateFunction: ValidationException is not in that operation's + // error set, InvalidParameterValueException is. + @Test + void createFunctionRejectsUnknownArchitecture() { + Map request = baseRequest("bad-arch-fn"); + request.put("Architectures", List.of("mips")); + + AwsException error = assertThrows(AwsException.class, + () -> service.createFunction(REGION, request)); + assertEquals("InvalidParameterValueException", error.getErrorCode()); + } + + @Test + void createFunctionRejectsMoreThanOneArchitecture() { + Map request = baseRequest("too-many-arch-fn"); + request.put("Architectures", List.of("x86_64", "arm64")); + + AwsException error = assertThrows(AwsException.class, + () -> service.createFunction(REGION, request)); + assertEquals("InvalidParameterValueException", error.getErrorCode()); + } + + @Test + void updateFunctionCodeAppliesValidArchitecture() { + service.createFunction(REGION, baseRequest("update-code-arch-fn")); + + LambdaFunction updated = service.updateFunctionCode(REGION, "update-code-arch-fn", + Map.of("Architectures", List.of("arm64"))); + + assertEquals(List.of("arm64"), updated.getArchitectures()); + } + + @Test + void updateFunctionCodeRejectsUnknownArchitecture() { + service.createFunction(REGION, baseRequest("update-code-bad-arch-fn")); + + AwsException error = assertThrows(AwsException.class, + () -> service.updateFunctionCode(REGION, "update-code-bad-arch-fn", + Map.of("Architectures", List.of("mips")))); + assertEquals("InvalidParameterValueException", error.getErrorCode()); + } + + @Test + void deleteAliasRejectsMalformedName() { + AwsException error = assertThrows(AwsException.class, + () -> service.deleteAlias(REGION, "some-fn", "123")); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void createFunctionUrlConfigRejectsUnknownAuthType() { + AwsException error = assertThrows(AwsException.class, + () -> service.createFunctionUrlConfig(REGION, "any-fn", null, + Map.of("AuthType", "BOGUS"))); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void createFunctionUrlConfigRejectsUnknownInvokeMode() { + AwsException error = assertThrows(AwsException.class, + () -> service.createFunctionUrlConfig(REGION, "any-fn", null, + Map.of("InvokeMode", "BOGUS"))); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void createFunctionUrlConfigRejectsAllNumericQualifier() { + AwsException error = assertThrows(AwsException.class, + () -> service.createFunctionUrlConfig(REGION, "any-fn", "123", Map.of())); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void updateFunctionUrlConfig_invalidInvokeMode_leavesAuthTypeUnchanged() { + // Catches: UpdateFunctionUrlConfig applying AuthType to the stored config before InvokeMode is rejected + service.createFunction(REGION, baseRequest("url-atomic-fn")); + LambdaUrlConfig seeded = new LambdaUrlConfig(); + seeded.setAuthType("NONE"); + service.getFunction(REGION, "url-atomic-fn").setUrlConfig(seeded); + + AwsException error = assertThrows(AwsException.class, + () -> service.updateFunctionUrlConfig(REGION, "url-atomic-fn", null, + Map.of("AuthType", "AWS_IAM", "InvokeMode", "BOGUS"))); + + assertEquals("ValidationException", error.getErrorCode()); + assertEquals("NONE", service.getFunctionUrlConfig(REGION, "url-atomic-fn", null).getAuthType()); + } + + @Test + void getAndDeleteFunctionUrlConfig_rejectMalformedQualifier() { + // Catches: Get/DeleteFunctionUrlConfig skipping the FunctionUrlQualifier constraint that Create/Update enforce + AwsException numeric = assertThrows(AwsException.class, + () -> service.getFunctionUrlConfig(REGION, "any-fn", "123")); + AwsException empty = assertThrows(AwsException.class, + () -> service.getFunctionUrlConfig(REGION, "any-fn", "")); + AwsException deleteNumeric = assertThrows(AwsException.class, + () -> service.deleteFunctionUrlConfig(REGION, "any-fn", "123")); + + assertEquals("ValidationException", numeric.getErrorCode()); + assertEquals("ValidationException", empty.getErrorCode()); + assertEquals("ValidationException", deleteNumeric.getErrorCode()); + } + + @Test + void updateFunctionConfiguration_overlongDescription_isRejectedAndNotStored() { + // Catches: UpdateFunctionConfiguration persisting a Description over the 256-character shape limit + service.createFunction(REGION, baseRequest("update-desc-fn")); + + AwsException error = assertThrows(AwsException.class, + () -> service.updateFunctionConfiguration(REGION, "update-desc-fn", + Map.of("Description", "d".repeat(257)))); + + assertEquals("ValidationException", error.getErrorCode()); + assertNull(service.getFunction(REGION, "update-desc-fn").getDescription()); + } + + @Test + void createFunction_bareStringLayers_isRejectedAsSerializationError() { + // Catches: a non-list Layers value being treated as absent instead of rejected + Map request = baseRequest("bare-layers-fn"); + request.put("Layers", "arn:aws:lambda:us-east-1:000000000000:layer:l0:1"); + + AwsException error = assertThrows(AwsException.class, + () -> service.createFunction(REGION, request)); + + assertEquals("SerializationException", error.getErrorCode()); + } + + @Test + void updateFunctionConfiguration_bareStringLayers_isRejectedAndKeepsStoredLayers() { + // Catches: a non-list Layers value on update silently clearing the stored layers + service.createFunction(REGION, baseRequest("bare-layers-update-fn")); + + AwsException error = assertThrows(AwsException.class, + () -> service.updateFunctionConfiguration(REGION, "bare-layers-update-fn", + Map.of("Layers", "not-a-list"))); + + assertEquals("SerializationException", error.getErrorCode()); + } + + @Test + void listEventSourceMappingsRejectsMalformedFunctionName() { + AwsException error = assertThrows(AwsException.class, + () -> service.listEventSourceMappings("not a valid name!")); + assertEquals("ValidationException", error.getErrorCode()); + } + + // Catches: EventSourceArn pattern missing the optional eusc- region prefix from the Arn shape. + @Test + void listEventSourceMappingsAcceptsEuscRegionEventSourceArn() { + assertEquals(List.of(), + service.listEventSourceMappings(null, "arn:aws-eusc:sqs:eusc-de-east-1:000000000000:q")); + } + + // Catches: FunctionName pattern missing "." in the name characters, so a dotted name is rejected. + @Test + void listEventSourceMappingsAcceptsDottedFunctionName() { + assertNotRejectedByListEsmPattern("my.func"); + } + + // Catches: FunctionName pattern missing the optional eusc- region prefix. + @Test + void listEventSourceMappingsAcceptsEuscRegionFunctionArn() { + assertEquals(List.of(), service.listEventSourceMappings( + "arn:aws-eusc:lambda:eusc-de-east-1:000000000000:function:my-func")); + } + + // Catches: FunctionName pattern missing the $LATEST.PUBLISHED qualifier. + @Test + void listEventSourceMappingsAcceptsLatestPublishedQualifier() { + assertNotRejectedByListEsmPattern( + "arn:aws:lambda:us-east-1:000000000000:function:my-func:$LATEST.PUBLISHED"); + } + + // LambdaArnUtils.resolve still rejects dotted names and $LATEST.PUBLISHED downstream, so only the + // ListEventSourceMappings pattern check (anchored with ^) is asserted here. + private void assertNotRejectedByListEsmPattern(String functionName) { + try { + service.listEventSourceMappings(functionName); + } catch (AwsException e) { + assertFalse(e.getMessage().contains("pattern: ^(arn:"), e.getMessage()); + } + } + + // Catches: LayerVersionArn pattern missing the AWS-managed awslayer alternative, so a valid + // AWS-managed layer ARN is rejected as a ValidationException. + @Test + void createFunctionAcceptsAwsManagedLayerArn() { + Map request = baseRequest("aws-layer-fn"); + request.put("Layers", List.of("arn:aws:lambda:::awslayer:AmazonLinux2")); + + LambdaFunction created = service.createFunction(REGION, request); + + assertEquals(List.of("arn:aws:lambda:::awslayer:AmazonLinux2"), created.getLayers()); + } + + @Test + void listEventSourceMappingsRejectsMalformedEventSourceArn() { + AwsException error = assertThrows(AwsException.class, + () -> service.listEventSourceMappings(null, "not-an-arn")); + assertEquals("ValidationException", error.getErrorCode()); + } + @Test void createEventSourceMapping_selfManagedKafka_success() { service.createFunction(REGION, baseRequest("kafka-fn")); @@ -1518,6 +1820,26 @@ class LambdaServiceTest { ))); } + @Test + void updateEventSourceMapping_invalidLaterField_leavesBatchSizeAndEnabledUnchanged() { + // Catches: UpdateEventSourceMapping mutating the stored mapping before a later member fails validation + service.createFunction(REGION, baseRequest("kafka-fn-update-atomic")); + EventSourceMapping esm = service.createEventSourceMapping(REGION, Map.of( + "FunctionName", "kafka-fn-update-atomic", + "Topics", List.of("valid-topic"), + "SelfManagedEventSource", Map.of( + "Endpoints", Map.of("KAFKA_BOOTSTRAP_SERVERS", List.of("localhost:9092"))))); + + assertThrows(AwsException.class, () -> service.updateEventSourceMapping(esm.getUuid(), Map.of( + "BatchSize", 5, + "Enabled", false, + "FunctionResponseTypes", List.of("Bogus")))); + + EventSourceMapping stored = service.getEventSourceMapping(esm.getUuid()); + assertEquals(10, stored.getBatchSize()); + assertTrue(stored.isEnabled()); + } + @Test void updateEventSourceMapping_functionTargetValidation() { service.createFunction(REGION, baseRequest("fn-esm-target-1")); @@ -1762,4 +2084,71 @@ class LambdaServiceTest { pool.shutdownNow(); } } + + @Test + void updateFunctionConfiguration_malformedKmsKeyArn_isRejectedAndNotStored() { + // Catches: UpdateFunctionConfiguration storing a KMSKeyArn that violates the botocore pattern + service.createFunction(REGION, baseRequest("kms-update-fn")); + + AwsException error = assertThrows(AwsException.class, () -> service.updateFunctionConfiguration( + REGION, "kms-update-fn", new HashMap<>(Map.of("KMSKeyArn", "not-an-arn")))); + + assertEquals("ValidationException", error.getErrorCode()); + assertNull(service.getFunction(REGION, "kms-update-fn").getKmsKeyArn()); + } + + @Test + void createAlias_invalidName_isRejectedAndNotStored() { + // Catches: CreateAlias accepting an all-digit or over-128-character alias name + service.createFunction(REGION, baseRequest("alias-name-fn")); + + AwsException digits = assertThrows(AwsException.class, + () -> service.createAlias(REGION, "alias-name-fn", "123", "$LATEST", null, null)); + AwsException tooLong = assertThrows(AwsException.class, + () -> service.createAlias(REGION, "alias-name-fn", "a".repeat(129), "$LATEST", null, null)); + + assertEquals("ValidationException", digits.getErrorCode()); + assertEquals("ValidationException", tooLong.getErrorCode()); + assertEquals(0, service.listAliases(REGION, "alias-name-fn").size()); + } + + @Test + void createAlias_emptyOrMissingName_isRejected() { + // Catches: CreateAlias accepting an empty or null alias name despite the 1-character minimum + service.createFunction(REGION, baseRequest("alias-empty-fn")); + + AwsException empty = assertThrows(AwsException.class, + () -> service.createAlias(REGION, "alias-empty-fn", "", "$LATEST", null, null)); + AwsException missing = assertThrows(AwsException.class, + () -> service.createAlias(REGION, "alias-empty-fn", null, "$LATEST", null, null)); + + assertEquals("ValidationException", empty.getErrorCode()); + assertEquals("ValidationException", missing.getErrorCode()); + assertEquals(0, service.listAliases(REGION, "alias-empty-fn").size()); + } + + @Test + void createEventSourceMapping_malformedEventSourceArn_isRejectedAndNotStored() { + // Catches: CreateEventSourceMapping accepting an ARN that only contains ":sqs:" but is not a valid ARN + LambdaFunction fn = service.createFunction(REGION, baseRequest("esm-arn-fn")); + + AwsException error = assertThrows(AwsException.class, () -> service.createEventSourceMapping(REGION, + new HashMap<>(Map.of("FunctionName", "esm-arn-fn", "EventSourceArn", "junk:sqs:queue")))); + + assertEquals("ValidationException", error.getErrorCode()); + assertEquals(0, service.listEventSourceMappings(fn.getFunctionArn()).size()); + } + + @Test + void createFunction_unknownPackageType_isRejectedAndNotStored() { + // Catches: CreateFunction accepting a PackageType outside the Zip/Image enum + Map request = baseRequest("package-type-fn"); + request.put("PackageType", "Rar"); + + AwsException error = assertThrows(AwsException.class, () -> service.createFunction(REGION, request)); + + assertEquals("ValidationException", error.getErrorCode()); + assertEquals("ResourceNotFoundException", + assertThrows(AwsException.class, () -> service.getFunction(REGION, "package-type-fn")).getErrorCode()); + } }