Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(lambda): code-signing endpoints and account settings (#2646)

Sam Fakhreddinec90c5adfcbc2
diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md
index ca45d79425..2aeaae2ecd 100644
--- a/docs/configuration/advanced/application-yml.md
+++ b/docs/configuration/advanced/application-yml.md
@@ -131,8 +131,8 @@ floci:
ephemeral: false # true = remove container after each invocation
default-memory-mb: 128
default-timeout-seconds: 3
- runtime-api-base-port: 9200 # Port range for Lambda Runtime API
- runtime-api-max-port: 9299
+ runtime-api-base-port: 12000 # Port range for Lambda Runtime API
+ runtime-api-max-port: 12499 # One port per running container = concurrency ceiling
code-path: ./data/lambda-code # Where ZIP archives are stored
poll-interval-ms: 1000
container-idle-timeout-seconds: 300 # Remove idle containers after this
diff --git a/docs/configuration/docker.md b/docs/configuration/docker.md
index 17c59fe979..fa7839ac6e 100644
--- a/docs/configuration/docker.md
+++ b/docs/configuration/docker.md
@@ -214,7 +214,7 @@ What each setting does and why it is needed:
!!! tip "When the Runtime API address is still unreachable"
On some Podman network topologies the auto-detected Runtime API address
(the host/IP Lambda containers use to call back into Floci) is still wrong,
- and invocations fail with `connect ECONNREFUSED <ip>:9200`. Set the address
+ and invocations fail with `connect ECONNREFUSED <ip>:12000`. Set the address
explicitly to bypass auto-detection:
```bash
diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md
index f65d0bb8ad..d98ffec7cd 100644
--- a/docs/configuration/environment-variables.md
+++ b/docs/configuration/environment-variables.md
@@ -189,8 +189,8 @@ See [Initialization Hooks](./initialization-hooks.md) for lifecycle phases and s
| `FLOCI_SERVICES_LAMBDA_EPHEMERAL` | `false` | Remove Lambda containers immediately after each invocation |
| `FLOCI_SERVICES_LAMBDA_DEFAULT_MEMORY_MB` | `128` | Default memory allocation for functions that don't specify one |
| `FLOCI_SERVICES_LAMBDA_DEFAULT_TIMEOUT_SECONDS` | `3` | Default invocation timeout in seconds |
-| `FLOCI_SERVICES_LAMBDA_RUNTIME_API_BASE_PORT` | `9200` | First port in the Lambda Runtime API port range |
-| `FLOCI_SERVICES_LAMBDA_RUNTIME_API_MAX_PORT` | `9299` | Last port in the Lambda Runtime API port range |
+| `FLOCI_SERVICES_LAMBDA_RUNTIME_API_BASE_PORT` | `12000` | First port in the Lambda Runtime API port range |
+| `FLOCI_SERVICES_LAMBDA_RUNTIME_API_MAX_PORT` | `12499` | Last port in the Lambda Runtime API port range. One port is held per running Lambda container, so the range width is the concurrent-execution ceiling |
| `FLOCI_SERVICES_LAMBDA_CODE_PATH` | `./data/lambda-code` | Container path where Lambda deployment ZIPs are stored |
| `FLOCI_SERVICES_LAMBDA_POLL_INTERVAL_MS` | `1000` | How often (ms) the SQS and Kinesis event source pollers check for new messages |
| `FLOCI_SERVICES_LAMBDA_CONTAINER_IDLE_TIMEOUT_SECONDS` | `300` | Seconds of inactivity before an idle Lambda container is removed |
diff --git a/docs/configuration/ports.md b/docs/configuration/ports.md
index 6a31ad4fb8..3f94a0e2d3 100644
--- a/docs/configuration/ports.md
+++ b/docs/configuration/ports.md
@@ -9,8 +9,8 @@
| `6379–6399` | TCP | ElastiCache Redis proxy (inside Floci) | Yes |
| `6500–6599` | HTTPS | EKS k3s API server — bound directly by each k3s container | **No** |
| `7001–7099` | TCP | RDS proxy (inside Floci) | Yes |
-| `9200–9299` | HTTP | Lambda Runtime API (internal, Docker-network only) | **No** |
| `9400–9499` | HTTP | OpenSearch data-plane — bound directly by each OpenSearch container | **No** |
+| `12000–12499` | HTTP | Lambda Runtime API (internal, Docker-network only) | **No** |
## Why some ports don't need docker-compose mapping
@@ -105,9 +105,11 @@ psql -h localhost -p 7001 -U admin
!!! note
Configure the range with `FLOCI_SERVICES_RDS_PROXY_BASE_PORT` and `FLOCI_SERVICES_RDS_PROXY_MAX_PORT`.
-## Ports 9200–9299 — Lambda Runtime API (internal)
+## Ports 12000–12499 — Lambda Runtime API (internal)
-Floci binds a Runtime API port in `9200–9299` for each warm Lambda container to poll. These ports are consumed by containers on the shared Docker network only — they are never accessed from the host and must **not** be mapped in `docker-compose.yml`.
+Floci binds a Runtime API port in `12000–12499` for each warm Lambda container to poll. These ports are consumed by containers on the shared Docker network only — they are never accessed from the host and must **not** be mapped in `docker-compose.yml`.
+
+One port is held for the lifetime of each running Lambda container, so the width of this range is a hard ceiling on **concurrent Lambda executions** — 500 with the default. This range was previously `9200–9299`; if you pinned that in your own configuration, raise it.
Configure the range with `FLOCI_SERVICES_LAMBDA_RUNTIME_API_BASE_PORT` and `FLOCI_SERVICES_LAMBDA_RUNTIME_API_MAX_PORT`.
diff --git a/docs/getting-started/quick-start.md b/docs/getting-started/quick-start.md
index 0887fb31c6..aabdff1c37 100644
--- a/docs/getting-started/quick-start.md
+++ b/docs/getting-started/quick-start.md
@@ -197,7 +197,7 @@ sudo ufw allow in on docker0 comment 'floci: containers reach host'
If you want to scope it tighter to just the Lambda Runtime API and the ECR registry port ranges:
```bash
-sudo ufw allow in on docker0 to any port 9200:9299 proto tcp comment 'floci lambda runtime api'
+sudo ufw allow in on docker0 to any port 12000:12499 proto tcp comment 'floci lambda runtime api'
sudo ufw allow in on docker0 to any port 5000:5099 proto tcp comment 'floci ecr registry'
```
diff --git a/docs/services/index.md b/docs/services/index.md
index 9cd19dbe82..fa294f7851 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -18,7 +18,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [S3 Tables](s3tables.md) | `/buckets`, `/namespaces/*`, `/tables/*` | REST JSON | 25 |
| [DynamoDB](dynamodb.md) | `POST /` + `X-Amz-Target: DynamoDB_20120810.*` | JSON 1.1 | 28 |
| [DynamoDB Streams](dynamodb.md#streams) | `POST /` + `X-Amz-Target: DynamoDBStreams_20120810.*` | JSON 1.1 | 4 |
-| [Lambda](lambda.md) | `/2015-03-31/functions/...` | REST JSON | 30 |
+| [Lambda](lambda.md) | `/2015-03-31/functions/...` | REST JSON | 46 |
| [Lambda MicroVMs](lambda-microvms.md) | `/2025-09-09/...` + `/2026-04-04/...` | REST JSON | 22 |
| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 79 |
| [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 53 + data-plane |
diff --git a/docs/services/lambda.md b/docs/services/lambda.md
index 754d0e2d8d..62517d54dd 100644
--- a/docs/services/lambda.md
+++ b/docs/services/lambda.md
@@ -33,6 +33,7 @@ Floci Lambda runs your function code locally inside real Docker containers - clo
| `GetPolicy` | Get the function resource policy |
| `RemovePermission` | Remove a resource-policy statement |
| `GetFunctionCodeSigningConfig` | Return code-signing config (always empty) |
+| `ListFunctionsByCodeSigningConfig` | Validates the ARN; no code-signing config can exist, so every well-formed ARN returns `ResourceNotFoundException` |
| `CreateFunctionUrlConfig` | Provision a function URL |
| `GetFunctionUrlConfig` | Read function URL config |
| `UpdateFunctionUrlConfig` | Update function URL config |
@@ -43,6 +44,7 @@ Floci Lambda runs your function code locally inside real Docker containers - clo
| `PutFunctionConcurrency` | Set reserved concurrent executions |
| `GetFunctionConcurrency` | Get reserved concurrent executions |
| `DeleteFunctionConcurrency` | Clear reserved concurrent executions |
+| `GetAccountSettings` | Account limits plus usage derived from the caller's stored functions |
## Hot-Reloading via Reactive S3 Sync
@@ -182,8 +184,7 @@ These AWS Lambda operations have no handler in Floci. Calls will return `404` or
- Provisioned concurrency (`PutProvisionedConcurrencyConfig`, `GetProvisionedConcurrencyConfig`, `ListProvisionedConcurrencyConfigs`, `DeleteProvisionedConcurrencyConfig`)
- Dead-letter, async invoke config, and event invoke config operations
- `InvokeWithResponseStream`
-- Code signing management (only `GetFunctionCodeSigningConfig` is wired; there is no `PutFunctionCodeSigningConfig` or `CreateCodeSigningConfig`)
-- Account and regional settings (`GetAccountSettings`)
+- Code signing management (only `GetFunctionCodeSigningConfig` and `ListFunctionsByCodeSigningConfig` are wired; there is no `PutFunctionCodeSigningConfig` or `CreateCodeSigningConfig`, so no code-signing config can exist and `ListFunctionsByCodeSigningConfig` reports every well-formed ARN as `ResourceNotFoundException` — a malformed ARN or an out-of-range `MaxItems` is rejected with `InvalidParameterValueException` first)
## Configuration
@@ -193,8 +194,8 @@ These AWS Lambda operations have no handler in Floci. Calls will return `404` or
| `FLOCI_SERVICES_LAMBDA_EPHEMERAL` | `false` | Remove containers after each invocation |
| `FLOCI_SERVICES_LAMBDA_DEFAULT_MEMORY_MB` | `128` | Default function memory (MB) |
| `FLOCI_SERVICES_LAMBDA_DEFAULT_TIMEOUT_SECONDS` | `3` | Default function timeout (seconds) |
-| `FLOCI_SERVICES_LAMBDA_RUNTIME_API_BASE_PORT` | `9200` | First port in the Lambda Runtime API range |
-| `FLOCI_SERVICES_LAMBDA_RUNTIME_API_MAX_PORT` | `9299` | Last port in the Lambda Runtime API range |
+| `FLOCI_SERVICES_LAMBDA_RUNTIME_API_BASE_PORT` | `12000` | First port in the Lambda Runtime API range |
+| `FLOCI_SERVICES_LAMBDA_RUNTIME_API_MAX_PORT` | `12499` | Last port in the Lambda Runtime API range. One port is held per running container, so the range width caps concurrent executions |
| `FLOCI_SERVICES_LAMBDA_CODE_PATH` | `./data/lambda-code` | Directory where Lambda ZIP files are stored |
| `FLOCI_SERVICES_LAMBDA_POLL_INTERVAL_MS` | `1000` | Event-source mapping poll interval (milliseconds) |
| `FLOCI_SERVICES_LAMBDA_CONTAINER_IDLE_TIMEOUT_SECONDS` | `300` | Idle container shutdown timeout (seconds) |
@@ -235,7 +236,7 @@ correct and needs no configuration.
On unusual network topologies, for example rootless Podman, auto-detection
can pick an address the Lambda container cannot reach, and invocations fail with
-`connect ECONNREFUSED <ip>:9200`. Set `FLOCI_SERVICES_LAMBDA_DOCKER_HOST_OVERRIDE`
+`connect ECONNREFUSED <ip>:12000`. Set `FLOCI_SERVICES_LAMBDA_DOCKER_HOST_OVERRIDE`
to the host or IP that containers can actually reach Floci on, and Floci uses it
verbatim instead of auto-detecting:
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index ce2cd62255..8ee566d0c1 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -1649,10 +1649,25 @@ public interface EmulatorConfig {
Optional<String> dockerHostOverride();
- @WithDefault("9200")
+ /**
+ * Runtime API port pool. One port is held for the lifetime of each running Lambda
+ * container, so this range is a hard ceiling on concurrent Lambda executions.
+ *
+ * <p>The former 9200-9299 default was exactly 100 ports, which cannot run a
+ * multi-account landing zone — LZA's LoggingStack fans out ~8 custom-resource Lambdas
+ * per account, so a 14-account org needs ~112 at once. Exhaustion did not read as a
+ * capacity limit either: the custom resource reported FAILED and CloudFormation rolled
+ * the stack back, so it surfaced as an unrelated CFN error (issue #2206).
+ *
+ * <p>12000-12499 rather than a widened 9200 range: 9200 is OpenSearch, 9092 Kafka,
+ * 9644 the Redpanda admin port and 9400-9499 the ECS proxy pool. Those are
+ * sibling-container-internal so they would not truly collide, but a pool this wide
+ * stops being obvious about what it covers. 12000-12499 touches nothing.
+ */
+ @WithDefault("12000")
int runtimeApiBasePort();
- @WithDefault("9299")
+ @WithDefault("12499")
int runtimeApiMaxPort();
@WithDefault("./data/lambda-code")
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/port/PortAllocator.java b/src/main/java/io/github/hectorvent/floci/core/common/port/PortAllocator.java
index c5fc7f00af..36b80616b7 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/port/PortAllocator.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/port/PortAllocator.java
@@ -36,8 +36,18 @@ public class PortAllocator {
return p;
}
}
+ // This exception usually reaches an operator second-hand — a custom resource reports
+ // FAILED and CloudFormation rolls the stack back, so what they see is a CFN error and
+ // this text buried in floci's own log. It has to carry its own diagnosis: which pool
+ // ran dry, how wide it was, and the property that widens it. Otherwise the only way to
+ // learn the knob exists is to find this class in the source (issue #2206).
throw new IllegalStateException(
- "No free ports in range " + basePort + "-" + maxPort);
+ "Lambda Runtime API port pool exhausted: no free ports in range "
+ + basePort + "-" + maxPort + " (" + (maxPort - basePort + 1)
+ + " ports, all in use). One port is held per running Lambda container, "
+ + "so this is the concurrent-execution ceiling. Widen it with "
+ + "floci.services.lambda.runtime-api-base-port / "
+ + "floci.services.lambda.runtime-api-max-port.");
}
public void release(int port) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaAccountSettingsController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaAccountSettingsController.java
new file mode 100644
index 0000000000..d8706bd859
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaAccountSettingsController.java
@@ -0,0 +1,61 @@
+package io.github.hectorvent.floci.services.lambda;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+
+/**
+ * Lambda account settings endpoint.
+ *
+ * <p>GetAccountSettings: {@code GET /2016-08-19/account-settings/}. The account limits mirror
+ * AWS's fixed storage defaults plus the configured region concurrency limit; the usage block is
+ * derived from the caller's stored functions.
+ */
+@Path("/2016-08-19")
+@Produces(MediaType.APPLICATION_JSON)
+public class LambdaAccountSettingsController {
+
+ private static final long ACCOUNT_TOTAL_CODE_SIZE_BYTES = 80_530_636_800L;
+ private static final long CODE_SIZE_UNZIPPED_BYTES = 262_144_000L;
+ private static final long CODE_SIZE_ZIPPED_BYTES = 52_428_800L;
+
+ private final LambdaService lambdaService;
+ private final RegionResolver regionResolver;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public LambdaAccountSettingsController(LambdaService lambdaService,
+ RegionResolver regionResolver,
+ ObjectMapper objectMapper) {
+ this.lambdaService = lambdaService;
+ this.regionResolver = regionResolver;
+ this.objectMapper = objectMapper;
+ }
+
+ @GET
+ @Path("/account-settings")
+ public Response getAccountSettings(@Context HttpHeaders headers) {
+ String region = regionResolver.resolveRegion(headers);
+ LambdaService.AccountSettings settings = lambdaService.getAccountSettings(region);
+
+ ObjectNode root = objectMapper.createObjectNode();
+ ObjectNode accountLimit = root.putObject("AccountLimit");
+ accountLimit.put("TotalCodeSize", ACCOUNT_TOTAL_CODE_SIZE_BYTES);
+ accountLimit.put("CodeSizeUnzipped", CODE_SIZE_UNZIPPED_BYTES);
+ accountLimit.put("CodeSizeZipped", CODE_SIZE_ZIPPED_BYTES);
+ accountLimit.put("ConcurrentExecutions", settings.concurrentExecutions());
+ accountLimit.put("UnreservedConcurrentExecutions", settings.unreservedConcurrentExecutions());
+ ObjectNode accountUsage = root.putObject("AccountUsage");
+ accountUsage.put("TotalCodeSize", settings.totalCodeSize());
+ accountUsage.put("FunctionCount", settings.functionCount());
+ return Response.ok(root).build();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.java
index 282f723f53..88c18d02c0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.java
@@ -13,7 +13,8 @@ import java.util.regex.Pattern;
*/
public final class LambdaArnUtils {
- private static final Pattern NAME_PATTERN = Pattern.compile("[a-zA-Z0-9-_]+");
+ private static final Pattern NAME_PATTERN = Pattern.compile("[a-zA-Z0-9-_.]+");
+ private static final int MAX_NAME_LENGTH = 256;
private static final Pattern ACCOUNT_PATTERN = Pattern.compile("\\d{12}");
private static final Pattern QUALIFIER_PATTERN = Pattern.compile("\\$LATEST|[a-zA-Z0-9-_]+");
@@ -144,6 +145,9 @@ public final class LambdaArnUtils {
if (name == null || name.isEmpty()) {
throw invalid("FunctionName segment is empty");
}
+ if (name.length() > MAX_NAME_LENGTH) {
+ throw invalid("FunctionName exceeds maximum length of " + MAX_NAME_LENGTH + ": " + name);
+ }
if (!NAME_PATTERN.matcher(name).matches()) {
throw invalid("FunctionName contains invalid characters: " + name);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigFunctionsController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigFunctionsController.java
new file mode 100644
index 0000000000..2d2697e54c
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigFunctionsController.java
@@ -0,0 +1,103 @@
+package io.github.hectorvent.floci.services.lambda;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.PathParam;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.QueryParam;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+
+import java.util.regex.Pattern;
+
+/**
+ * ListFunctionsByCodeSigningConfig: GET /2020-04-22/code-signing-configs/{CodeSigningConfigArn}/functions.
+ *
+ * <p>A separate class from {@link LambdaCodeSigningController} because it lives
+ * under a different API version prefix (/2020-04-22 vs /2020-06-30) — JAX-RS
+ * class-level {@code @Path} can only be one literal prefix, and a class without
+ * one falls through to a more general catch-all route (S3's bucket-path matcher)
+ * instead of matching here.</p>
+ *
+ * <p>Floci does not implement code signing config management — there is no
+ * CreateCodeSigningConfig / PutFunctionCodeSigningConfig, so no code signing
+ * config can ever exist. That does <em>not</em> make an unconditional empty list
+ * the right answer: botocore models both {@code InvalidParameterValueException}
+ * and {@code ResourceNotFoundException} for this operation, and the only resource
+ * the path parameter can name is a code signing config. A malformed ARN is
+ * therefore a 400 and a well-formed ARN is a 404, because every well-formed ARN
+ * necessarily names a config that does not exist here. Returning 200 with an
+ * empty list would tell a caller that the config exists and simply has no
+ * functions attached, which is a different — and false — statement.</p>
+ */
+@Path("/2020-04-22")
+@Produces(MediaType.APPLICATION_JSON)
+@Consumes(MediaType.APPLICATION_JSON)
+public class LambdaCodeSigningConfigFunctionsController {
+
+ /**
+ * botocore's {@code CodeSigningConfigArn} shape pattern, verbatim. Applied with
+ * {@link String#matches(String)} so it is anchored whole-string, which is the
+ * right semantics for an ARN; the shape's {@code max: 200} is checked separately
+ * because the pattern itself does not bound the partition suffix.
+ */
+ private static final Pattern CODE_SIGNING_CONFIG_ARN = Pattern.compile(
+ "arn:(aws[a-zA-Z-]*)?:lambda:(eusc-)?[a-z]{2}((-gov)|(-iso([a-z]?)))?-[a-z]+-\\d{1}"
+ + ":\\d{12}:code-signing-config:csc-[a-z0-9]{17}");
+
+ private static final int ARN_MAX_LENGTH = 200;
+ private static final int MAX_ITEMS_MIN = 1;
+ private static final int MAX_ITEMS_MAX = 10000;
+
+ /**
+ * Validation order matches AWS: request parameters are rejected before the
+ * resource is resolved, so a bad {@code MaxItems} is reported as such rather
+ * than being masked by the not-found that every well-formed ARN produces here.
+ */
+ @GET
+ @Path("/code-signing-configs/{codeSigningConfigArn}/functions")
+ public Response listFunctionsByCodeSigningConfig(
+ @PathParam("codeSigningConfigArn") String codeSigningConfigArn,
+ @QueryParam("Marker") String marker,
+ @QueryParam("MaxItems") String maxItems) {
+ requireValidArn(codeSigningConfigArn);
+ parseMaxItems(maxItems);
+ // Marker is accepted and carries no state: the result set is always empty,
+ // so any marker addresses a page past the end and NextMarker is never emitted.
+
+ throw new AwsException("ResourceNotFoundException",
+ "The code signing configuration " + codeSigningConfigArn + " does not exist.", 404);
+ }
+
+ private void requireValidArn(String arn) {
+ if (arn == null || arn.isBlank()
+ || arn.length() > ARN_MAX_LENGTH
+ || !CODE_SIGNING_CONFIG_ARN.matcher(arn).matches()) {
+ throw new AwsException("InvalidParameterValueException",
+ "1 validation error detected: Value '" + arn + "' at 'codeSigningConfigArn' "
+ + "failed to satisfy constraint: Member must satisfy regular expression pattern: "
+ + CODE_SIGNING_CONFIG_ARN.pattern(), 400);
+ }
+ }
+
+ private void parseMaxItems(String maxItems) {
+ if (maxItems == null || maxItems.isBlank()) {
+ return;
+ }
+ int value;
+ try {
+ value = Integer.parseInt(maxItems.trim());
+ } catch (NumberFormatException e) {
+ throw new AwsException("InvalidParameterValueException",
+ "Value '" + maxItems + "' at 'maxItems' failed to satisfy constraint: "
+ + "Member must be an integer", 400);
+ }
+ if (value < MAX_ITEMS_MIN || value > MAX_ITEMS_MAX) {
+ throw new AwsException("InvalidParameterValueException",
+ "Value '" + value + "' at 'maxItems' failed to satisfy constraint: "
+ + "Member must be between " + MAX_ITEMS_MIN + " and " + MAX_ITEMS_MAX, 400);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningController.java
index ab99ee36dd..68ddf30efd 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningController.java
@@ -25,6 +25,11 @@ import jakarta.ws.rs.core.Response;
* when no signing config is attached). Non-existent functions surface a 404 via
* LambdaService, unblocking Terraform and other tools that call this endpoint as
* part of their normal Lambda resource lifecycle.
+ *
+ * The class-level prefix matters: without it, requests here fall through to a more
+ * general catch-all route elsewhere (S3's bucket-path matcher) instead of this
+ * controller — see {@link LambdaCodeSigningConfigFunctionsController} for the
+ * separate /2020-04-22 endpoint, which needs its own class for the same reason.
*/
@Path("/2020-06-30")
@Produces(MediaType.APPLICATION_JSON)
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaFunctionStore.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaFunctionStore.java
index e25a32304a..202efdcd32 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaFunctionStore.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaFunctionStore.java
@@ -13,6 +13,7 @@ import jakarta.inject.Inject;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Predicate;
/**
* Wraps the storage backend for Lambda functions with region-aware key logic.
@@ -82,6 +83,22 @@ public class LambdaFunctionStore implements Resettable {
indexFunction(fn);
}
+ /**
+ * Saves into {@code accountId}'s partition rather than the ambient caller's. Async
+ * paths (CDI observers, pollers) run with no {@code RequestContext} and would
+ * otherwise write every account's function into the default account's partition.
+ */
+ public void saveForAccount(String accountId, String region, LambdaFunction fn) {
+ getForAccount(accountId, region, fn.getFunctionName(), fn.getVersion()).ifPresent(this::deindexFunction);
+
+ if (backend instanceof AccountAwareStorageBackend<LambdaFunction> aware) {
+ aware.putForAccount(accountId, regionKey(region, fn.getFunctionName(), fn.getVersion()), fn);
+ } else {
+ backend.put(regionKey(region, fn.getFunctionName(), fn.getVersion()), fn);
+ }
+ indexFunction(fn);
+ }
+
public Optional<LambdaFunction> get(String region, String functionName) {
return get(region, functionName, "$LATEST");
}
@@ -126,8 +143,26 @@ public class LambdaFunctionStore implements Resettable {
return backend.scan(key -> key.startsWith(prefix));
}
+ /**
+ * Like {@link #list(String)}, but across every account's partition. For async callers
+ * that have no {@code RequestContext} and so would otherwise see only the default
+ * account's functions.
+ */
+ public List<LambdaFunction> listAllAccounts(String region) {
+ String prefix = "lambda::" + region + "::";
+ Predicate<String> filter = key -> key.startsWith(prefix) && key.endsWith("::$LATEST");
+ if (backend instanceof AccountAwareStorageBackend<LambdaFunction> aware) {
+ return aware.scanAllAccountEntries(filter).stream()
+ .map(AccountAwareStorageBackend.AccountEntry::value)
+ .toList();
+ }
+ return backend.scan(filter);
+ }
+
public List<LambdaFunction> listAll() {
- return backend.scan(key -> true);
+ return backend instanceof AccountAwareStorageBackend<LambdaFunction> aware
+ ? aware.scanAllAccounts()
+ : backend.scan(key -> true);
}
public void delete(String region, String functionName) {
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 5e686e66f2..6861c774ce 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
@@ -62,6 +62,10 @@ public class LambdaService implements ResourceProvider {
+ "\\d{12}:access-point/fsap-[a-f0-9]{17}$");
private static final Pattern FILE_SYSTEM_LOCAL_MOUNT_PATH = Pattern.compile("^/mnt/[A-Za-z0-9._-]+$");
private static final Pattern LOG_GROUP_PATTERN = Pattern.compile("[.\\-_/#A-Za-z0-9]+");
+ 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+");
+ private static final int MAX_HANDLER_LENGTH = 128;
private final LambdaFunctionStore functionStore;
private final LambdaExecutorService executorService;
@@ -543,6 +547,12 @@ public class LambdaService implements ResourceProvider {
if (request.containsKey("LoggingConfig")) {
validateLoggingConfig(request.get("LoggingConfig"));
}
+ if (request.containsKey("Role")) {
+ validateRoleArn((String) request.get("Role"));
+ }
+ if (request.containsKey("Handler")) {
+ validateHandler((String) request.get("Handler"));
+ }
Map<String, Object> requestedVpcConfig = fn.getVpcConfig();
if (request.get("VpcConfig") instanceof Map<?, ?>) {
@@ -700,9 +710,11 @@ public class LambdaService implements ResourceProvider {
if (concurrencyLimiter != null) {
concurrencyLimiter.reset(arn);
}
- codeStore.delete(functionName);
+ codeStore.delete(ownerAccount(fn), functionName);
functionStore.delete(region, functionName);
- versionCounters.remove(region + "::" + functionName);
+ reclaimLegacyCodeDirectoryIfUnused(functionName);
+ versionCounters.remove(versionCounterKey(region, fn));
+ versionCounters.remove(legacyVersionCounterKey(region, functionName));
if (aliasStore != null) {
for (LambdaAlias alias : aliasStore.list(region, functionName)) {
aliasStore.delete(region, functionName, alias.getName());
@@ -721,6 +733,27 @@ public class LambdaService implements ResourceProvider {
LOG.infov("Deleted Lambda function: {0}", functionName);
}
+ /**
+ * The pre-account-scoped code layout gave every account's same-named function the exact
+ * same on-disk directory (CodeStore never scoped it by region either), so it is only safe
+ * to reclaim once nothing at all still has {@code codeLocalPath} pointing at it. That
+ * includes published versions, not just {@code $LATEST}: publishVersion snapshots
+ * codeLocalPath verbatim, so a version published while $LATEST was still on the legacy path
+ * keeps that directory alive on its own even after $LATEST itself migrates. Checking only
+ * $LATEST (via listAllAccounts) missed this and let a later delete or code update reclaim
+ * the directory out from under that version's own future invokes. listAll() has no region
+ * or $LATEST filter, matching the fact that the legacy path itself carries neither.
+ */
+ private void reclaimLegacyCodeDirectoryIfUnused(String functionName) {
+ String legacyPath = codeStore.getLegacyCodePath(functionName).toAbsolutePath().normalize().toString();
+ boolean stillLive = functionStore.listAll().stream()
+ .anyMatch(other -> functionName.equals(other.getFunctionName())
+ && legacyPath.equals(other.getCodeLocalPath()));
+ if (!stillLive) {
+ codeStore.deleteLegacy(functionName);
+ }
+ }
+
public InvokeResult invoke(String region, String functionName, byte[] payload, InvocationType type) {
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(functionName);
enforceRegion(region, ref);
@@ -1133,70 +1166,102 @@ public class LambdaService implements ResourceProvider {
* {@code concurrencyOpLocks}) so publishes of unrelated functions do not
* serialize on the instance monitor for the storage round-trip.
*/
- private int nextVersionNumber(String counterKey) {
+ private int nextVersionNumber(String counterKey, String legacyCounterKey) {
synchronized (versionCounterLocks.computeIfAbsent(counterKey, k -> new Object())) {
- int next = versionCounters.getOrDefault(counterKey, 0) + 1;
+ Integer current = versionCounters.get(counterKey);
+ if (current == null && legacyCounterKey != null) {
+ // Counters persisted before the key carried the owning account. Starting over
+ // from 0 here would re-issue a version number that already names a snapshot.
+ current = versionCounters.remove(legacyCounterKey);
+ }
+ int next = (current != null ? current : 0) + 1;
versionCounters.put(counterKey, next);
return next;
}
}
+ /**
+ * Version numbering belongs to the owning account, not to whichever account's
+ * partition the counter map happens to be reached through.
+ */
+ static String versionCounterKey(String region, LambdaFunction fn) {
+ return region + "::" + ownerAccount(fn) + "::" + fn.getFunctionName();
+ }
+
+ /** The pre-account counter key, still present in persisted state from before this change. */
+ private static String legacyVersionCounterKey(String region, String functionName) {
+ return region + "::" + functionName;
+ }
+
+ /** Package-private accessor for tests that need to seed or inspect counter state. */
+ Map<String, Integer> versionCounters() {
+ return versionCounters;
+ }
+
public LambdaFunction publishVersion(String region, String functionName, String description) {
LambdaFunction fn = getFunction(region, functionName);
functionName = fn.getFunctionName();
- int version = nextVersionNumber(region + "::" + functionName);
- LambdaFunction snapshot = new LambdaFunction();
- snapshot.setAccountId(fn.getAccountId());
- snapshot.setFunctionName(fn.getFunctionName());
- snapshot.setVersion(String.valueOf(version));
- snapshot.setFunctionArn(fn.getFunctionArn().replace(":$LATEST", "") + ":" + version);
- snapshot.setRuntime(fn.getRuntime());
- snapshot.setRole(fn.getRole());
- snapshot.setHandler(fn.getHandler());
- snapshot.setDescription(description != null ? description : fn.getDescription());
- snapshot.setTimeout(fn.getTimeout());
- snapshot.setMemorySize(fn.getMemorySize());
- snapshot.setPackageType(fn.getPackageType());
- snapshot.setState(fn.getState());
- snapshot.setCodeSizeBytes(fn.getCodeSizeBytes());
- snapshot.setEnvironment(fn.getEnvironment());
- snapshot.setVpcConfig(fn.getVpcConfig() == null
- ? null
- : new java.util.HashMap<>(fn.getVpcConfig()));
- snapshot.setVpcId(fn.getVpcId());
- snapshot.setSnapStartApplyOn(fn.getSnapStartApplyOn());
- snapshot.setLogFormat(fn.getLogFormat());
- snapshot.setApplicationLogLevel(fn.getApplicationLogLevel());
- snapshot.setSystemLogLevel(fn.getSystemLogLevel());
- snapshot.setLogGroup(fn.getLogGroup());
- snapshot.setFileSystemConfigs(new ArrayList<>(fn.getFileSystemConfigs()));
- snapshot.setLastModified(System.currentTimeMillis());
- snapshot.setRevisionId(UUID.randomUUID().toString());
-
- // Everything that determines what actually runs. Without these the snapshot describes a
- // function with no code: a version-qualified invoke resolves to it, launches a container
- // with nothing in it, and hangs to the function timeout instead of failing (#1987). A
- // published version is an immutable snapshot of code plus configuration, so it carries the
- // code location for every package type, not only Zip.
- snapshot.setCodeLocalPath(fn.getCodeLocalPath());
- snapshot.setCodeSha256(fn.getCodeSha256());
- snapshot.setS3Bucket(fn.getS3Bucket());
- snapshot.setS3Key(fn.getS3Key());
- snapshot.setHotReloadHostPath(fn.getHotReloadHostPath());
- snapshot.setImageUri(fn.getImageUri());
- snapshot.setImageConfigCommand(fn.getImageConfigCommand());
- snapshot.setImageConfigEntryPoint(fn.getImageConfigEntryPoint());
- snapshot.setImageConfigWorkingDirectory(fn.getImageConfigWorkingDirectory());
- snapshot.setLayers(fn.getLayers());
- snapshot.setArchitectures(fn.getArchitectures());
- snapshot.setEphemeralStorageSize(fn.getEphemeralStorageSize());
- snapshot.setTracingMode(fn.getTracingMode());
- snapshot.setDeadLetterTargetArn(fn.getDeadLetterTargetArn());
- snapshot.setKmsKeyArn(fn.getKmsKeyArn());
-
- functionStore.save(region, snapshot);
- LOG.infov("Published version {0} for function {1}", version, functionName);
- return snapshot;
+ // Shares the per-function lock deleteFunction and extractZipCodeBytes take around their
+ // own codeLocalPath-affecting work: without it, a version could be published in the
+ // narrow window between reclaimLegacyCodeDirectoryIfUnused's check and its actual
+ // delete, persisting a snapshot.codeLocalPath (below) that names a directory about to
+ // be removed as unreferenced.
+ synchronized (lockForConcurrencyOp(fn.getFunctionArn())) {
+ int version = nextVersionNumber(versionCounterKey(region, fn),
+ legacyVersionCounterKey(region, functionName));
+ LambdaFunction snapshot = new LambdaFunction();
+ snapshot.setAccountId(fn.getAccountId());
+ snapshot.setFunctionName(fn.getFunctionName());
+ snapshot.setVersion(String.valueOf(version));
+ snapshot.setFunctionArn(fn.getFunctionArn().replace(":$LATEST", "") + ":" + version);
+ snapshot.setRuntime(fn.getRuntime());
+ snapshot.setRole(fn.getRole());
+ snapshot.setHandler(fn.getHandler());
+ snapshot.setDescription(description != null ? description : fn.getDescription());
+ snapshot.setTimeout(fn.getTimeout());
+ snapshot.setMemorySize(fn.getMemorySize());
+ snapshot.setPackageType(fn.getPackageType());
+ snapshot.setState(fn.getState());
+ snapshot.setCodeSizeBytes(fn.getCodeSizeBytes());
+ snapshot.setEnvironment(fn.getEnvironment());
+ snapshot.setVpcConfig(fn.getVpcConfig() == null
+ ? null
+ : new java.util.HashMap<>(fn.getVpcConfig()));
+ snapshot.setVpcId(fn.getVpcId());
+ snapshot.setSnapStartApplyOn(fn.getSnapStartApplyOn());
+ snapshot.setLogFormat(fn.getLogFormat());
+ snapshot.setApplicationLogLevel(fn.getApplicationLogLevel());
+ snapshot.setSystemLogLevel(fn.getSystemLogLevel());
+ snapshot.setLogGroup(fn.getLogGroup());
+ snapshot.setFileSystemConfigs(new ArrayList<>(fn.getFileSystemConfigs()));
+ snapshot.setLastModified(System.currentTimeMillis());
+ snapshot.setRevisionId(UUID.randomUUID().toString());
+
+ // Everything that determines what actually runs. Without these the snapshot describes a
+ // function with no code: a version-qualified invoke resolves to it, launches a container
+ // with nothing in it, and hangs to the function timeout instead of failing (#1987). A
+ // published version is an immutable snapshot of code plus configuration, so it carries the
+ // code location for every package type, not only Zip.
+ snapshot.setCodeLocalPath(fn.getCodeLocalPath());
+ snapshot.setCodeSha256(fn.getCodeSha256());
+ snapshot.setS3Bucket(fn.getS3Bucket());
+ snapshot.setS3Key(fn.getS3Key());
+ snapshot.setHotReloadHostPath(fn.getHotReloadHostPath());
+ snapshot.setImageUri(fn.getImageUri());
+ snapshot.setImageConfigCommand(fn.getImageConfigCommand());
+ snapshot.setImageConfigEntryPoint(fn.getImageConfigEntryPoint());
+ snapshot.setImageConfigWorkingDirectory(fn.getImageConfigWorkingDirectory());
+ snapshot.setLayers(fn.getLayers());
+ snapshot.setArchitectures(fn.getArchitectures());
+ snapshot.setEphemeralStorageSize(fn.getEphemeralStorageSize());
+ snapshot.setTracingMode(fn.getTracingMode());
+ snapshot.setDeadLetterTargetArn(fn.getDeadLetterTargetArn());
+ snapshot.setKmsKeyArn(fn.getKmsKeyArn());
+
+ functionStore.save(region, snapshot);
+ LOG.infov("Published version {0} for function {1}", version, functionName);
+ return snapshot;
+ }
}
private static List<LambdaFileSystemConfig> parseFileSystemConfigs(Object value) {
@@ -1337,6 +1402,43 @@ public class LambdaService implements ResourceProvider {
}
}
+ /**
+ * Role must be an IAM role ARN ({@code arn:aws*:iam::ACCOUNT:role/NAME}); blank/absent is
+ * only valid because callers gate this on {@code containsKey("Role")} beforehand.
+ */
+ private static void validateRoleArn(String role) {
+ if (role == null || !ROLE_ARN_PATTERN.matcher(role).matches()) {
+ throw new AwsException("InvalidParameterValueException",
+ "1 validation error detected: Value '" + role + "' at 'role' failed to satisfy "
+ + "constraint: Member must satisfy regular expression pattern: "
+ + ROLE_ARN_PATTERN.pattern(), 400);
+ }
+ }
+
+ /**
+ * Handler must be a 0-128 character string with no whitespace; unlike {@code Description},
+ * a caller-supplied {@code null} is rejected rather than treated as "clear it" — {@code null}
+ * is not a string at all, and Handler names the file AWS invokes, so silently nulling it out
+ * would break every subsequent invocation instead of failing the request that caused it.
+ */
+ private static void validateHandler(String handler) {
+ if (handler == null) {
+ throw new AwsException("InvalidParameterValueException",
+ "1 validation error detected: Value 'null' at 'handler' failed to satisfy "
+ + "constraint: Member must not be null", 400);
+ }
+ if (handler.isEmpty()) {
+ return;
+ }
+ if (handler.length() > MAX_HANDLER_LENGTH || !HANDLER_PATTERN.matcher(handler).matches()) {
+ throw new AwsException("InvalidParameterValueException",
+ "1 validation error detected: Value '" + handler + "' at 'handler' failed to satisfy "
+ + "constraint: Member must satisfy regular expression pattern: "
+ + HANDLER_PATTERN.pattern() + " or member must have length less than or equal to "
+ + MAX_HANDLER_LENGTH, 400);
+ }
+ }
+
/**
* LoggingConfig is replaced wholesale, not merged: AWS resets any member the request omits
* back to its default, so an update that names only LogFormat drops a previously set LogGroup.
@@ -1634,6 +1736,31 @@ public class LambdaService implements ResourceProvider {
return fn.getReservedConcurrentExecutions();
}
+ /**
+ * Aggregates the caller's stored {@code $LATEST} functions in a region: code-size usage,
+ * function count, and the unreserved share of the configured concurrency limit.
+ */
+ public AccountSettings getAccountSettings(String region) {
+ List<LambdaFunction> functions = functionStore.list(region);
+ long totalCodeSize = 0;
+ long reserved = 0;
+ for (LambdaFunction fn : functions) {
+ totalCodeSize += fn.getCodeSizeBytes();
+ if (fn.getReservedConcurrentExecutions() != null) {
+ reserved += fn.getReservedConcurrentExecutions();
+ }
+ }
+ int concurrencyLimit = config != null
+ ? config.services().lambda().regionConcurrencyLimit()
+ : 1000;
+ long unreserved = Math.max(0, concurrencyLimit - reserved);
+ return new AccountSettings(totalCodeSize, functions.size(), concurrencyLimit, unreserved);
+ }
+
+ public record AccountSettings(long totalCodeSize, int functionCount,
+ int concurrentExecutions, long unreservedConcurrentExecutions) {
+ }
+
public void deleteFunctionConcurrency(String region, String functionName) {
LambdaFunction fn = getFunction(region, functionName);
String arn = fn.getFunctionArn();
@@ -1657,7 +1784,8 @@ public class LambdaService implements ResourceProvider {
}
}
- private Object lockForConcurrencyOp(String functionArn) {
+ /** Package-private (not private) so tests can hold this lock to prove a critical section waits for it. */
+ Object lockForConcurrencyOp(String functionArn) {
return concurrencyOpLocks.computeIfAbsent(functionArn, k -> new Object());
}
@@ -1693,10 +1821,18 @@ public class LambdaService implements ResourceProvider {
return "awslambda-" + r + "-tasks";
}
+ /**
+ * The account that owns a function, for keying account-scoped state (its S3 code key,
+ * its on-disk extraction directory, its PublishVersion counter). All three must agree,
+ * so they all derive the account here.
+ */
+ static String ownerAccount(LambdaFunction fn) {
+ return fn.getAccountId() != null ? fn.getAccountId() : "000000000000";
+ }
+
/** Stable, account-scoped S3 key for a function's current deployment package. */
public static String codeObjectKey(LambdaFunction fn) {
- String account = fn.getAccountId() != null ? fn.getAccountId() : "000000000000";
- return "snapshots/" + account + "/" + fn.getFunctionName();
+ return "snapshots/" + ownerAccount(fn) + "/" + fn.getFunctionName();
}
/** Stable, account-scoped S3 key for a published layer version's archive. */
@@ -1723,7 +1859,7 @@ public class LambdaService implements ResourceProvider {
}
private void extractZipCodeBytes(LambdaFunction fn, byte[] zipBytes, String region) {
- Path codePath = codeStore.getCodePath(fn.getFunctionName());
+ Path codePath = codeStore.getCodePath(ownerAccount(fn), fn.getFunctionName());
try {
zipExtractor.extractTo(zipBytes, codePath);
fn.setCodeLocalPath(codePath.toAbsolutePath().normalize().toString());
@@ -1760,6 +1896,14 @@ public class LambdaService implements ResourceProvider {
// Deploy succeeded: keep the exact package so GetFunction can serve
// a real Code.Location.
storeDeploymentPackage(fn, zipBytes, region);
+ // Reclaim a directory left behind by a function created before account-scoping;
+ // codePath above is already the new location, so this is a no-op once migrated.
+ // Locked against publishVersion (see its own comment) so a version cannot be
+ // persisted, referencing this legacy path, in the window between the check below
+ // and the actual delete.
+ synchronized (lockForConcurrencyOp(fn.getFunctionArn())) {
+ reclaimLegacyCodeDirectoryIfUnused(fn.getFunctionName());
+ }
} catch (AwsException e) {
throw e;
} catch (IOException e) {
@@ -2181,9 +2325,12 @@ public class LambdaService implements ResourceProvider {
public void onS3ObjectUpdated(@Observes S3ObjectUpdatedEvent event) {
LOG.debugv("Observing S3 update: {0}/{1}", event.bucketName(), event.key());
// For simplicity, we scan all functions in the default region
- // Most local dev setups use a single region
+ // Most local dev setups use a single region.
+ // This runs on the CDI event thread with no RequestContext, so an ambient scan
+ // would only ever see the default account's partition — a function owned by any
+ // other account would silently never hot-reload from S3.
String region = regionResolver.getDefaultRegion();
- List<LambdaFunction> functions = functionStore.list(region);
+ List<LambdaFunction> functions = functionStore.listAllAccounts(region);
for (LambdaFunction fn : functions) {
if (fn.isHotReload()) {
continue;
@@ -2196,7 +2343,7 @@ public class LambdaService implements ResourceProvider {
extractZipCodeBytes(fn, obj.getData(), region);
fn.setLastModified(Instant.now().toEpochMilli());
fn.setRevisionId(UUID.randomUUID().toString());
- functionStore.save(region, fn);
+ functionStore.saveForAccount(ownerAccount(fn), region, fn);
// Push to warm workers
warmPool.pushCodeUpdate(fn);
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/zip/CodeStore.java b/src/main/java/io/github/hectorvent/floci/services/lambda/zip/CodeStore.java
index fd0a4d3e41..3f9bb7481d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/zip/CodeStore.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/zip/CodeStore.java
@@ -12,7 +12,10 @@ import java.util.Comparator;
/**
* Manages on-disk locations of extracted Lambda function code.
- * Each function gets its own directory under the configured code path.
+ * Each function gets its own directory under {@code <codePath>/<accountId>/}, mirroring
+ * the account-prefixed S3 key {@code LambdaService.codeObjectKey} uses for the same
+ * deployment package. Without the account segment two accounts' same-named functions in
+ * one region share a single extraction directory and overwrite each other's code.
*/
@ApplicationScoped
public class CodeStore {
@@ -30,18 +33,39 @@ public class CodeStore {
this.baseDir = baseDir;
}
- public Path getCodePath(String functionName) {
+ public Path getCodePath(String accountId, String functionName) {
+ return baseDir.resolve(sanitizeName(accountId)).resolve(sanitizeName(functionName));
+ }
+
+ /**
+ * The pre-account-scoped path a function's code would have extracted to before this class
+ * added an account segment. Retained so {@link #delete} and code re-extraction can reclaim a
+ * directory left behind by a function created before that migration.
+ */
+ public Path getLegacyCodePath(String functionName) {
return baseDir.resolve(sanitizeName(functionName));
}
- public void delete(String functionName) {
- Path codePath = getCodePath(functionName);
- if (!Files.exists(codePath)) {
+ public void delete(String accountId, String functionName) {
+ deleteDirectory(getCodePath(accountId, functionName), functionName);
+ }
+
+ /**
+ * Best-effort removal of a function's pre-account-scoped directory. Deliberately NOT called
+ * automatically from {@link #delete}: the pre-account-scoped layout gave every account's
+ * same-named function the exact same directory, so it is only safe to remove once the caller
+ * (see {@code LambdaService}) has confirmed no other account's function still references it.
+ */
+ public void deleteLegacy(String functionName) {
+ deleteDirectory(getLegacyCodePath(functionName), functionName);
+ }
+
+ private void deleteDirectory(Path path, String functionName) {
+ if (!Files.exists(path)) {
return;
}
- try {
- Files.walk(codePath)
- .sorted(Comparator.reverseOrder())
+ try (var walk = Files.walk(path)) {
+ walk.sorted(Comparator.reverseOrder())
.forEach(p -> {
try {
Files.delete(p);
@@ -55,16 +79,29 @@ public class CodeStore {
}
}
- public boolean exists(String functionName) {
- Path codePath = getCodePath(functionName);
- try {
- return Files.exists(codePath) && Files.list(codePath).findAny().isPresent();
+ public boolean exists(String accountId, String functionName) {
+ Path codePath = getCodePath(accountId, functionName);
+ if (!Files.exists(codePath)) {
+ return false;
+ }
+ try (var listing = Files.list(codePath)) {
+ return listing.findAny().isPresent();
} catch (IOException e) {
return false;
}
}
+ /**
+ * Replaces disallowed characters, then collapses any segment that consists entirely of dots
+ * ({@code "."}, {@code ".."}, ...) to a safe placeholder: dots alone survive the character
+ * replacement above but are special path segments that {@link Path#resolve} would otherwise
+ * follow outside {@link #baseDir}.
+ */
private String sanitizeName(String name) {
- return name.replaceAll("[^a-zA-Z0-9_\\-.]", "_");
+ String sanitized = name.replaceAll("[^a-zA-Z0-9_\\-.]", "_");
+ if (sanitized.isEmpty() || sanitized.chars().allMatch(c -> c == '.')) {
+ return "_";
+ }
+ return sanitized;
}
}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index a987947772..7f70f9ce52 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -247,8 +247,13 @@ floci:
ephemeral: false
default-memory-mb: 128
default-timeout-seconds: 3
- runtime-api-base-port: 9200
- runtime-api-max-port: 9299
+ # 500 ports, not the former 100 (9200-9299): one port is held per running Lambda
+ # container, so this is the concurrent-execution ceiling, and a multi-account LZA needs
+ # ~112 at once. See EmulatorConfig.runtimeApiBasePort for why 12000 and not a wider 9200.
+ # Keep in step with the @WithDefault there — a value set here WINS over the annotation,
+ # so changing only the default silently does nothing (the issue #2225 trap).
+ runtime-api-base-port: 12000
+ runtime-api-max-port: 12499
code-path: ./data/lambda-code
poll-interval-ms: 1000
container-idle-timeout-seconds: 300
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/port/PortAllocatorTest.java b/src/test/java/io/github/hectorvent/floci/core/common/port/PortAllocatorTest.java
index 07685f91ed..b0b6896924 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/port/PortAllocatorTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/port/PortAllocatorTest.java
@@ -51,6 +51,29 @@ class PortAllocatorTest {
assertThrows(IllegalStateException.class, allocator::allocate);
}
+ /**
+ * When the pool runs dry the exception is often the only artefact an operator ever sees —
+ * it reaches them second-hand as a CloudFormation rollback, with floci's own logs the only
+ * place the cause survives (issue #2206). "No free ports in range 9200-9299" does not say
+ * which pool ran dry or how to widen it, leaving the reader to find PortAllocator in the
+ * source to discover the knob exists. The message must carry its own diagnosis.
+ */
+ @Test
+ void exhaustionMessageNamesThePoolAndTheWideningProperty() {
+ PortAllocator allocator = new PortAllocator(9200, 9200);
+ allocator.allocate();
+
+ IllegalStateException thrown = assertThrows(IllegalStateException.class, allocator::allocate);
+ String message = thrown.getMessage();
+
+ assertTrue(message.contains("Lambda Runtime API"),
+ "message must name the pool that ran dry; got: " + message);
+ assertTrue(message.contains("floci.services.lambda.runtime-api-max-port"),
+ "message must name the property that widens the pool; got: " + message);
+ assertTrue(message.contains("9200"),
+ "message must still report the exhausted range; got: " + message);
+ }
+
@Test
void releasedPortBecomesAvailableAgain() {
PortAllocator allocator = new PortAllocator(9200, 9201);
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/port/RuntimeApiPortPoolDefaultTest.java b/src/test/java/io/github/hectorvent/floci/core/common/port/RuntimeApiPortPoolDefaultTest.java
new file mode 100644
index 0000000000..b8539fbbfb
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/port/RuntimeApiPortPoolDefaultTest.java
@@ -0,0 +1,139 @@
+package io.github.hectorvent.floci.core.common.port;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.smallrye.config.WithDefault;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Method;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The Lambda Runtime API port pool's *default* width is a capacity ceiling on concurrent Lambda
+ * executions, because one port is held for the lifetime of each running Lambda container.
+ *
+ * <p>The original default of 9200-9299 was exactly 100 ports, which cannot run a multi-account
+ * landing zone: LZA's LoggingStack alone fans out roughly 8 custom-resource Lambdas per account,
+ * so a 14-account org needs ~112 concurrently and exhausts the pool (issue #2206). Worse, the
+ * failure does not present as a capacity limit — the custom resource reports FAILED and
+ * CloudFormation rolls the stack back, so the operator sees an unrelated-looking CFN error.
+ *
+ * <p>These assertions pin the two properties that made the old default wrong, so a future edit
+ * cannot quietly reintroduce either. They read the annotation rather than booting the config,
+ * which keeps the guard fast and dependency-free.
+ */
+class RuntimeApiPortPoolDefaultTest {
+
+ /** Enough for a ~14-account landing zone (~112 concurrent) with headroom for Deploy. */
+ private static final int MIN_USABLE_POOL_WIDTH = 500;
+
+ /**
+ * The value that actually takes effect. {@code application.yml} is a config SOURCE, not a
+ * set of defaults, so any key it sets WINS over the interface's {@code @WithDefault} — the
+ * same trap that made {@code storage.mode} ignore its annotation (issue #2225). Reading only
+ * the annotation would let a widened default pass this suite while the running emulator kept
+ * the old 100-port pool, so resolve the yaml first and fall back to the annotation.
+ */
+ private static int defaultOf(String method) throws Exception {
+ Integer fromYaml = yamlValue(kebab(method));
+ return fromYaml != null ? fromYaml : annotationDefaultOf(method);
+ }
+
+ private static int annotationDefaultOf(String method) throws NoSuchMethodException {
+ Method m = EmulatorConfig.LambdaServiceConfig.class.getMethod(method);
+ WithDefault d = m.getAnnotation(WithDefault.class);
+ assertNotNull(d, method + "() must carry an explicit @WithDefault");
+ return Integer.parseInt(d.value());
+ }
+
+ /** {@code runtimeApiBasePort} -> {@code runtime-api-base-port}. */
+ private static String kebab(String method) {
+ return method.replaceAll("([a-z0-9])([A-Z])", "$1-$2").toLowerCase(java.util.Locale.ROOT);
+ }
+
+ /** The value under {@code floci.services.lambda.<key>} in application.yml, or null. */
+ private static Integer yamlValue(String key) throws Exception {
+ java.nio.file.Path yml = java.nio.file.Path.of("src/main/resources/application.yml");
+ assertTrue(java.nio.file.Files.exists(yml), "application.yml not found at " + yml.toAbsolutePath());
+ java.util.regex.Pattern p =
+ java.util.regex.Pattern.compile("^\\s*" + java.util.regex.Pattern.quote(key) + ":\\s*(\\d+)\\s*$");
+ for (String line : java.nio.file.Files.readAllLines(yml)) {
+ java.util.regex.Matcher m = p.matcher(line);
+ if (m.matches()) {
+ return Integer.valueOf(m.group(1));
+ }
+ }
+ return null;
+ }
+
+ @Test
+ void annotationDefaultAndApplicationYamlAgree() throws Exception {
+ for (String method : new String[] {"runtimeApiBasePort", "runtimeApiMaxPort"}) {
+ Integer yaml = yamlValue(kebab(method));
+ if (yaml != null) {
+ assertEquals(annotationDefaultOf(method), yaml.intValue(),
+ kebab(method) + " differs between @WithDefault and application.yml; the "
+ + "yaml wins at runtime, so the annotation would be a lie");
+ }
+ }
+ }
+
+ @Test
+ void defaultPoolIsWideEnoughForAMultiAccountLandingZone() throws Exception {
+ int base = defaultOf("runtimeApiBasePort");
+ int max = defaultOf("runtimeApiMaxPort");
+ int width = max - base + 1;
+
+ assertTrue(width >= MIN_USABLE_POOL_WIDTH,
+ "default Runtime API pool is " + width + " ports (" + base + "-" + max + "); "
+ + "a multi-account LZA needs at least " + MIN_USABLE_POOL_WIDTH
+ + " or it exhausts mid-deploy and surfaces as a CloudFormation rollback");
+ }
+
+ @Test
+ void defaultPoolDoesNotOverlapPortsFlociAlreadyUses() throws Exception {
+ int base = defaultOf("runtimeApiBasePort");
+ int max = defaultOf("runtimeApiMaxPort");
+
+ // A pool this wide stops being obvious about what it covers, so the overlaps that matter
+ // are asserted rather than reasoned about: 9200 OpenSearch, 9092 Kafka, 9644 Redpanda
+ // admin, 9400-9499 the ECS proxy pool, 4566 the emulator's own port, 6379-6399 Redis.
+ int[][] forbidden = {
+ {4566, 4566}, {6379, 6399}, {9092, 9092},
+ {9200, 9200}, {9400, 9499}, {9644, 9644},
+ };
+ for (int[] range : forbidden) {
+ boolean overlaps = base <= range[1] && range[0] <= max;
+ assertFalse(overlaps, "default Runtime API pool " + base + "-" + max
+ + " overlaps reserved ports " + range[0] + "-" + range[1]);
+ }
+ }
+
+ @Test
+ void basePortPrecedesMaxPort() throws Exception {
+ assertTrue(defaultOf("runtimeApiBasePort") < defaultOf("runtimeApiMaxPort"),
+ "base port must be below max port or the pool is empty");
+ }
+
+ @Test
+ void poolHonoursTheConfiguredWidthAtRuntime() throws Exception {
+ // The annotation is only a default; prove the allocator actually hands out the whole
+ // configured range, so widening the default genuinely raises the concurrency ceiling.
+ int base = defaultOf("runtimeApiBasePort");
+ int max = defaultOf("runtimeApiMaxPort");
+ PortAllocator allocator = new PortAllocator(base, max);
+
+ java.util.Set<Integer> handed = new java.util.HashSet<>();
+ for (int i = 0; i < MIN_USABLE_POOL_WIDTH; i++) {
+ assertTrue(handed.add(allocator.allocate()),
+ "allocator handed out a duplicate port after " + handed.size() + " allocations");
+ }
+
+ assertEquals(MIN_USABLE_POOL_WIDTH, handed.size(),
+ "allocator must yield at least " + MIN_USABLE_POOL_WIDTH
+ + " concurrent ports across the full configured range");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaAccountScopedCodeTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaAccountScopedCodeTest.java
new file mode 100644
index 0000000000..a119010762
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaAccountScopedCodeTest.java
@@ -0,0 +1,228 @@
+package io.github.hectorvent.floci.services.lambda;
+
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
+import io.github.hectorvent.floci.services.lambda.zip.CodeStore;
+import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Base64;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Two accounts owning a same-named function in the same region must not share
+ * on-disk extracted code or a PublishVersion counter. Cross-account invoke
+ * resolves a function by the ARN's own account ({@code LambdaService.resolveInvokeTarget}),
+ * so a collision here silently serves one account's code under the other's ARN.
+ */
+class LambdaAccountScopedCodeTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String ACCOUNT_A = "111111111111";
+ private static final String ACCOUNT_B = "222222222222";
+
+ @Test
+ void sameFunctionNameInTwoAccountsKeepsItsOwnCodeOnDisk(@TempDir Path baseDir) throws Exception {
+ CodeStore sharedCodeStore = new CodeStore(baseDir);
+ LambdaService svcA = serviceFor(ACCOUNT_A, sharedCodeStore);
+ LambdaService svcB = serviceFor(ACCOUNT_B, sharedCodeStore);
+
+ LambdaFunction a = svcA.createFunction(REGION, zipRequest("shared-fn", "module.exports.handler = 'A';"));
+ LambdaFunction b = svcB.createFunction(REGION, zipRequest("shared-fn", "module.exports.handler = 'B';"));
+
+ assertNotEquals(a.getCodeLocalPath(), b.getCodeLocalPath(),
+ "each account's function must extract to its own directory");
+ assertEquals("module.exports.handler = 'A';",
+ Files.readString(Path.of(a.getCodeLocalPath()).resolve("index.js")),
+ "account A's code must survive account B's create");
+ assertEquals("module.exports.handler = 'B';",
+ Files.readString(Path.of(b.getCodeLocalPath()).resolve("index.js")));
+ }
+
+ @Test
+ void deletingOneAccountsFunctionLeavesTheOthersCodeIntact(@TempDir Path baseDir) throws Exception {
+ CodeStore sharedCodeStore = new CodeStore(baseDir);
+ LambdaService svcA = serviceFor(ACCOUNT_A, sharedCodeStore);
+ LambdaService svcB = serviceFor(ACCOUNT_B, sharedCodeStore);
+
+ LambdaFunction a = svcA.createFunction(REGION, zipRequest("shared-fn", "A"));
+ svcB.createFunction(REGION, zipRequest("shared-fn", "B"));
+
+ svcB.deleteFunction(REGION, "shared-fn");
+
+ assertTrue(sharedCodeStore.exists(ACCOUNT_A, "shared-fn"),
+ "deleting B's function must not delete A's code");
+ assertEquals("A", Files.readString(Path.of(a.getCodeLocalPath()).resolve("index.js")));
+ }
+
+ @Test
+ void publishVersionCounterKeyCarriesTheOwningAccount() {
+ LambdaFunction a = functionOwnedBy(ACCOUNT_A);
+ LambdaFunction b = functionOwnedBy(ACCOUNT_B);
+
+ assertNotEquals(LambdaService.versionCounterKey(REGION, a), LambdaService.versionCounterKey(REGION, b),
+ "same-named functions in different accounts must number versions independently");
+ assertTrue(LambdaService.versionCounterKey(REGION, a).contains(ACCOUNT_A));
+ }
+
+ @Test
+ void publishVersionAdoptsACounterPersistedUnderThePreAccountKey(@TempDir Path baseDir) throws Exception {
+ // The counter map is persisted, and its whole point is that a restart must not re-issue
+ // an already-used version number. Re-keying it must therefore carry the old value
+ // forward rather than restart numbering from 1 over existing snapshots.
+ LambdaService svc = serviceFor(ACCOUNT_A, new CodeStore(baseDir));
+ svc.createFunction(REGION, zipRequest("legacy-fn", "A"));
+ svc.versionCounters().put(REGION + "::legacy-fn", 3);
+
+ LambdaFunction published = svc.publishVersion(REGION, "legacy-fn", null);
+
+ assertEquals("4", published.getVersion());
+ assertNull(svc.versionCounters().get(REGION + "::legacy-fn"),
+ "the migrated legacy entry must not linger and be adopted twice");
+ }
+
+ @Test
+ void updateFunctionCodeRemovesAPreAccountScopedLegacyDirectory(@TempDir Path baseDir) throws Exception {
+ // A function created before account-scoping left its code at baseDir/<functionName>.
+ // Updating its code after the upgrade re-extracts to the new account-scoped path but
+ // must also reclaim the old directory, or it lingers on disk forever.
+ CodeStore codeStore = new CodeStore(baseDir);
+ LambdaService svc = serviceFor(ACCOUNT_A, codeStore);
+ svc.createFunction(REGION, zipRequest("legacy-fn", "A"));
+ Path legacyPath = codeStore.getLegacyCodePath("legacy-fn");
+ Files.createDirectories(legacyPath);
+ Files.writeString(legacyPath.resolve("index.js"), "stale");
+
+ svc.updateFunctionCode(REGION, "legacy-fn",
+ Map.of("ZipFile", zipBase64("index.js", "B")));
+
+ assertFalse(Files.exists(legacyPath), "the pre-account-scoped directory must be reclaimed on update");
+ }
+
+ @Test
+ void updateFunctionCodeDoesNotDeleteALegacyDirectoryStillReferencedByAPublishedVersion(
+ @TempDir Path baseDir) throws Exception {
+ // publishVersion snapshots codeLocalPath verbatim (it must, or a version-qualified
+ // invoke launches a container with no code - see #1987). If $LATEST was still on the
+ // legacy path at publish time, that version's snapshot is now the ONLY thing keeping
+ // the legacy directory alive once $LATEST itself migrates. The unused-check only scanned
+ // $LATEST records, so it missed this and reclaimed the directory out from under the
+ // published version's own future invokes.
+ CodeStore codeStore = new CodeStore(baseDir);
+ LambdaService svc = serviceFor(ACCOUNT_A, codeStore);
+ svc.createFunction(REGION, zipRequest("legacy-version-fn", "v1"));
+
+ Path legacyPath = codeStore.getLegacyCodePath("legacy-version-fn");
+ Files.createDirectories(legacyPath);
+ Files.writeString(legacyPath.resolve("index.js"), "v1");
+ LambdaFunction latest = svc.getFunction(REGION, "legacy-version-fn");
+ latest.setCodeLocalPath(legacyPath.toAbsolutePath().normalize().toString());
+
+ LambdaFunction version = svc.publishVersion(REGION, "legacy-version-fn", null);
+ assertEquals(legacyPath.toAbsolutePath().normalize().toString(), version.getCodeLocalPath(),
+ "the published version must have snapshotted the legacy path");
+
+ svc.updateFunctionCode(REGION, "legacy-version-fn", Map.of("ZipFile", zipBase64("index.js", "v2")));
+
+ assertTrue(Files.exists(legacyPath),
+ "a legacy directory a published version still references must survive this update");
+ }
+
+ @Test
+ void updateFunctionCodeDoesNotDeleteALegacyDirectoryStillLiveForAnotherAccount(@TempDir Path baseDir) throws Exception {
+ // Before account-scoping, two accounts' same-named functions shared the exact same
+ // on-disk directory. If account B's function was never updated since the migration, its
+ // $LATEST still points at that shared legacy directory. Account A updating its own code
+ // must not delete it out from under B.
+ CodeStore codeStore = new CodeStore(baseDir);
+ LambdaFunctionStore sharedStore = new LambdaFunctionStore(AccountAwareStorageBackend.inMemory(ACCOUNT_A));
+ LambdaService svcA = new LambdaService(sharedStore, new WarmPool(), codeStore, new ZipExtractor(),
+ new RegionResolver(REGION, ACCOUNT_A));
+ svcA.createFunction(REGION, zipRequest("shared-fn", "A"));
+
+ Path legacyPath = codeStore.getLegacyCodePath("shared-fn");
+ Files.createDirectories(legacyPath);
+ Files.writeString(legacyPath.resolve("index.js"), "B-legacy");
+ LambdaFunction bFn = new LambdaFunction();
+ bFn.setFunctionName("shared-fn");
+ bFn.setAccountId(ACCOUNT_B);
+ bFn.setVersion("$LATEST");
+ bFn.setCodeLocalPath(legacyPath.toAbsolutePath().normalize().toString());
+ sharedStore.saveForAccount(ACCOUNT_B, REGION, bFn);
+
+ svcA.updateFunctionCode(REGION, "shared-fn", Map.of("ZipFile", zipBase64("index.js", "A-v2")));
+
+ assertTrue(Files.exists(legacyPath),
+ "a legacy directory another account's $LATEST still points at must survive this update");
+ }
+
+ @Test
+ void deleteFunctionDoesNotDeleteALegacyDirectoryStillLiveForAnotherAccount(@TempDir Path baseDir) throws Exception {
+ CodeStore codeStore = new CodeStore(baseDir);
+ LambdaFunctionStore sharedStore = new LambdaFunctionStore(AccountAwareStorageBackend.inMemory(ACCOUNT_A));
+ LambdaService svcA = new LambdaService(sharedStore, new WarmPool(), codeStore, new ZipExtractor(),
+ new RegionResolver(REGION, ACCOUNT_A));
+ svcA.createFunction(REGION, zipRequest("shared-fn", "A"));
+
+ Path legacyPath = codeStore.getLegacyCodePath("shared-fn");
+ Files.createDirectories(legacyPath);
+ Files.writeString(legacyPath.resolve("index.js"), "B-legacy");
+ LambdaFunction bFn = new LambdaFunction();
+ bFn.setFunctionName("shared-fn");
+ bFn.setAccountId(ACCOUNT_B);
+ bFn.setVersion("$LATEST");
+ bFn.setCodeLocalPath(legacyPath.toAbsolutePath().normalize().toString());
+ sharedStore.saveForAccount(ACCOUNT_B, REGION, bFn);
+
+ svcA.deleteFunction(REGION, "shared-fn");
+
+ assertTrue(Files.exists(legacyPath),
+ "a legacy directory another account's $LATEST still points at must survive this delete");
+ }
+
+ private LambdaFunction functionOwnedBy(String accountId) {
+ LambdaFunction fn = new LambdaFunction();
+ fn.setAccountId(accountId);
+ fn.setFunctionName("shared-fn");
+ return fn;
+ }
+
+ private LambdaService serviceFor(String accountId, CodeStore codeStore) {
+ return new LambdaService(
+ new LambdaFunctionStore(new InMemoryStorage<String, LambdaFunction>()),
+ new WarmPool(),
+ codeStore,
+ new ZipExtractor(),
+ new RegionResolver(REGION, accountId));
+ }
+
+ private Map<String, Object> zipRequest(String name, String handlerSource) throws Exception {
+ return new java.util.HashMap<>(Map.of(
+ "FunctionName", name,
+ "Runtime", "nodejs20.x",
+ "Role", "arn:aws:iam::000000000000:role/test-role",
+ "Handler", "index.handler",
+ "Code", Map.of("ZipFile", zipBase64("index.js", handlerSource))
+ ));
+ }
+
+ private String zipBase64(String entryName, String content) throws Exception {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ try (ZipOutputStream zip = new ZipOutputStream(out)) {
+ zip.putNextEntry(new ZipEntry(entryName));
+ zip.write(content.getBytes());
+ zip.closeEntry();
+ }
+ return Base64.getEncoder().encodeToString(out.toByteArray());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaAccountSettingsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaAccountSettingsIntegrationTest.java
new file mode 100644
index 0000000000..e05df8284b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaAccountSettingsIntegrationTest.java
@@ -0,0 +1,103 @@
+package io.github.hectorvent.floci.services.lambda;
+
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.Base64;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+
+/**
+ * Verifies GetAccountSettings: {@code GET /2016-08-19/account-settings/}. Account limits mirror
+ * AWS's fixed storage defaults plus the configured concurrency limit; usage reflects the caller's
+ * stored functions. Distinct account ids in the credential keep the usage assertions isolated
+ * from other Lambda tests.
+ */
+@QuarkusTest
+class LambdaAccountSettingsIntegrationTest {
+
+ private static final String SETTINGS_PATH = "/2016-08-19/account-settings/";
+
+ @Test
+ void accountSettings_emptyAccount_returnsAwsLimitsAndZeroUsage() {
+ given()
+ .header("Authorization", auth("000000000401"))
+ .when()
+ .get(SETTINGS_PATH)
+ .then()
+ .statusCode(200)
+ .body("AccountLimit.TotalCodeSize", equalTo(80530636800L))
+ .body("AccountLimit.CodeSizeUnzipped", equalTo(262144000))
+ .body("AccountLimit.CodeSizeZipped", equalTo(52428800))
+ .body("AccountLimit.ConcurrentExecutions", equalTo(1000))
+ .body("AccountLimit.UnreservedConcurrentExecutions", equalTo(1000))
+ .body("AccountUsage.TotalCodeSize", equalTo(0))
+ .body("AccountUsage.FunctionCount", equalTo(0));
+ }
+
+ @Test
+ void accountSettings_reflectsStoredFunctionsAndReservedConcurrency() {
+ String authorization = auth("000000000402");
+ int codeSize = given()
+ .contentType("application/json")
+ .header("Authorization", authorization)
+ .body("""
+ {
+ "FunctionName": "account-settings-fn",
+ "Runtime": "nodejs20.x",
+ "Role": "arn:aws:iam::000000000402:role/lambda-role",
+ "Handler": "index.handler",
+ "Code": {"ZipFile": "%s"}
+ }
+ """.formatted(zipBase64()))
+ .when()
+ .post("/2015-03-31/functions")
+ .then()
+ .statusCode(201)
+ .extract().path("CodeSize");
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", authorization)
+ .body("{\"ReservedConcurrentExecutions\": 25}")
+ .when()
+ .put("/2017-10-31/functions/account-settings-fn/concurrency")
+ .then()
+ .statusCode(200);
+
+ given()
+ .header("Authorization", authorization)
+ .when()
+ .get(SETTINGS_PATH)
+ .then()
+ .statusCode(200)
+ .body("AccountUsage.FunctionCount", equalTo(1))
+ .body("AccountUsage.TotalCodeSize", equalTo(codeSize))
+ .body("AccountLimit.ConcurrentExecutions", equalTo(1000))
+ .body("AccountLimit.UnreservedConcurrentExecutions", equalTo(975));
+ }
+
+ private static String auth(String accountId) {
+ return "AWS4-HMAC-SHA256 Credential=" + accountId + "/20260101/us-east-1/lambda/aws4_request";
+ }
+
+ private static String zipBase64() {
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ try (ZipOutputStream zip = new ZipOutputStream(out)) {
+ zip.putNextEntry(new ZipEntry("index.js"));
+ zip.write("exports.handler = async () => ({ ok: true });".getBytes());
+ zip.closeEntry();
+ }
+ return Base64.getEncoder().encodeToString(out.toByteArray());
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtilsTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtilsTest.java
index 061ef4c92d..3753fc0d10 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtilsTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtilsTest.java
@@ -24,6 +24,8 @@ class LambdaArnUtilsTest {
"arn:aws:lambda:us-east-1:000000000000:function:my-fn:prod, my-fn, prod, us-east-1",
"arn:aws:lambda:us-east-1:000000000000:function:my-fn:$LATEST, my-fn, $LATEST, us-east-1",
"arn:aws:lambda:us-east-1:000000000000:function:my_fn-1, my_fn-1, , us-east-1",
+ "my.fn.v2, my.fn.v2, , ",
+ "arn:aws:lambda:us-east-1:000000000000:function:my.fn.v2, my.fn.v2, , us-east-1",
})
void resolveAcceptsValidForms(String input, String expectedName, String expectedQualifier, String expectedRegion) {
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(input);
@@ -56,6 +58,21 @@ class LambdaArnUtilsTest {
assertEquals(400, ex.getHttpStatus());
}
+ @Test
+ void resolveRejectsNameLongerThan256Chars() {
+ String tooLong = "a".repeat(257);
+ AwsException ex = assertThrows(AwsException.class, () -> LambdaArnUtils.resolve(tooLong));
+ assertEquals("InvalidParameterValueException", ex.getErrorCode());
+ assertEquals(400, ex.getHttpStatus());
+ }
+
+ @Test
+ void resolveAccepts256CharName() {
+ String maxLen = "a".repeat(256);
+ LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(maxLen);
+ assertEquals(maxLen, ref.name());
+ }
+
@Test
void resolveRejectsNull() {
assertThrows(AwsException.class, () -> LambdaArnUtils.resolve(null));
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaFunctionStoreAccountScopeTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaFunctionStoreAccountScopeTest.java
new file mode 100644
index 0000000000..de10ff2f9f
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaFunctionStoreAccountScopeTest.java
@@ -0,0 +1,83 @@
+package io.github.hectorvent.floci.services.lambda;
+
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * The S3 sync-reload observer runs with no {@code RequestContext}, so it sees the default
+ * account's partition. It needs an all-accounts view to find the function an S3 update
+ * belongs to, and an explicit-account save to put it back where it came from.
+ */
+class LambdaFunctionStoreAccountScopeTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String DEFAULT_ACCOUNT = "000000000000";
+ private static final String OTHER_ACCOUNT = "222222222222";
+
+ @Test
+ void listAllAccountsSeesFunctionsOutsideTheAmbientPartition() {
+ LambdaFunctionStore store = accountAwareStore();
+ store.saveForAccount(OTHER_ACCOUNT, REGION, function("other-fn", OTHER_ACCOUNT));
+
+ assertTrue(store.list(REGION).isEmpty(),
+ "the ambient scan must not see another account's function");
+ List<LambdaFunction> all = store.listAllAccounts(REGION);
+ assertEquals(1, all.size());
+ assertEquals("other-fn", all.get(0).getFunctionName());
+ }
+
+ @Test
+ void listAllAccountsKeepsTheRegionAndLatestFilter() {
+ LambdaFunctionStore store = accountAwareStore();
+ store.saveForAccount(OTHER_ACCOUNT, REGION, function("latest-fn", OTHER_ACCOUNT));
+ LambdaFunction published = function("latest-fn", OTHER_ACCOUNT);
+ published.setVersion("1");
+ store.saveForAccount(OTHER_ACCOUNT, REGION, published);
+ store.saveForAccount(OTHER_ACCOUNT, "eu-west-1", function("elsewhere-fn", OTHER_ACCOUNT));
+
+ List<LambdaFunction> all = store.listAllAccounts(REGION);
+
+ assertEquals(1, all.size(), "published versions and other regions must stay excluded");
+ assertEquals("$LATEST", all.get(0).getVersion());
+ }
+
+ @Test
+ void saveForAccountWritesIntoTheOwningPartitionNotTheAmbientOne() {
+ LambdaFunctionStore store = accountAwareStore();
+ store.saveForAccount(OTHER_ACCOUNT, REGION, function("owned-fn", OTHER_ACCOUNT));
+
+ assertTrue(store.getForAccount(OTHER_ACCOUNT, REGION, "owned-fn").isPresent());
+ assertTrue(store.get(REGION, "owned-fn").isEmpty(),
+ "the ambient (default-account) partition must stay clean");
+ }
+
+ @Test
+ void listAllSeesEveryAccountSoRestartRehydrationCountsThemAll() {
+ // The reserved-concurrency pool is per region and shared across accounts, so the
+ // startup rehydration that feeds it has to see every account's functions or a restart
+ // silently frees capacity that steady-state PutFunctionConcurrency had accounted for.
+ LambdaFunctionStore store = accountAwareStore();
+ store.saveForAccount(DEFAULT_ACCOUNT, REGION, function("default-fn", DEFAULT_ACCOUNT));
+ store.saveForAccount(OTHER_ACCOUNT, REGION, function("other-fn", OTHER_ACCOUNT));
+
+ assertEquals(2, store.listAll().size());
+ }
+
+ private LambdaFunctionStore accountAwareStore() {
+ return new LambdaFunctionStore(AccountAwareStorageBackend.<LambdaFunction>inMemory(DEFAULT_ACCOUNT));
+ }
+
+ private LambdaFunction function(String name, String accountId) {
+ LambdaFunction fn = new LambdaFunction();
+ fn.setFunctionName(name);
+ fn.setAccountId(accountId);
+ fn.setVersion("$LATEST");
+ fn.setFunctionArn("arn:aws:lambda:" + REGION + ":" + accountId + ":function:" + name);
+ return fn;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaListFunctionsByCodeSigningConfigConsumerTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaListFunctionsByCodeSigningConfigConsumerTest.java
new file mode 100644
index 0000000000..1c44f02014
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaListFunctionsByCodeSigningConfigConsumerTest.java
@@ -0,0 +1,114 @@
+package io.github.hectorvent.floci.services.lambda;
+
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+
+/**
+ * Wire-level test for {@code ListFunctionsByCodeSigningConfig}.
+ *
+ * <p>New class, not appended to {@code LambdaCodeSigningIntegrationTest} (which
+ * uses ordered setUp/tearDown fixtures this operation doesn't need), so
+ * falsifiability isolates per operation (CS-001).</p>
+ *
+ * <p>The identifier is validated even though Floci models no code-signing
+ * configs: botocore models both {@code InvalidParameterValueException} and
+ * {@code ResourceNotFoundException} for this operation, and the only resource
+ * the ARN can name is a code-signing config. Since there is no
+ * CreateCodeSigningConfig / PutFunctionCodeSigningConfig in this codebase, every
+ * well-formed ARN necessarily names a config that does not exist, so the modeled
+ * 404 — not a silent empty list — is the honest answer.</p>
+ */
+@QuarkusTest
+class LambdaListFunctionsByCodeSigningConfigConsumerTest {
+
+ /** Matches botocore's CodeSigningConfigArn pattern: csc- plus 17 lowercase alphanumerics. */
+ private static final String WELL_FORMED_ARN =
+ "arn:aws:lambda:us-east-1:000000000000:code-signing-config:csc-0f6c334ab1234567c";
+
+ private static String path(String arn) {
+ return "/2020-04-22/code-signing-configs/" + arn + "/functions";
+ }
+
+ @Test
+ void wellFormedButUnknownConfig_returnsResourceNotFound() {
+ given()
+ .when()
+ .get(path(WELL_FORMED_ARN))
+ .then()
+ .statusCode(404)
+ .body("__type", equalTo("ResourceNotFoundException"));
+ }
+
+ /**
+ * The model's region alternation is {@code (eusc-)?[a-z]{2}((-gov)|(-iso([a-z]?)))?-[a-z]+-\d},
+ * which admits the newer isolated partitions (iso-e/iso-f) and the European sovereign
+ * cloud. A well-formed ARN in one of those must reach the modeled 404, not be rejected
+ * as malformed.
+ */
+ @Test
+ void wellFormedIsolatedPartitionArn_returnsResourceNotFound() {
+ given()
+ .when()
+ .get(path("arn:aws-iso-e:lambda:us-isoe-east-1:000000000000:"
+ + "code-signing-config:csc-0f6c334ab1234567c"))
+ .then()
+ .statusCode(404)
+ .body("__type", equalTo("ResourceNotFoundException"));
+ }
+
+ @Test
+ void malformedArn_returnsInvalidParameterValue() {
+ given()
+ .when()
+ .get(path("not-an-arn"))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidParameterValueException"));
+ }
+
+ @Test
+ void shortSuffixArn_returnsInvalidParameterValue() {
+ given()
+ .when()
+ .get(path("arn:aws:lambda:us-east-1:000000000000:code-signing-config:csc-0f6c334ab"))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidParameterValueException"));
+ }
+
+ @Test
+ void maxItemsBelowRange_returnsInvalidParameterValue() {
+ given()
+ .queryParam("MaxItems", 0)
+ .when()
+ .get(path(WELL_FORMED_ARN))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidParameterValueException"));
+ }
+
+ @Test
+ void maxItemsAboveRange_returnsInvalidParameterValue() {
+ given()
+ .queryParam("MaxItems", 10001)
+ .when()
+ .get(path(WELL_FORMED_ARN))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidParameterValueException"));
+ }
+
+ @Test
+ void nonNumericMaxItems_returnsInvalidParameterValue() {
+ given()
+ .queryParam("MaxItems", "many")
+ .when()
+ .get(path(WELL_FORMED_ARN))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidParameterValueException"));
+ }
+}
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 b63a8349ba..1f86e794fd 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
@@ -222,6 +222,68 @@ class LambdaServiceTest {
assertEquals(vpcConfig(), service.getFunction(REGION, "update-efs-vpc-function").getVpcConfig());
}
+ @Test
+ void updateFunctionConfigurationRejectsMalformedRoleArn() {
+ service.createFunction(REGION, baseRequest("update-role-function"));
+
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.updateFunctionConfiguration(REGION, "update-role-function",
+ Map.of("Role", "not-an-arn")));
+
+ assertEquals("InvalidParameterValueException", error.getErrorCode());
+ assertEquals("arn:aws:iam::000000000000:role/test-role",
+ service.getFunction(REGION, "update-role-function").getRole());
+ }
+
+ @Test
+ void updateFunctionConfigurationAcceptsValidRoleArn() {
+ service.createFunction(REGION, baseRequest("update-role-valid-function"));
+
+ LambdaFunction updated = service.updateFunctionConfiguration(REGION, "update-role-valid-function",
+ Map.of("Role", "arn:aws:iam::000000000000:role/new-role"));
+
+ assertEquals("arn:aws:iam::000000000000:role/new-role", updated.getRole());
+ }
+
+ @Test
+ void updateFunctionConfigurationRejectsHandlerWithWhitespace() {
+ service.createFunction(REGION, baseRequest("update-handler-function"));
+
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.updateFunctionConfiguration(REGION, "update-handler-function",
+ Map.of("Handler", "index handler")));
+
+ assertEquals("InvalidParameterValueException", error.getErrorCode());
+ assertEquals("index.handler",
+ service.getFunction(REGION, "update-handler-function").getHandler());
+ }
+
+ @Test
+ void updateFunctionConfigurationRejectsHandlerLongerThan128Chars() {
+ service.createFunction(REGION, baseRequest("update-handler-length-function"));
+
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.updateFunctionConfiguration(REGION, "update-handler-length-function",
+ Map.of("Handler", "h".repeat(129))));
+
+ assertEquals("InvalidParameterValueException", error.getErrorCode());
+ }
+
+ @Test
+ void updateFunctionConfigurationRejectsExplicitNullHandler() {
+ service.createFunction(REGION, baseRequest("update-handler-null-function"));
+ Map<String, Object> request = new java.util.HashMap<>();
+ request.put("Handler", null);
+
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.updateFunctionConfiguration(REGION, "update-handler-null-function", request));
+
+ assertEquals("InvalidParameterValueException", error.getErrorCode());
+ assertEquals("index.handler",
+ service.getFunction(REGION, "update-handler-null-function").getHandler(),
+ "an explicit null must not silently clear the handler");
+ }
+
@Test
void createFunctionFailsWhenMissingFunctionName() {
Map<String, Object> req = baseRequest("x");
@@ -885,4 +947,49 @@ class LambdaServiceTest {
assertEquals(expectedStatementIds, actualStatementIds);
}
+
+ @Test
+ void publishVersionWaitsForAConcurrentHolderOfTheFunctionsConcurrencyLock() throws Exception {
+ // publishVersion reads codeLocalPath and persists a snapshot of it with no
+ // synchronization against extractZipCodeBytes's own reclaim-the-legacy-directory
+ // decision (which runs under this same per-function lock, e.g. from deleteFunction).
+ // Without publishVersion also taking that lock, a version could be published in the
+ // narrow window between that decision and the actual delete, persisting a snapshot
+ // that references a directory which is about to be removed as "unused". Proving
+ // publishVersion blocks on this lock closes that window regardless of the exact
+ // interleaving, rather than relying on timing to catch it in the act.
+ LambdaFunction fn = service.createFunction(REGION, baseRequest("lock-race-fn"));
+ Object lock = service.lockForConcurrencyOp(fn.getFunctionArn());
+
+ ExecutorService pool = Executors.newFixedThreadPool(1);
+ CountDownLatch acquired = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ Thread holder = new Thread(() -> {
+ synchronized (lock) {
+ acquired.countDown();
+ try {
+ release.await();
+ } catch (InterruptedException ignored) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ });
+ try {
+ holder.start();
+ assertTrue(acquired.await(2, java.util.concurrent.TimeUnit.SECONDS));
+
+ Future<LambdaFunction> publishFuture = pool.submit(
+ () -> service.publishVersion(REGION, "lock-race-fn", null));
+ assertThrows(java.util.concurrent.TimeoutException.class,
+ () -> publishFuture.get(200, java.util.concurrent.TimeUnit.MILLISECONDS),
+ "publishVersion must block while another operation holds this function's lock");
+
+ release.countDown();
+ holder.join();
+ assertNotNull(publishFuture.get(2, java.util.concurrent.TimeUnit.SECONDS));
+ } finally {
+ release.countDown();
+ pool.shutdownNow();
+ }
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/zip/CodeStoreTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/zip/CodeStoreTest.java
new file mode 100644
index 0000000000..9513a73e85
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/zip/CodeStoreTest.java
@@ -0,0 +1,110 @@
+package io.github.hectorvent.floci.services.lambda.zip;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class CodeStoreTest {
+
+ private static final String ACCOUNT_A = "111111111111";
+ private static final String ACCOUNT_B = "222222222222";
+
+ @Test
+ void sameFunctionNameInTwoAccountsResolvesToDistinctDirectories(@TempDir Path baseDir) {
+ CodeStore store = new CodeStore(baseDir);
+
+ Path a = store.getCodePath(ACCOUNT_A, "shared-name");
+ Path b = store.getCodePath(ACCOUNT_B, "shared-name");
+
+ assertNotEquals(a, b, "two accounts must not share one on-disk extraction directory");
+ assertTrue(a.startsWith(baseDir.resolve(ACCOUNT_A)));
+ assertTrue(b.startsWith(baseDir.resolve(ACCOUNT_B)));
+ }
+
+ @Test
+ void deleteRemovesOnlyTheOwningAccountsCode(@TempDir Path baseDir) throws IOException {
+ CodeStore store = new CodeStore(baseDir);
+ writeHandler(store.getCodePath(ACCOUNT_A, "shared-name"), "a");
+ writeHandler(store.getCodePath(ACCOUNT_B, "shared-name"), "b");
+
+ store.delete(ACCOUNT_B, "shared-name");
+
+ assertTrue(store.exists(ACCOUNT_A, "shared-name"), "deleting B's code must not touch A's");
+ assertFalse(store.exists(ACCOUNT_B, "shared-name"));
+ assertEquals("a", Files.readString(store.getCodePath(ACCOUNT_A, "shared-name").resolve("index.js")));
+ }
+
+ @Test
+ void accountSegmentIsSanitizedLikeTheFunctionName(@TempDir Path baseDir) {
+ CodeStore store = new CodeStore(baseDir);
+
+ Path traversal = store.getCodePath("../../etc", "fn");
+
+ assertTrue(traversal.normalize().startsWith(baseDir.normalize()),
+ "a hostile account segment must not escape the base directory");
+ }
+
+ @Test
+ void bareDotDotAccountSegmentCannotEscapeTheBaseDirectory(@TempDir Path baseDir) {
+ // "../../etc" contains "/", which sanitizeName replaces with "_", neutralizing it as a
+ // single segment. A segment that is EXACTLY ".." consists entirely of otherwise-allowed
+ // characters (dots), so it survives that replacement untouched and still resolves to the
+ // parent directory once handed to Path.resolve.
+ CodeStore store = new CodeStore(baseDir);
+
+ Path traversal = store.getCodePath("..", "fn");
+
+ assertTrue(traversal.normalize().startsWith(baseDir.normalize()),
+ "a bare '..' account segment must not escape the base directory");
+ }
+
+ @Test
+ void bareDotFunctionSegmentCannotResolveToTheAccountDirectoryItself(@TempDir Path baseDir) {
+ CodeStore store = new CodeStore(baseDir);
+
+ Path traversal = store.getCodePath(ACCOUNT_A, ".");
+
+ assertTrue(traversal.normalize().startsWith(baseDir.normalize()));
+ assertNotEquals(baseDir.resolve(ACCOUNT_A).normalize(), traversal.normalize(),
+ "a bare '.' function segment must not collapse to the account directory itself");
+ }
+
+ @Test
+ void deleteDoesNotTouchAPreAccountScopedLegacyDirectory(@TempDir Path baseDir) throws IOException {
+ // The pre-account-scoped layout gave every account's same-named function the exact same
+ // directory, so CodeStore itself cannot safely know whether another account's function
+ // still depends on it. That decision belongs to the caller (LambdaService, which can
+ // check every account's persisted functions) via the separate deleteLegacy() below -
+ // delete() must only ever touch its own account-scoped path.
+ CodeStore store = new CodeStore(baseDir);
+ Path legacyPath = baseDir.resolve("legacy-fn");
+ writeHandler(legacyPath, "legacy");
+ writeHandler(store.getCodePath(ACCOUNT_A, "legacy-fn"), "current");
+
+ store.delete(ACCOUNT_A, "legacy-fn");
+
+ assertTrue(Files.exists(legacyPath), "delete() must not unilaterally remove the legacy directory");
+ assertFalse(store.exists(ACCOUNT_A, "legacy-fn"));
+ }
+
+ @Test
+ void deleteLegacyRemovesThePreAccountScopedDirectory(@TempDir Path baseDir) throws IOException {
+ CodeStore store = new CodeStore(baseDir);
+ Path legacyPath = store.getLegacyCodePath("legacy-fn");
+ writeHandler(legacyPath, "legacy");
+
+ store.deleteLegacy("legacy-fn");
+
+ assertFalse(Files.exists(legacyPath));
+ }
+
+ private void writeHandler(Path codePath, String content) throws IOException {
+ Files.createDirectories(codePath);
+ Files.writeString(codePath.resolve("index.js"), content);
+ }
+}