Skip to content

Latest commit

 

History

History
170 lines (132 loc) · 40.6 KB

spec.md

File metadata and controls

170 lines (132 loc) · 40.6 KB

loch lambda-runtime — specification v1 (draft 3, 2026-11-06)

Draft 3 integrates two reviews: security ([sec]) and AWS compatibility ([aws], checked against the AWS docs, the botocore model, the RIE at commit d71cae7 and the Node/Python RICs read in the images; copies in scratchpad/review-ric/ and scratchpad/review-src/). Items marked (unverified) match the RIE formatter but were not seen on a live AWS response: clients must match on errorType, not on messages.

Canonical spec for the loch/lambda-runtime project. Context: host-panel-api/docs/design/services-decisions.md §20 (functions module of Loch.sh Panel), spike results in scratchpad/fn-spike/.

Product constraints

  • Main principle: open-source infrastructure, no vendor lock-in, based on Docker. The binary knows neither the panel nor loch: it implements AWS's public protocols and is usable standalone.
  • AWS Lambda compatible with minimal adjustments: existing Lambda functions and Lambda container images run almost unchanged (Runtime API 2018-06-01, AWS_LAMBDA_* variables, AWS base images, AWS event formats, AWS Invoke API).
  • Go (latest stable), Apache-2.0 (LICENSE, NOTICE), up-to-date dependencies, stdlib preferred. Code, README, messages in English.

Why

The Runtime Interface Emulator (RIE) bundled in AWS base images crashes on two overlapping invocations (ReserveFailed: AlreadyReserved then nil pointer panic in rapidcore/server.go:666, exit 2, every in-flight request lost; upstream v1.35 too). It also invokes the function on any HTTP method, answers 200 on timeouts and exceptions without a reliable marker, and silently truncates bodies over 6 MiB. The RIE (Apache-2.0) is a behaviour reference; its code is not copied.

Deliverable

  • Static Go binary loch-lambda-runtime (name to confirm), CGO_ENABLED=0, linux/amd64 and linux/arm64.
  • Subcommands: (default) run, health, version, invoke (see "Local invoke").
  • [sec] Release hygiene: reproducible build (-trimpath, CGO_ENABLED=0, pinned toolchain, -buildid=), binaries + SHA256SUMS with a detached signature (minisign or cosign keyless; public key/identity published in the README and embedded in Loch.sh Panel), SBOM per release. The trust root on the panel side is the panel build (embedded hash table and public key), never a bare SHA256SUMS.

