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/.
- 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.
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.
- 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 +SHA256SUMSwith 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 bareSHA256SUMS.
- 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 shareENTRYPOINT ["/lambda-entrypoint.sh"],WORKDIR /var/task) and images usingawslambdaric/aws-lambda-ricas entrypoint. - [aws]
/lambda-entrypoint.shexits 142 unless it gets exactly one argument, and the image CMD isnull: the handler must always be supplied. The child runs withDir= the image WORKDIR (by default the runtime's own working directory, which Docker sets to the image WORKDIR,/var/taskin the AWS images; flag--workdir/LOCH_RUNTIME_WORKDIR): relative entrypoints such as./mainon 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/libon 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.shexports_HANDLER="$1", execs the RIE whenAWS_LAMBDA_RUNTIME_APIis empty,/var/runtime/bootstrapotherwise. - [aws] Environment of the child (the rest is passed through unchanged):
- always forced:
AWS_LAMBDA_RUNTIME_API=127.0.0.1:9001(IPv4host: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 toLambdaMultiConcurrentRuntimeClient, 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(defaultfunction),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(defaultus-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 inventsAWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/AWS_SESSION_TOKEN, they come from the caller's environment (the panel's secrets).
- always forced:
AWS_LAMBDA_FUNCTION_MEMORY_SIZEabsent: 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-sizefrom 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 withinLOCH_RUNTIME_SHUTDOWN_GRACE, then SIGTERM the group, then SIGKILL after ~500 ms.LOCH_RUNTIME_SHUTDOWN_GRACEmust be shorter than the composestop_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 isSandbox.Timedout, notRuntime.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 keepserrorin health (Dockerunhealthy) and is counted in the metrics. - [aws] An exit while idle (between invocations) → re-init before the next
next, not an error state.
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 → 404ResourceNotFoundException. Same path as the RIE, soaws 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 thingmaindoes, for every subcommand) and removes the credential variables from its own environment. Processes started withdocker exec(health,invoke) inherit the container's environment and also callPR_SET_DUMPABLE=0first, but the Go runtime starts beforemain: a function scanning/proccan open their/proc/<pid>/environwithin 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/shwith the full environment: use the exec form (["CMD", "/loch/lambda-runtime", "health"]). WithoutCAP_SETUIDthe uids cannot be separated. Hence: no usable secret in the container.- Bearer token, stored as its SHA-256 (
LOCH_RUNTIME_TOKEN_SHA256, 64 hex, orLOCH_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 plainLOCH_RUNTIME_TOKEN(orLOCH_RUNTIME_TOKEN_FILE) is accepted for standalone use, but the function can read it through thedocker execprocesses. 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.1or::1, inside the container's network namespace, can only come from the function itself or fromdocker execprocesses; the function gains nothing by invoking itself. Theinvokeandhealthsubcommands 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).
- Bearer token, stored as its SHA-256 (
- SigV4 details (service
lambda, any region), so AWS SDK callers withendpoint-urlwork unchanged. Two phases, because the AWS SDKs for Lambda do not sendX-Amz-Content-Sha256while the signature covers the payload hash:- before the body: format, access key id (constant-time compare of hashes), credential scope (service
lambda,aws4_request), signedX-Amz-Date(orDate) within ±5 min and matching the scope date,SignedHeaderssorted and includinghostand the date header; with a signedX-Amz-Content-Sha256, the signature itself, and the request is authenticated from then on (only the body's integrity is left);UNSIGNED-PAYLOADrefused; - 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 ofLOCH_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 inAuthorization, 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, …) andContent-Typemust be signed.X-Amzn-Trace-Idis not (the SDKs never sign it): a replay may change the trace id, whose format is validated. ADryRunis 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.
- before the body: format, access key id (constant-time compare of hashes), credential scope (service
- 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/plainrequest to a reachable Invoke API (a published127.0.0.1port in local development, for instance) without a CORS preflight, and DNS rebinding makes the request same-origin. So the Invoke API and/_loch/metricsanswer 403AccessDeniedException(Connection: close, no CORS header, the message does not name the opt-out) to any request carryingOrigin,Sec-Fetch-Site,Sec-Fetch-DestorSec-Fetch-User, whatever the value: modern browsers sendOriginon every POST, same-origin included (nullfrom afile://page), andSec-Fetch-Site/Sec-Fetch-Destto trustworthy origins (HTTPS,localhost,127.0.0.1); the AWS SDKs, the AWS CLI, curl, Deno and Python send none of them.Sec-Fetch-Modealone is accepted: Node'sfetch(undici) sendsSec-Fetch-Mode: corsby 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/healthis not filtered (probes, no invocation).LOCH_RUNTIME_ALLOW_BROWSER=trueaccepts browser requests. A reverse proxy that forwards a browser'sOriginto the function is refused too, by design: strip the header at the proxy, or use the opt-out. NoHostallow-list: invocations are POSTs, which carryOrigin, 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/metricsthat way (counters, no invocation); legacy browsers (IE, Edge Legacy) did not sendOriginon form POSTs. - Every authentication failure: AWS-shaped 401/403,
Connection: close, counted inloch_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
*_FILEvariants (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:romount, 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 canchmodit 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:robind mount). The file is opened withO_NONBLOCK|O_NOCTTYand 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/healthstays open;/_loch/metricsandX-Amz-Log-Type: Tailrequire the credential (with SigV4, aGET /_loch/metricsis signed over an empty body)./_loch/metricsis under the same per-IP cap as invocations.- [sec] HTTP server limits:
ReadHeaderTimeout5 s,IdleTimeout5 s (an idle keep-alive connection holds a slot of the cap),MaxHeaderBytes32 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 408RequestTimeoutExceptionand 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 capLOCH_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_NOFILEis per process, the function has its own; a warning at startup when the runtime'sRLIMIT_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; withLOCH_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 atLOCH_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 whenLOCH_RUNTIME_MAX_CONNS≥ 8 × (LOCH_RUNTIME_QUEUE_SIZE+ 1), as by default up toLOCH_RUNTIME_QUEUE_SIZE95; beyond, or with an explicit lower value, one IP has at mostLOCH_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 … invokeand the healthcheck are inside the container), still bound by the global cap./_loch/healthis also served alone on a loopback listenerLOCH_RUNTIME_HEALTH_ADDR(default127.0.0.1:8081, 4 connections), which thehealthsubcommand uses, so the healthcheck never competes with Invoke clients. - Body: raw event, limit
LOCH_RUNTIME_MAX_PAYLOAD(6 MiB). Over → 413RequestTooLargeException[aws], never a truncated body; aContent-Lengthover 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→ 400InvalidParameterValueExceptionin 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 400InvalidRequestContentException), relayed decoded asLambda-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: 413RequestTooLargeException; 429TooManyRequestsException+Retry-After+"Reason":"ReservedFunctionConcurrentInvocationLimitExceeded"(AWS SDKs retry it by themselves); 404ResourceNotFoundException; 400InvalidRequestContentException/InvalidParameterValueException; 408RequestTimeoutException(body not received in time, loch-specific); 401/403 for authentication; 405 for other methods; 503ServiceExceptionon 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), fallbackRuntime.ExitErrorbelow; - response too large: limit 6,291,556 bytes (6 MiB + 100,
interop.MaxPayloadSizein 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 secondsbefore END, SIGKILL of the group, re-init before the next one; - OOM (
memory.eventsoom_killdelta 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 writtensignal: <name>, as observed in the spike), re-init.
- init error: the body the runtime posted to
- 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(defaultmin(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 waitLOCH_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-Msis computed whennextreturns the invocation. - Health:
GET /_loch/health→ 200{"status":"ready",…}/ 503initializing|error|stopping, queue depth; never invokes, needs no credential. Served on the Invoke listener and on the loopback health listener.healthsubcommand queries the latter, exit 0/1 (compose healthcheck["CMD","/loch/lambda-runtime","health"], no curl).
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).
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-Idalways, valid X-Ray formRoot=1-<8 hex epoch>-<24 hex>;Parent=<16 hex>;Sampled=0or the incomingX-Amzn-Trace-Id(both RICs copy it to_X_AMZN_TRACE_ID, parsed by the X-Ray SDK and Powertools);Lambda-Runtime-Client-ContextandLambda-Runtime-Cognito-Identityonly when non-empty [aws] (the Node RICJSON.parses them whenever present);Lambda-Runtime-Invocation-Idis not sent in v1 (stated deviation; it is optional);- optionally
Lambda-Runtime-Aws-Tenant-IdfromX-Amz-Tenant-Id(low priority).
POST …/invocation/{id}/response(limit 6,291,556 bytes) andPOST …/invocation/{id}/error→ 202{"status":"OK"};POST …/runtime/init/error→ 202.- [aws] Error type =
Lambda-Runtime-Function-Error-Typeif present, otherwise the body'serrorType, otherwiseRuntime.Unknown. The Node and Python RICs post invocation errors through aws-lambda-cpp, which never sends that header (only/init/errordoes): the type is in the body ({"errorType","errorMessage","trace"}Node,{"errorMessage","errorType","requestId","stackTrace"}Python).Lambda-Runtime-Function-XRay-Error-Causeis accepted and ignored. - [aws] Response streaming accepted in buffered mode:
/responsewithLambda-Runtime-Function-Response-Mode: streamingand chunked encoding (NodestreamifyResponsehandlers) is buffered up to the limit; error trailers (Lambda-Runtime-Function-Error-Type,Lambda-Runtime-Function-Error-Bodybase64) 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/extensionsis never launched: a layer extension silently does nothing (documented).AWS_LAMBDA_EXEC_WRAPPERkeeps working (handled by the bootstraps). - Out of scope v1: Extensions and Telemetry APIs, streaming to the client, SnapStart, X-Ray export, async
Event.
- 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-filedriver 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.peakwhen 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\ton the first REPORT after an init, on failureStatus: timeoutorStatus: error\tError Type: <type>(unverified); optionalINIT_START Runtime Version: …. WithAWS_LAMBDA_LOG_FORMAT=JSONthe 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}.
- 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_SIZEset to the same value.
- 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) andmirror.gcr.io/amazon/aws-lambda-*(arch-suffixed tagsnodejs:{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_KEYfrom panel secrets andAWS_ENDPOINT_URL_S3/AWS_ENDPOINT_URL(standard SDK variables), so the code is unchanged; the panel setsAWS_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.
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,bootstrapby 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/bootstrapscript, 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(otherr-x) ✓, and every directory on the wayo+x. A root-owned0700bootstrap fails withPermission denied. -
Docker Desktop (macOS) does not enforce the owner on bind mounts: a
0700file of the host user runs as uid 10001 there, and fails on Linux. The execute bit is enforced everywhere (a0644file fails) ✓. -
Panel side (recommendation, not measured): a zip made without Unix modes (Windows tools) would extract a non-executable
bootstrap; set0755on it when extracting, or refuse the zip. -
Architecture: the binary must match the image (
GOARCH=arm64oramd64), static (CGO_ENABLED=0,-tags lambda.norpcwithaws-lambda-go) or built against the image's glibc (AL2023). A mismatch runs under emulation wherebinfmthandles 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(thehealthsubcommand exits 1), every invocation answers 200 withX-Amz-Function-Error: Unhandledand that error as payload ✓, and the init is retried with the backoff. [aws] Lambda also reports init errors as function errors (exact shape unverified). - missing:
-
/var/taskis read-only: the bootstrap writes to/tmponly.
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,ENDorREPORTline (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, theinvokeenvelope, or/_loch/health. - Signal PID 1. Same uid. Measured with the runtime as PID 1 (Node 22 image, uid 10001,
cap_drop: ALL),killfrom inside the container:SIGTERMandSIGINTstop the runtime gracefully (exit 0);SIGHUPreloads the credential files (hence their checks);SIGQUIT,SIGABRT,SIGTRAP,SIGSEGV,SIGBUS,SIGILL,SIGFPEandSIGSYSmake 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 (anon-failurerestart policy or a crash alert would fire); the other signals (SIGUSR1,SIGUSR2,SIGPIPE,SIGALRM,SIGWINCH,SIGSTOP, …) are ignored, and so isSIGKILLfrom inside the namespace. Self-inflicted only (the function can already stop its container withSIGTERM); 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 withCAP_SYS_RESOURCEcould 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/healthon the Invoke listener: the state of the runtime andqueueDepth. 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 signatureInvalidSignatureException, as on AWS. The access key id is random and kept private (it travels in clear inAuthorizationon 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.
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.
- 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 infunction.json, checksversion. - 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).
- 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 atnext), 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,invokesubcommand 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,streamifyResponsehandler, SIGTERM during an invocation, non-POST methods, healthcheck,--withprovided.al2023(a Gobootstrap), an AWS SDK v3 call from Node withendpoint-urland SigV4 against the runtime (aws lambda invoke); bonus: sharp resize (spikecode-sharp/).