fix(lambda): validate Layers ARNs eagerly on CreateFunction/UpdateFunctionConfiguration (#2282)

* fix(appconfig): add DeleteConfigurationProfile/DeleteHostedConfigurationVersion/ListDeploymentStrategies/DeleteDeploymentStrategy

These four operations had no route at all, so a request fell through
to S3's generic path-style catch-all (GET/DELETE /{bucket}[/{key}])
and returned a misleading NoSuchBucket 404 instead of a real AppConfig
response - confirmed via both raw HTTP and the real AWS SDK for Java.

Adds the missing routes + AppConfigService methods, mirroring existing
precedent (DeleteConfigurationProfile/DeleteHostedConfigurationVersion/
DeleteDeploymentStrategy follow DeleteApplication's idempotent-delete
convention - no upfront existence check; ListDeploymentStrategies
includes the three predefined strategies alongside custom ones,
verified against the API reference's own sample response).

DeleteDeploymentStrategy's real path is /deployementstrategies/{id}
(extra "e" - a genuine, documented quirk in AWS's own API model; every
other deployment-strategy operation correctly uses
/deploymentstrategies). Confirmed against the API reference and
reproduced against the real SDK, which sends the misspelled path
literally - matched it rather than "fixing" it, since wire-protocol
fidelity to what AWS actually does is the point.

Regenerated docs/services/appconfig.md's Supported Operations list
(hand-maintained for REST controllers - not yet covered by
tools/docs/regen_action_docs.py, confirmed via services.yaml's own
Phase-1 scope comment).

Tests: AppConfigIntegrationTest (+4), compatibility-tests/sdk-test-java
AppConfigTest (+1, covering all four operations via the real SDK).
Ran locally (JDK 25):

AppConfigIntegrationTest (unit):        29/29 passed
AppConfigTest (SDK compat, live):       16/16 passed

* fix(appconfig): scope profile deletion to its application, reject deleting predefined strategies

Review feedback on #2280 (Copilot + Greptile, both independently):

- deleteConfigurationProfile ignored appId entirely and deleted by the
  bare, globally-keyed profileId - a caller could delete another
  application's profile just by guessing/reusing its ID, since
  sibling reads (getConfigurationProfile) already enforce this
  ownership check but the new delete route didn't. Now rejects with
  the same ResourceNotFoundException as a mismatched get; a profileId
  that doesn't exist anywhere is still an idempotent no-op, matching
  deleteApplication's existing convention - only an existing-but-
  wrongly-scoped one is rejected.
- Same method also now cascades the delete to that profile's hosted
  configuration versions - they aren't independently addressable
  outside a profile's lifecycle, so leaving them in versionStore after
  the profile was "deleted" let a caller keep fetching versions for a
  profile that supposedly no longer exists.
- deleteDeploymentStrategy silently reported success (204) for a
  predefined strategy (e.g. AppConfig.AllAtOnce) without doing
  anything, since builtins were never in strategyStore in the first
  place - the strategy would still exist and still show up in every
  subsequent Get/List call despite the "successful" delete. Now
  rejects with BadRequestException.

Also applied this project's own established cleanup-logging
convention (System.err.println on a best-effort catch, matching
several other compatibility-tests/sdk-test-java files) to the one new
try/finally block flagged by Greptile, rather than swallowing the
exception silently.

Tests: 2 new AppConfigIntegrationTest cases (cross-application delete
rejected + original untouched, predefined-strategy delete rejected +
still resolvable) and 2 new SDK compatibility tests using the real
AWS SDK for Java v2's exception types.

AppConfigIntegrationTest:                31/31 passed
AppConfigTest (SDK compat, live):        18/18 passed

* fix(lambda): validate Layers ARNs eagerly on CreateFunction/UpdateFunctionConfiguration

Real AWS rejects an unresolvable layer ARN at attach time with
InvalidParameterValueException. Floci accepted any ARN unconditionally
- CreateFunction/UpdateFunctionConfiguration never validated it at
all, so the only signal was a silent WARN log from ContainerLauncher
when it tried (and failed) to mount the layer's content at container-
launch time, well after the caller had already moved on believing the
attach succeeded.

Adds LambdaLayerService as a LambdaService dependency and validates
each Layers ARN via the existing resolveLayerByArn before setting it
on the function, on both CreateFunction and UpdateFunctionConfiguration.
Left ContainerLauncher's existing warn-and-continue behavior alone for
the one case it still legitimately covers: a layer deleted *after*
being attached (real AWS doesn't re-validate layers on invoke either).

The three package-private test-only constructors (predating layer
support) now assign the new field null and validateLayersResolvable
short-circuits on it, following this class's own existing convention
for optional test-nulled dependencies (see the s3Service/aliasStore/
esmStore null-guards already throughout this file) - existing tests
using those constructors are unaffected.

Also fixes docs/services/lambda.md, which still described layer
support as entirely stubbed/unimplemented (PublishLayerVersion,
GetLayerVersion, ListLayerVersions, ListLayers, and DeleteLayerVersion
were all actually implemented already, just never documented as such).

This intentionally does NOT add real cross-account layer content
fetching (e.g. resolving the actual AWS-owned AppConfig Extension or a
Datadog-published layer) - there is no AWS-SDK/credential-handling
infrastructure anywhere in Floci for that, and it's a materially
larger feature (new dependency, credential trust boundary into
Floci's own control-plane process, cache/failure-semantics design)
than this fix. Documented as a known limitation instead.

Tests: LambdaLayerIntegrationTest (+2, covering both CreateFunction
and UpdateFunctionConfiguration rejecting an unresolvable layer and
leaving existing state unchanged). Ran locally (JDK 25):

LambdaLayerIntegrationTest:                  21/21 passed
LambdaServiceTest/PersistenceTest/
  ImageConfigTest/EventInvokeConfigTest/
  ContainerLauncherTest (constructor-affected): 114/114 passed

* fix(lambda): validate UpdateFunctionConfiguration's Layers before any field mutation

Review feedback on #2282 (Greptile): InMemoryStorage#get returns the
live object backing the store entry, not a copy, and this method
mutates that object's fields one by one with a single save() at the
end - validating Layers where it's applied (after Description,
Timeout, and several other fields are already set) meant a rejected
update could leave those earlier fields live on the stored function
even though the whole call returned 400.

Moves the Layers extraction + validateLayersResolvable call to the
very top of the method, before any field mutation, so a rejected
Layers ARN no longer has that side effect. CreateFunction didn't need
the same fix - its function object is newly constructed and never
touches the store until the very end, so a validation failure there
was already side-effect-free (confirmed by checking where zip
extraction happens relative to the existing Layers check - after it).

This is a narrow fix for the field this PR touches - the same
mutate-then-single-save pattern already existed for other fields
(e.g. the RevisionId check happens after Description/Handler/
MemorySize/Role/Runtime/Timeout/Environment are already mutated), so
it's a pre-existing gap for those, not something this PR introduces or
attempts to fix wholesale.

Strengthened the existing update-rejection test to bundle a Description
change into the same rejected request and assert it was NOT applied -
this is the actual regression check for the ordering fix, not just
that Layers itself was left alone.

LambdaLayerIntegrationTest: 21/21 passed.
This commit is contained in:
sheldon-nadarajah-sft authored and GitHub committed 2026-08-17 15:23:13 -04:00
1 parent 02898cf5e2
commit 2f0ef45978
3 files changed
+136 -6

No files matched your search

+10 -2
View File
@@ -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 Implemented
These 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`
@@ -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<>());
}
@@ -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