Process model (the binary is PID 1, the container entrypoint)

  • Command line: loch-lambda-runtime [flags] -- <original ENTRYPOINT...> <original CMD...>. Shortcut: a single argument without -- (index.handler) means /lambda-entrypoint.sh index.handler. The panel copies the image's ENTRYPOINT/CMD (docker image inspect), so any Lambda image works: the AWS base images (nodejs, python, provided.al2023, java, dotnet, ruby share ENTRYPOINT ["/lambda-entrypoint.sh"], WORKDIR /var/task) and images using awslambdaric / aws-lambda-ric as entrypoint.
  • [aws] /lambda-entrypoint.sh exits 142 unless it gets exactly one argument, and the image CMD is null: the handler must always be supplied. The child runs with Dir = the image WORKDIR (by default the runtime's own working directory, which Docker sets to the image WORKDIR, /var/task in the AWS images; flag --workdir / LOCH_RUNTIME_WORKDIR): relative entrypoints such as ./main on provided.al2023 resolve against it.
  • Compose example: entrypoint: ["/loch/lambda-runtime"], command: ["--", "/lambda-entrypoint.sh", "index.handler"], binary mounted read-only at /loch/lambda-runtime (not /opt: Lambda layers; the bootstraps put /opt/nodejs, /opt/python, /opt/lib on their search paths).
  • Starts the Runtime API on 127.0.0.1:9001 (loopback only), then runs the child. Verified in Node 22 and Python 3.13: /lambda-entrypoint.sh exports _HANDLER="$1", execs the RIE when AWS_LAMBDA_RUNTIME_API is empty, /var/runtime/bootstrap otherwise.
  • [aws] Environment of the child (the rest is passed through unchanged):
    • always forced: AWS_LAMBDA_RUNTIME_API=127.0.0.1:9001 (IPv4 host:port: the Node RIC splits on :), overriding any image or user value;
    • always removed, with a warning: AWS_LAMBDA_MAX_CONCURRENCY (it switches the Node bootstrap to /var/runtime/mc/index.mjs, Python to LambdaMultiConcurrentRuntimeClient, and contradicts one invocation in flight);
    • always removed, silently: every LOCH_RUNTIME_* variable (the runtime's own settings, which locate the Invoke credentials);
    • set when absent: AWS_LAMBDA_FUNCTION_NAME (default function), AWS_LAMBDA_FUNCTION_VERSION=$LATEST, AWS_LAMBDA_FUNCTION_MEMORY_SIZE, AWS_LAMBDA_LOG_GROUP_NAME=/aws/lambda/<name>, AWS_LAMBDA_LOG_STREAM_NAME=YYYY/MM/DD/[$LATEST]<32 hex>, AWS_REGION (default us-east-1), AWS_DEFAULT_REGION (= region), AWS_LAMBDA_INITIALIZATION_TYPE=on-demand, AWS_XRAY_CONTEXT_MISSING=LOG_ERROR, LAMBDA_TASK_ROOT=/var/task, LAMBDA_RUNTIME_DIR=/var/runtime;
    • never set: AWS_EXECUTION_ENV (the AWS bootstraps export it) and credentials: the runtime never invents AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_SESSION_TOKEN, they come from the caller's environment (the panel's secrets).
  • AWS_LAMBDA_FUNCTION_MEMORY_SIZE absent: derived from /sys/fs/cgroup/memory.max (cgroup v2) and logged; max (no limit) → 3008, as the RIE (the Node bootstrap derives --max-old-space-size from it: 231 for 256).
  • AWS_LAMBDA_FUNCTION_TIMEOUT (seconds, default 300 like the RIE) is an RIE convention, not a documented Lambda variable: kept, and documented as such.
  • PID 1 duties: reap zombies, child in its own process group, child started with oom_score_adj=1000 (no privilege needed) so the kernel OOM-kills the bootstrap rather than PID 1. [aws] SIGTERM: stop accepting (queued requests get 503 + Retry-After), let the running invocation finish within LOCH_RUNTIME_SHUTDOWN_GRACE, then SIGTERM the group, then SIGKILL after ~500 ms. LOCH_RUNTIME_SHUTDOWN_GRACE must be shorter than the compose stop_grace_period (the panel sets both).
  • Init at startup (not lazily), so health reflects reality. [aws] As on Lambda, an init longer than LOCH_RUNTIME_INIT_TIMEOUT (10 s) is not fatal: init keeps running and its time is charged to the first invocation's timeout ("suppressed init"); if that expires the answer is Sandbox.Timedout, not Runtime.InitError. A posted /init/error (the RICs then exit: Node 128/129, Python 1) → the invocations that were waiting get that error; re-init with capped backoff; a crash loop keeps error in health (Docker unhealthy) and is counted in the metrics.
  • [aws] An exit while idle (between invocations) → re-init before the next next, not an error state.

Invocation API (0.0.0.0:8080), AWS Invoke compatible

  • POST /2015-03-31/functions/{name}/invocations. [aws] {name} (URL-decoded) = function, AWS_LAMBDA_FUNCTION_NAME, <name>:$LATEST, or its ARN, full (arn:aws:lambda:<AWS_REGION>:000000000000:function:<name>, partition, region and account checked) or partial (000000000000:function:<name>); ?Qualifier= absent or $LATEST; anything else → 404 ResourceNotFoundException. Same path as the RIE, so aws lambda invoke --endpoint-url, SAM and SDKs work. Any other method → 405, never invokes.
  • One endpoint for every network caller: other sites or functions on the function's private networks (SDK with endpoint-url), later the Loch S3 webhook. The panel uses "Local invoke".
  • [sec] Authentication is required for network callers unless LOCH_RUNTIME_AUTH=off (standalone/dev only, warning at startup). Private networks are not an access control (any container can join by name), and an unauthenticated caller could forge an S3 event and make the function use its own credentials on another object (confused deputy). Errors in the AWS shape below (401 missing, 403 wrong).
  • Threat model of the credentials. The function's code runs under the runtime's uid, in the same container. PID 1 is non-dumpable (PR_SET_DUMPABLE=0, the first thing main does, for every subcommand) and removes the credential variables from its own environment. Processes started with docker exec (health, invoke) inherit the container's environment and also call PR_SET_DUMPABLE=0 first, but the Go runtime starts before main: a function scanning /proc can open their /proc/<pid>/environ within those few milliseconds, and the open descriptor stays readable afterwards (the access check is made at open). A shell-form healthcheck (CMD-SHELL) leaves a dumpable /bin/sh with the full environment: use the exec form (["CMD", "/loch/lambda-runtime", "health"]). Without CAP_SETUID the uids cannot be separated. Hence: no usable secret in the container.
    • Bearer token, stored as its SHA-256 (LOCH_RUNTIME_TOKEN_SHA256, 64 hex, or LOCH_RUNTIME_TOKEN_SHA256_FILE): the runtime compares the SHA-256 of the presented token in constant time; the token itself never enters the container, only the panel knows it (shown once, given to the callers). This is what the panel uses. A plain LOCH_RUNTIME_TOKEN (or LOCH_RUNTIME_TOKEN_FILE) is accepted for standalone use, but the function can read it through the docker exec processes. Exactly one bearer source (configuration error otherwise). Checked entirely before the body is read.
    • SigV4 is optional, off until LOCH_RUNTIME_ACCESS_KEY (or _FILE) is set: HMAC needs the secret itself, so the function can read its own SigV4 secret. That only lets it invoke itself, which it can already do (loopback); the secret must never be presented as protected from the function's code. The panel enables it per function, only for AWS SDK callers.
    • The loopback needs no credential: a request from 127.0.0.1 or ::1, inside the container's network namespace, can only come from the function itself or from docker exec processes; the function gains nothing by invoking itself. The invoke and health subcommands therefore use no credential. The global caps still apply. Never run with --network host: the loopback exemption assumes the container has its own network namespace (with the host's, every local process of the host would invoke the function and read its metrics without a credential). Loch.sh Panel refuses it (host, container and none network modes).
  • SigV4 details (service lambda, any region), so AWS SDK callers with endpoint-url work unchanged. Two phases, because the AWS SDKs for Lambda do not send X-Amz-Content-Sha256 while the signature covers the payload hash:
    • before the body: format, access key id (constant-time compare of hashes), credential scope (service lambda, aws4_request), signed X-Amz-Date (or Date) within ±5 min and matching the scope date, SignedHeaders sorted and including host and the date header; with a signed X-Amz-Content-Sha256, the signature itself, and the request is authenticated from then on (only the body's integrity is left); UNSIGNED-PAYLOAD refused;
    • after the body: the signature over the body hash (or the body against X-Amz-Content-Sha256), compared in constant time. Without that header, the request is unverified until then: its reservation comes from a separate budget (bytes: a quarter of LOCH_RUNTIME_QUEUE_BYTES, at least one maximum payload, and one maximum payload per source IP; count: at most max(1, LOCH_RUNTIME_QUEUE_SIZE/4) unverified requests, and max(1, that/4) per source IP, so that clients behind a NAT or a proxy can upload several at once), it takes no queue slot until verified, then enters the queue like any request (429 if full: its body was sent for nothing, an accepted cost), and its body must arrive within 5 s + size / 4 MiB/s, else 408. A caller holding only the access key id, which travels in clear in Authorization, cannot fill the queue with bodies that are never sent or never verify: it can still occupy the unverified budget (one request per IP and max(1, LOCH_RUNTIME_QUEUE_SIZE/4) in all with the defaults, each for at most 5 s + size / 4 MiB/s), which delays only the callers without a payload hash header (429, retried by the AWS SDKs). Accepted trade-off: with the defaults, one IP uploads one such request at a time.
    • As on AWS, every x-amz-* header of the request (X-Amz-Log-Type, X-Amz-Client-Context, X-Amz-Tenant-Id, …) and Content-Type must be signed. X-Amzn-Trace-Id is not (the SDKs never sign it): a replay may change the trace id, whose format is validated. A DryRun is answered only once fully authenticated, its body included.
    • Errors as on AWS: an unknown access key id → UnrecognizedClientException, a wrong signature → InvalidSignatureException. The access key id is generated at random by the panel (20 uppercase letters and digits) and kept private, so a third party fails in phase 1.
  • Replay: a signed request can be replayed within the ±5 min skew, and HTTP is in clear text: the Invoke listener must only be exposed on private networks (the panel uses internal networks only). No nonce cache.
  • [sec] Browser requests are refused (CSRF, DNS rebinding): a web page can make a browser POST a "simple" text/plain request to a reachable Invoke API (a published 127.0.0.1 port in local development, for instance) without a CORS preflight, and DNS rebinding makes the request same-origin. So the Invoke API and /_loch/metrics answer 403 AccessDeniedException (Connection: close, no CORS header, the message does not name the opt-out) to any request carrying Origin, Sec-Fetch-Site, Sec-Fetch-Dest or Sec-Fetch-User, whatever the value: modern browsers send Origin on every POST, same-origin included (null from a file:// page), and Sec-Fetch-Site/Sec-Fetch-Dest to trustworthy origins (HTTPS, localhost, 127.0.0.1); the AWS SDKs, the AWS CLI, curl, Deno and Python send none of them. Sec-Fetch-Mode alone is accepted: Node's fetch (undici) sends Sec-Fetch-Mode: cors by itself (measured, Node 26). Checked after the method, before the per-IP cap, the authentication and the body, whatever the authentication setting, loopback included; not counted as an authentication failure, logged at most once per minute and per source IP. /_loch/health is not filtered (probes, no invocation). LOCH_RUNTIME_ALLOW_BROWSER=true accepts browser requests. A reverse proxy that forwards a browser's Origin to the function is refused too, by design: strip the header at the proxy, or use the opt-out. No Host allow-list: invocations are POSTs, which carry Origin, rebinding included, and callers on the function's networks use its service name. Residual, with authentication off only: a same-origin GET through DNS rebinding to a plain-HTTP name carries none of these headers, so any browser could read /_loch/metrics that way (counters, no invocation); legacy browsers (IE, Edge Legacy) did not send Origin on form POSTs.
  • Every authentication failure: AWS-shaped 401/403, Connection: close, counted in loch_lambda_auth_failures_total, logged at most once per source IP and per minute.
  • Credential sources: environment variables are read once at startup, then removed from the runtime's environment; the *_FILE variants (regular files only, ≤ 4 KiB) are re-read on SIGHUP (rotate by renaming a complete new file over the old one). [sec] The function runs under the runtime's uid and can send it SIGHUP, so a credential file it could change would let it install its own credential. The file and every directory above it, up to /, along the path and along the path its symbolic links lead to, must be out of the runtime's reach (the directories holding the intermediate links of a chain are not checked): on a read-only file system (a :ro mount, the read-only rootfs), or owned by another uid and not writable by the runtime (access(2); any unexpected error refuses). An element owned by the runtime's uid on a writable file system is refused whatever its mode: its owner can chmod it back. A world-writable file is refused, and so is any element in a directory writable by the runtime, sticky or not (/tmp). Run as uid 10001: as root, every element belongs to the runtime's user, so the whole path, rootfs included, must be read-only. Mount the credential files read-only (Docker secrets, or a :ro bind mount). The file is opened with O_NONBLOCK|O_NOCTTY and its type is checked on the descriptor (a FIFO or a device swapped in is refused, never waited on), then the path is checked to still name the opened file. A refused file is a configuration error at startup; on reload it is logged and the credentials in force are kept. A reload that fails keeps the credentials in force: replacing a file with an invalid credential revokes nothing; to revoke, restart with new credentials. Values are never logged.
  • /_loch/health stays open; /_loch/metrics and X-Amz-Log-Type: Tail require the credential (with SigV4, a GET /_loch/metrics is signed over an empty body). /_loch/metrics is under the same per-IP cap as invocations.
  • [sec] HTTP server limits: ReadHeaderTimeout 5 s, IdleTimeout 5 s (an idle keep-alive connection holds a slot of the cap), MaxHeaderBytes 32 KiB, body read deadline re-armed on progress (5 s between reads at most) and bounded by 5 s + size / 1 MiB/s (anti-slowloris), else 408 RequestTimeoutException and the connection is closed; every error answered to a request with a body closes the connection (the body may be unread, and the HTTP server would wait for it before answering), connection cap LOCH_RUNTIME_MAX_CONNS (default 8 × (LOCH_RUNTIME_QUEUE_SIZE + 1), 136 with the default queue, at most 768, under the usual 1024 open files with room for the runtime's other descriptors; RLIMIT_NOFILE is per process, the function has its own; a warning at startup when the runtime's RLIMIT_NOFILE < LOCH_RUNTIME_MAX_CONNS + 256) and min(LOCH_RUNTIME_MAX_CONNS, max(4, LOCH_RUNTIME_MAX_CONNS/8)) open connections per source IP (17 by default; with LOCH_RUNTIME_MAX_CONNS ≥ 32, it takes 8 source addresses to hold every slot with connections that never send their headers, fewer below; a source IP is a full address, so an IPv6 /64 counts as many: the Invoke listener stays on private IPv4 networks; beyond: an AWS-shaped 429 written before closing). Requests in flight (being read, queued or running) are capped per source IP at LOCH_RUNTIME_QUEUE_SIZE + 1, so one caller can fill the queue but not more (429 + Connection: close). As each request needs a connection, this holds when LOCH_RUNTIME_MAX_CONNS ≥ 8 × (LOCH_RUNTIME_QUEUE_SIZE + 1), as by default up to LOCH_RUNTIME_QUEUE_SIZE 95; beyond, or with an explicit lower value, one IP has at most LOCH_RUNTIME_MAX_CONNS/8 requests in flight. SigV4 requests without a payload hash header are further capped while unverified (above). Memory: each connection costs at most about 40 KiB (32 KiB of headers, buffers and a goroutine), counted in the function's cgroup, which the runtime shares: about 5.5 MiB for 136 connections (about 4 % of a 128 MB function in the worst case), about 30 MiB for 768. Loopback callers are exempt from the per-IP caps (docker exec … invoke and the healthcheck are inside the container), still bound by the global cap. /_loch/health is also served alone on a loopback listener LOCH_RUNTIME_HEALTH_ADDR (default 127.0.0.1:8081, 4 connections), which the health subcommand uses, so the healthcheck never competes with Invoke clients.
  • Body: raw event, limit LOCH_RUNTIME_MAX_PAYLOAD (6 MiB). Over → 413 RequestTooLargeException [aws], never a truncated body; a Content-Length over the limit is refused before reading; chunked bodies are counted. Empty body → {} is NOT invented: it is passed as is (both RICs then fail with an unmarshal error, which is the function's answer) (real Lambda behaviour unverified).
  • Headers:
    • X-Amz-Invocation-Type: RequestResponse (default), DryRun → 204, Event → 400 InvalidParameterValueException in v1 (202 on real Lambda: a stated deviation);
    • X-Amz-Client-Context [aws]: base64, ≤ 3,583 bytes, decoded and checked to be a JSON object (else 400 InvalidRequestContentException), relayed decoded as Lambda-Runtime-Client-Context;
    • X-Amz-Log-Type: Tail → X-Amz-Log-Result = base64 of the last 4096 bytes of this invocation's logs, START to REPORT included;
    • the request id is always generated by the runtime, as on Lambda (a caller-chosen id would let two callers blur the log correlation); callers correlate with the returned x-amzn-RequestId. X-Amzn-Trace-Id, when valid, becomes the trace id.
  • [aws] Errors of the Invoke API itself (not function errors) use the AWS rest-json shape: header x-amzn-ErrorType: <Name>, x-amzn-RequestId, body {"Type":"User","message":"…"}. Codes: 413 RequestTooLargeException; 429 TooManyRequestsException + Retry-After + "Reason":"ReservedFunctionConcurrentInvocationLimitExceeded" (AWS SDKs retry it by themselves); 404 ResourceNotFoundException; 400 InvalidRequestContentException / InvalidParameterValueException; 408 RequestTimeoutException (body not received in time, loch-specific); 401/403 for authentication; 405 for other methods; 503 ServiceException on shutdown.
  • Function results: the HTTP status is the delivery (200). Always x-amzn-RequestId [aws] (= Lambda-Runtime-Aws-Request-Id), X-Amz-Executed-Version: $LATEST, Content-Type.
    • success: payload as posted by the runtime;
    • function error: X-Amz-Function-Error: Unhandled + the body the runtime posted, verbatim;
    • [aws] precedence, first match wins: posted init error > posted response or error > response too large > timeout > OOM > exit. Bodies:
      • init error: the body the runtime posted to /init/error (e.g. Runtime.ImportModuleError, Runtime.HandlerNotFound), fallback Runtime.ExitError below;
      • response too large: limit 6,291,556 bytes (6 MiB + 100, interop.MaxPayloadSize in the RIE); the runtime gets 413 {"errorMessage":"Exceeded maximum allowed payload size (6291556 bytes).","errorType":"RequestEntityTooLarge"}, the invoker gets {"errorType":"Function.ResponseSizeTooLarge","errorMessage":"Response payload size exceeded maximum allowed payload size (6291556 bytes)."} (message unverified), then re-init (Python dies on the 413);
      • timeout: {"errorType":"Sandbox.Timedout","errorMessage":"RequestId: <id> Error: Task timed out after 3.00 seconds"} (configured timeout, 2 decimals) (prefix unverified), plus the Lambda log line <timestamp> <id> Task timed out after 3.00 seconds before END, SIGKILL of the group, re-init before the next one;
      • OOM (memory.events oom_kill delta during the invocation + SIGKILL): {"errorType":"Runtime.OutOfMemory","errorMessage":"RequestId: <id> Error: Runtime exited with error: signal: killed"} (message unverified), re-init;
      • exit: {"errorType":"Runtime.ExitError","errorMessage":"RequestId: <id> Error: Runtime exited with error: exit status N"} (signals written signal: <name>, as observed in the spike), re-init.
  • Concurrency: exactly ONE invocation in flight to the bootstrap (Lambda model). FIFO queue bounded by count LOCH_RUNTIME_QUEUE_SIZE (default 16) and by bytes [sec] LOCH_RUNTIME_QUEUE_BYTES (default min(32 MiB, memory/8), never below one maximum payload, at most 64 GiB, effective value logged at startup: the bodies live in the function's own cgroup). The count covers the waiting requests (being read or queued); the bytes cover every body in memory (waiting, popped but not started, running) until the job is answered. Either full → 429 (Retry-After = the time left before a delayed re-init, 1 s otherwise, at most 30 s); configurable max wait LOCH_RUNTIME_QUEUE_TIMEOUT → 429, also for a job popped but not started yet (bootstrap re-initing); client gone while queued → removed; client gone while running → finish, drop the result. [aws] Queue wait does not consume the function timeout: Lambda-Runtime-Deadline-Ms is computed when next returns the invocation.
  • Health: GET /_loch/health → 200 {"status":"ready",…} / 503 initializing|error|stopping, queue depth; never invokes, needs no credential. Served on the Invoke listener and on the loopback health listener. health subcommand queries the latter, exit 0/1 (compose healthcheck ["CMD","/loch/lambda-runtime","health"], no curl).

Local invoke [sec]

loch-lambda-runtime invoke [--timeout <s>] [--log-tail] [--watch-stdin] reads the event on stdin (max 6 MiB, within 10 s), invokes 127.0.0.1:8080 without any credential (the loopback is exempt), and writes one bounded JSON envelope on stdout: {"statusCode":…,"functionError":…,"requestId":…,"durationMs":…,"payload":"<base64>","logTail":"<base64>"}; logTail is empty when not requested or when there is none. The client ignores proxy variables and redirects. Lifetime: it always ends by its own deadline, counted from its start: --timeout, by default AWS_LAMBDA_FUNCTION_TIMEOUT + LOCH_RUNTIME_QUEUE_TIMEOUT + 5 s (the panel passes no --timeout and relies on this bound). Docker cannot kill a docker exec process and, when the client goes away, does not close its stdout (writes keep succeeding, measured on Docker 29.9) but closes its stdin within about 0.5 s: with --watch-stdin, the event is the first JSON value on stdin, ended by a newline (a scalar such as 42, true or null only ends at the next byte; objects, arrays and strings end by themselves, multi-line JSON works), the caller keeps stdin open, and invoke ends within a second once stdin closes (tested). Exit 0 = delivered (whatever the function result or the HTTP status), 1 = transport error, deadline or caller gone, 2 = unusable event. The panel uses it through docker exec, so it never joins a function network (no bridge, no DNS impostor, no exposure of the panel API to tenants).

Runtime API (127.0.0.1:9001), version 2018-06-01 per AWS docs

  • GET /2018-06-01/runtime/invocation/next (long-poll) → 200 with the event and:
    • Lambda-Runtime-Aws-Request-Id, Lambda-Runtime-Deadline-Ms (epoch ms), Lambda-Runtime-Invoked-Function-Arn = arn:aws:lambda:<AWS_REGION>:000000000000:function:<name> [aws] (functions parse the account id from field 4);
    • Lambda-Runtime-Trace-Id always, valid X-Ray form Root=1-<8 hex epoch>-<24 hex>;Parent=<16 hex>;Sampled=0 or the incoming X-Amzn-Trace-Id (both RICs copy it to _X_AMZN_TRACE_ID, parsed by the X-Ray SDK and Powertools);
    • Lambda-Runtime-Client-Context and Lambda-Runtime-Cognito-Identity only when non-empty [aws] (the Node RIC JSON.parses them whenever present);
    • Lambda-Runtime-Invocation-Id is not sent in v1 (stated deviation; it is optional);
    • optionally Lambda-Runtime-Aws-Tenant-Id from X-Amz-Tenant-Id (low priority).
  • POST …/invocation/{id}/response (limit 6,291,556 bytes) and POST …/invocation/{id}/error → 202 {"status":"OK"}; POST …/runtime/init/error → 202.
  • [aws] Error type = Lambda-Runtime-Function-Error-Type if present, otherwise the body's errorType, otherwise Runtime.Unknown. The Node and Python RICs post invocation errors through aws-lambda-cpp, which never sends that header (only /init/error does): the type is in the body ({"errorType","errorMessage","trace"} Node, {"errorMessage","errorType","requestId","stackTrace"} Python). Lambda-Runtime-Function-XRay-Error-Cause is accepted and ignored.
  • [aws] Response streaming accepted in buffered mode: /response with Lambda-Runtime-Function-Response-Mode: streaming and chunked encoding (Node streamifyResponse handlers) is buffered up to the limit; error trailers (Lambda-Runtime-Function-Error-Type, Lambda-Runtime-Function-Error-Body base64) become the function error. Streaming to the client stays out of scope (real Lambda also buffers through the plain Invoke API).
  • [aws] Server limits on :9001: no read, write or idle timeout on next (AWS: "do not set a timeout on the GET request"; the Node RIC keeps one keep-alive socket); MaxHeaderBytes ≥ 2 MiB (Python caps the X-Ray cause header just below 1 MiB, Node has no cap); keep-alive.
  • Real state machine: unknown/stale id, double response, concurrent next → clean 4xx, NEVER a panic. [aws] Any non-2xx answer is fatal for the Python RIC (it raises and exits): every such path is followed by the exit / re-init handling above.
  • [aws] Unknown routes → clean 404: /2020-01-01/extension/*, /2022-07-01/telemetry, /2020-08-15/logs, /2018-06-01/runtime/restore/next ("SnapStart is not enabled"). /opt/extensions is never launched: a layer extension silently does nothing (documented). AWS_LAMBDA_EXEC_WRAPPER keeps working (handled by the bootstraps).
  • Out of scope v1: Extensions and Telemetry APIs, streaming to the client, SnapStart, X-Ray export, async Event.

Logs and metrics

  • Child stdout/stderr relayed unbuffered to the container output. Writes happen under the relay's lock: back-pressure from the log driver would also hold the engine. No rate limit in v1; the panel bounds the volume with the json-file driver options (max-size, max-file).
  • [aws] Platform lines in Lambda's plain-text format (tab-separated): START RequestId: <id> Version: $LATEST, END RequestId: <id>, REPORT RequestId: <id>\tDuration: X ms\tBilled Duration: Y ms\tMemory Size: M MB\tMax Memory Used: N MB\t (memory.peak when available: the container's lifetime peak, init and earlier invocations included, since the read-only cgroup cannot be reset — stated deviation from Lambda's per-invocation figure), Init Duration: Z ms\t on the first REPORT after an init, on failure Status: timeout or Status: error\tError Type: <type> (unverified); optional INIT_START Runtime Version: …. With AWS_LAMBDA_LOG_FORMAT=JSON the platform lines become {"time","type":"platform.start|platform.report|platform.initStart","record":{…}} (the RICs already format application logs from the passed-through variable).
  • The runtime's own logs: JSON (slog) on stderr, never interleaved inside an invocation's log tail. Never event contents or secrets.
  • GET /_loch/metrics (credential required), Prometheus text format: loch_lambda_invocations_total{outcome=success|error|timeout|exit|oom|too_large|init_error|throttled}, loch_lambda_invocation_duration_seconds (histogram, 1 ms to 15 min), loch_lambda_auth_failures_total, loch_lambda_inits_total{result=success|failure}, loch_lambda_init_duration_seconds (histogram), loch_lambda_queue_depth, loch_lambda_queue_depth_max, loch_lambda_memory_peak_bytes (when readable), loch_lambda_state{state}, loch_lambda_runtime_info{version}.

Container lifecycle (panel side, for information)

  • 1 container = 1 function = 1 runtime, created by compose, kept alive by Docker (restart: unless-stopped). Always warm, no scale-to-zero in v1; cold start (~200 ms measured, init included) only at deploy, restart, or after a timeout/crash (re-init).
  • Scaling later = replicas on the panel side; replicas are independent.
  • Memory: compose mem_limit = memswap_limit, AWS_LAMBDA_FUNCTION_MEMORY_SIZE set to the same value.

Deployment (panel side, for information)

  • v1: zip + AWS base image (Node.js, Python). The panel validates and extracts the zip into a versioned directory mounted read-only at /var/task; the runtime never handles a zip.
  • Later: client Lambda container images (hence the -- requirement, needed from v1).
  • The runtime binary is mounted read-only, pinned by sha256 in the panel's private reference, never part of the image.
  • Image source does not matter to the runtime: both public.ecr.aws/lambda/* (multi-arch) and mirror.gcr.io/amazon/aws-lambda-* (arch-suffixed tags nodejs:{22,24,26}-{arm64,x86_64}, python:{3.12,3.13,3.14}-{arm64,x86_64}; plain tags frozen since 2025-01 and amd64 only; first pulls may answer not found / 429, retry) must work.
  • [aws] /tmp: Lambda gives 512 MB by default, and "download the object to /tmp" is a common pattern; the panel makes the tmpfs size configurable (default 512 MB, documented as counted against the memory limit).
  • [aws] AWS SDK use: functions calling AWS-compatible services (Loch S3) get AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY from panel secrets and AWS_ENDPOINT_URL_S3 / AWS_ENDPOINT_URL (standard SDK variables), so the code is unchanged; the panel sets AWS_EC2_METADATA_DISABLED=true (otherwise the SDK credential chain times out on IMDS). Later: an ECS-style container-credentials endpoint (AWS_CONTAINER_CREDENTIALS_FULL_URI + AWS_CONTAINER_AUTHORIZATION_TOKEN) for rotating keys. Open: S3 virtual-hosted-style addressing does not resolve on Docker DNS; check path-style defaults with Loch S3 in phase 1b.

Custom runtimes: provided.al2023 and bootstrap (Go, Rust, …)

Measured with the runtime on public.ecr.aws/lambda/provided:al2023 (arm64, Docker Desktop and a Docker volume for the Linux-only cases) under the hardening (uid 10001, read-only, cap_drop: ALL). Items marked ✓ are covered by integration/compat_test.go (TestProvidedAL2023, TestProvidedBootstrapErrors).

  • Command: as for the other images, -- /lambda-entrypoint.sh <handler> (or the shortcut <handler>) ✓. The entrypoint script requires exactly one argument and exports it as _HANDLER; Go (aws-lambda-go) ignores it: any non-empty value works, bootstrap by convention. -- ./bootstrap (relative to /var/task, the working directory) also works, without _HANDLER ✓. Without handler nor command, the runtime refuses to start (usage, exit 2).

  • Name and place: according to the image's /var/runtime/bootstrap script, it execs /var/task/bootstrap, else /opt/bootstrap (layers), and nothing else. Any executable works: a static binary, or a script (#!/bin/sh) that execs one.

  • Mode: readable and executable by uid 10001. The files belong to the panel or the developer, not to 10001: 0755 (other r-x) ✓, and every directory on the way o+x. A root-owned 0700 bootstrap fails with Permission denied.

  • Docker Desktop (macOS) does not enforce the owner on bind mounts: a 0700 file of the host user runs as uid 10001 there, and fails on Linux. The execute bit is enforced everywhere (a 0644 file fails) ✓.

  • Panel side (recommendation, not measured): a zip made without Unix modes (Windows tools) would extract a non-executable bootstrap; set 0755 on it when extracting, or refuse the zip.

  • Architecture: the binary must match the image (GOARCH=arm64 or amd64), static (CGO_ENABLED=0, -tags lambda.norpc with aws-lambda-go) or built against the image's glibc (AL2023). A mismatch runs under emulation where binfmt handles that architecture (an amd64 bootstrap ran on Docker Desktop arm64), and fails otherwise (Exec format error, measured with a loong64 binary). The panel can check the ELF header (e_machine) at deploy.

  • When the bootstrap cannot run, the causes and what the image's script posts to /runtime/init/error:

    • missing: Runtime.InvalidEntrypoint, no bootstrap found at /var/task/bootstrap or /opt/bootstrap ✓;
    • not executable, not readable, wrong architecture without emulation: Runtime.InvalidEntrypoint, failed to exec /var/task/bootstrap (the reason on stderr) ✓ for the first;
    • exits during init: Runtime.ExitError, Runtime exited with error: exit status N (the runtime's error) ✓.

    Then health is error (the health subcommand exits 1), every invocation answers 200 with X-Amz-Function-Error: Unhandled and that error as payload ✓, and the init is retried with the backoff. [aws] Lambda also reports init errors as function errors (exact shape unverified).

  • /var/task is read-only: the bootstrap writes to /tmp only.

Threat model: what the function's code can do [sec]

The function's code is untrusted and runs under the runtime's uid, in the same container. Besides what the sections above cover (credentials, credential files, the loopback exemption), it can:

  • Forge platform log lines. It writes freely to stdout and stderr, so it can print a fake START, END or REPORT line (plain text or JSON); the relay only guarantees that the runtime's own lines start on a fresh line. Never derive billing or health from logs: use /_loch/metrics, the invoke envelope, or /_loch/health.
  • Signal PID 1. Same uid. Measured with the runtime as PID 1 (Node 22 image, uid 10001, cap_drop: ALL), kill from inside the container: SIGTERM and SIGINT stop the runtime gracefully (exit 0); SIGHUP reloads the credential files (hence their checks); SIGQUIT, SIGABRT, SIGTRAP, SIGSEGV, SIGBUS, SIGILL, SIGFPE and SIGSYS make the Go runtime exit 2 at once, with a dump of every goroutine's stack (and the registers) in the container logs, skipping the graceful shutdown (an on-failure restart policy or a crash alert would fire); the other signals (SIGUSR1, SIGUSR2, SIGPIPE, SIGALRM, SIGWINCH, SIGSTOP, …) are ignored, and so is SIGKILL from inside the namespace. Self-inflicted only (the function can already stop its container with SIGTERM); the dumps show addresses, lengths and register words, not string contents, and the function cannot read the container logs.
  • Revoke its oom_score_adj. The child starts at 1000 so that the kernel kills it before PID 1; it may lower its own value down to the container's minimum (oom_score_adj_min, 0 by default: 0 accepted, -1 refused, measured), which only a writer with CAP_SYS_RESOURCE could change. Then an OOM may kill PID 1 instead, which stops the container: self-inflicted only.
  • Invoke itself through the loopback, without credential, bound by the global caps.

And a network caller, without credential, can:

  • Read /_loch/health on the Invoke listener: the state of the runtime and queueDepth. Accepted: O(1), no event, no secret.
  • Tell a valid access key id from a wrong one: an unknown id answers UnrecognizedClientException, a known id with a wrong signature InvalidSignatureException, as on AWS. The access key id is random and kept private (it travels in clear in Authorization on the private network): with it alone, a caller can only hold the unverified budget (see SigV4).

A web page, through a visitor's browser, cannot invoke the function: browser requests are refused (see Invoke API), unless LOCH_RUNTIME_ALLOW_BROWSER=true; with authentication off, it can read /_loch/metrics through DNS rebinding.

Hardening (validated in the spike with the RIE, must hold)

Arbitrary non-root uid (10001:10001), read_only, cap_drop: ALL, no-new-privileges, only /tmp writable (tmpfs), memory limit without swap, cpus 0.5, pids_limit 128, internal network, no published port. The binary writes nothing outside /tmp, depends on neither the image's libc nor curl. OOM detection reads memory.events from the container's own cgroup (read-only): verify it is visible under the hardening.

How Loch.sh Panel uses it

  • Downloads the release for the host arch, verifies it against the hash table and public key embedded in the panel build, stores it in FUNCTIONS_DATA_DIRECTORY/.runtime/<version>/<arch>/, pins the sha256 in function.json, checks version.
  • Invokes with docker exec <fn> /loch/lambda-runtime invoke --log-tail (bounded stdin/stdout, deadline = function timeout + queue wait + margin), never through a network bridge. Network callers (other sites, the Loch S3 outbox) use the HTTP endpoint with the token or SigV4 key pair the panel generated for that function. The panel treats the envelope as untrusted (fixed JSON envelope, never copies function headers or content types).
  • Generates per-function credentials (.loch/fn-<name>/invoke.token, access key pair), 0400, shown once, rotatable.
  • The Loch S3 webhook will authenticate with SigV4 or the bearer token like any caller; the Loch S3 side also signs the body (HMAC, timestamp, replay window).

Tests

  • Unit: Runtime API state machine (including double response, stale id, concurrent next, error type from body vs header, streaming mode with trailers), queue (full, byte cap, disconnects, max wait, deadline computed at next), timeouts, outcome precedence, configuration parsing, environment building (forced/removed/defaulted variables), authentication (bearer, SigV4 valid/expired/wrong, missing), server limits (slow headers, slow body, oversized Content-Length, chunked), Invoke error shapes (x-amzn-ErrorType, body), function name/ARN/Qualifier matching, invoke subcommand envelope, log line formats (text and JSON).
  • Integration (build tag integration, Docker) against real AWS images from both registries, under the full hardening: 50 parallel invocations without a crash (each served or 429), timeout, exception (Node and Python bodies), process.exit / os._exit, init error (missing module, missing handler), slow init (> 10 s), payload 6 MiB + 1 → 413, oversized response, OOM, streamifyResponse handler, SIGTERM during an invocation, non-POST methods, healthcheck, -- with provided.al2023 (a Go bootstrap), an AWS SDK v3 call from Node with endpoint-url and SigV4 against the runtime (aws lambda invoke); bonus: sharp resize (spike code-sharp/).