Light, fluffy, and always free - The AWS Local Emulator alternative
fix(lambda): validate Layers ARNs eagerly on CreateFunction/UpdateFunctionConfiguration (#2282)
sheldon-nadarajah-sft2f0ef459782e
diff --git a/docs/services/lambda.md b/docs/services/lambda.mdindex a804c8dda1..06b1dc9ade 100644--- a/docs/services/lambda.md+++ b/docs/services/lambda.md@@ -164,13 +164,21 @@ services:Function URLs are also reachable directly on `/{proxy:.*}` under the Lambda URL controller, which routes the request into the normal `Invoke` path.-**Stubbed:** `ListLayers` and `ListLayerVersions` return empty arrays. No layer storage exists.+**Layers:** `PublishLayerVersion`, `GetLayerVersion`, `ListLayerVersions`, `ListLayers`, and+`DeleteLayerVersion` are implemented, with real local storage under+`{lambda.codePath}/layers/{name}/{version}`. `CreateFunction`/`UpdateFunctionConfiguration`+validate each `Layers` ARN eagerly against that storage, matching real AWS - an unresolvable ARN+is rejected with `InvalidParameterValueException`, not silently accepted. Only resolves layers+published into this same local Floci instance; a real AWS-owned layer ARN (e.g. the AWS AppConfig+Extension or a Datadog-published layer) can never resolve here, since there's no mechanism in+Floci for fetching real AWS content - publish your own copy of the layer's content locally under+a name you control and reference that ARN instead.## Not ImplementedThese AWS Lambda operations have no handler in Floci. Calls will return `404` or an error:-- Layers (`PublishLayerVersion`, `DeleteLayerVersion`, `GetLayerVersion`, `GetLayerVersionByArn`, `AddLayerVersionPermission`, `RemoveLayerVersionPermission`, `GetLayerVersionPolicy`)+- Layer permissions and cross-account ARN lookup (`GetLayerVersionByArn`, `AddLayerVersionPermission`, `RemoveLayerVersionPermission`, `GetLayerVersionPolicy`)- Provisioned concurrency (`PutProvisionedConcurrencyConfig`, `GetProvisionedConcurrencyConfig`, `ListProvisionedConcurrencyConfigs`, `DeleteProvisionedConcurrencyConfig`)- Dead-letter, async invoke config, and event invoke config operations- `InvokeWithResponseStream`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.javaindex 627bcee3d4..0c857404e9 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@@ -72,6 +72,7 @@ public class LambdaService {private final KinesisEventSourcePoller kinesisPoller;private final DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller;private final StorageFactory storageFactory;+ private final LambdaLayerService layerService;private Map<String, Integer> versionCounters = new ConcurrentHashMap<>();private Map<String, FunctionEventInvokeConfig> eventInvokeConfigs = new ConcurrentHashMap<>();/**@@ -139,6 +140,7 @@ public class LambdaService {this.kinesisPoller = null;this.dynamodbStreamsPoller = null;this.storageFactory = storageFactory;+ this.layerService = null;}@Inject@@ -157,7 +159,8 @@ public class LambdaService {SqsEventSourcePoller poller,KinesisEventSourcePoller kinesisPoller,DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller,- StorageFactory storageFactory) {+ StorageFactory storageFactory,+ LambdaLayerService layerService) {this.functionStore = functionStore;this.executorService = executorService;this.concurrencyLimiter = concurrencyLimiter;@@ -174,6 +177,23 @@ public class LambdaService {this.kinesisPoller = kinesisPoller;this.dynamodbStreamsPoller = dynamodbStreamsPoller;this.storageFactory = storageFactory;+ this.layerService = layerService;+ }++ // Real AWS validates a function's Layers eagerly at CreateFunction/UpdateFunctionConfiguration+ // time with InvalidParameterValueException, not lazily at invoke time - resolveLayerByArn's+ // caller in ContainerLauncher only logs a warning and silently launches without the layer's+ // content mounted, which is correct AWS-parity behavior for a layer deleted *after* being+ // attached (AWS doesn't re-validate on every invoke either), but was previously the only+ // signal at all for a bad ARN, even a typo caught at attach time on real AWS.+ private void validateLayersResolvable(List<String> layerArns) {+ if (layerArns == null || layerService == null) return;+ for (String arn : layerArns) {+ if (layerService.resolveLayerByArn(arn) == null) {+ throw new AwsException("InvalidParameterValueException",+ "Layer version " + arn + " does not exist.", 400);+ }+ }}/** Package-private accessor for tests that want to assert limiter state directly. */@@ -321,6 +341,7 @@ public class LambdaService {List<String> layers = request.get("Layers") instanceof List? (List<String>) request.get("Layers") : null;if (layers != null) {+ validateLayersResolvable(layers);fn.setLayers(new ArrayList<>(layers));}@@ -463,6 +484,18 @@ public class LambdaService {public LambdaFunction updateFunctionConfiguration(String region, String functionName, Map<String, Object> request) {LambdaFunction fn = getFunction(region, functionName);+ // Validated before any field mutation below, not inline where Layers is applied further+ // down - fn is the live object backing this store entry (InMemoryStorage#get returns the+ // 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.+ @SuppressWarnings("unchecked")+ List<String> layerList = request.containsKey("Layers") && request.get("Layers") instanceof List+ ? (List<String>) request.get("Layers") : null;+ if (request.containsKey("Layers")) {+ validateLayersResolvable(layerList);+ }+Map<String, Object> requestedVpcConfig = fn.getVpcConfig();if (request.get("VpcConfig") instanceof Map<?, ?>) {@SuppressWarnings("unchecked")@@ -545,9 +578,6 @@ public class LambdaService {}if (request.containsKey("Layers")) {- @SuppressWarnings("unchecked")- List<String> layerList = request.get("Layers") instanceof List- ? (List<String>) request.get("Layers") : null;fn.setLayers(layerList != null ? new ArrayList<>(layerList) : new ArrayList<>());}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.javaindex 7c74dc9777..7f4397b0d8 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@@ -311,6 +311,98 @@ class LambdaLayerIntegrationTest {.statusCode(400);}+ // ── Attach-time layer validation on CreateFunction/UpdateFunctionConfiguration ────────────+ // Real AWS rejects an unresolvable Layers ARN eagerly, at attach time, with+ // InvalidParameterValueException - previously Floci accepted any ARN unconditionally and the+ // failure only ever surfaced as a silent warning log when the container tried to launch.++ @Test+ @Order(17)+ void createFunction_withNonExistentLayer_returns400() throws Exception {+ given()+ .contentType("application/json")+ .body("""+ {+ "FunctionName": "layer-validation-create-fn",+ "Runtime": "nodejs20.x",+ "Role": "arn:aws:iam::000000000000:role/lambda-role",+ "Handler": "index.handler",+ "Code": { "ZipFile": "%s" },+ "Layers": ["arn:aws:lambda:us-east-1:000000000000:layer:no-such-layer:1"]+ }+ """.formatted(functionZipBase64()))+ .when()+ .post("/2015-03-31/functions")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterValueException"));++ // The function must not have been created at all - not partially, not with the layer+ // dropped.+ given()+ .when()+ .get("/2015-03-31/functions/layer-validation-create-fn")+ .then()+ .statusCode(404);+ }++ @Test+ @Order(18)+ void updateFunctionConfiguration_withNonExistentLayer_returns400AndLeavesLayersUnchanged() throws Exception {+ String fnName = "layer-validation-update-fn";+ given()+ .contentType("application/json")+ .body("""+ {+ "FunctionName": "%s",+ "Runtime": "nodejs20.x",+ "Role": "arn:aws:iam::000000000000:role/lambda-role",+ "Handler": "index.handler",+ "Description": "original description",+ "Code": { "ZipFile": "%s" },+ "Layers": ["arn:aws:lambda:us-east-1:000000000000:layer:%s:2"]+ }+ """.formatted(fnName, functionZipBase64(), LAYER_NAME))+ .when()+ .post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ // Description is bundled into the SAME rejected request as the bad layer - this is+ // the regression check for validating Layers before any field mutation: if Layers+ // were checked where it's applied (after Description is already set on the live+ // stored object), this update would be rejected but Description would already have+ // silently changed.+ given()+ .contentType("application/json")+ .body("""+ {+ "Description": "should not be applied",+ "Layers": ["arn:aws:lambda:us-east-1:000000000000:layer:no-such-layer:1"]+ }+ """)+ .when()+ .put("/2015-03-31/functions/" + fnName + "/configuration")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterValueException"));++ given()+ .when()+ .get("/2015-03-31/functions/" + fnName)+ .then()+ .body("Configuration.Description", equalTo("original description"))+ .statusCode(200)+ .body("Configuration.Layers", hasSize(1))+ .body("Configuration.Layers[0].Arn", containsString(":layer:" + LAYER_NAME + ":2"));++ given()+ .when()+ .delete("/2015-03-31/functions/" + fnName)+ .then()+ .statusCode(204);+ }+// ── cleanup ──────────────────────────────────────────────────────────────@Test