ソースを参照

docs: runner secrets, authentication and packaging

CLAUDE.md gains the three things an operator or a future reader gets
wrong otherwise: the SVAPI_FN_<project>__<NAME> scheme and why the
project is in the name, the startup refusal for an unauthenticated
non-loopback runner, and the 0751 mode on /etc/smartbotic-vectorapi that
a server upgrade must not reset to 0750.

Also the step nothing in the build enforces: installing the runner does
not enable functions, because the server disables the routes when no
endpoint is configured.

The spec records ctx.env and runner authentication as shipped rather than
deferred, and replaces the authentication item in "Still open" with what
packaging left open - chiefly that one runner process serving every
project in an engine written in C is a cross-tenant boundary that
hardening bounds but does not remove.
fszontagh 1 ヶ月 前
親
コミット
3a62865c38
2 ファイル変更、28 行追加、13 行削除
  1. 6 2
      CLAUDE.md
  2. 22 11
      docs/superpowers/specs/2026-10-06-function-runtime-design.md

+ 6 - 2
CLAUDE.md

@@ -55,7 +55,8 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **A write is validated on a runner before storage**, so the engine that validates is the engine that executes; with no healthy runner the write is refused **503** rather than stored unchecked.
 - **`RunnerPool` retry is three-way, not two.** Never connected → retry (nothing ran). Answered, whatever the answer → never retry (the runner did its job). **Delivered then unanswered** (read timeout, non-200, unparseable body) → **do not retry**, mark unhealthy: the handler may be running right now, and a retry would run a side-effecting function twice. `validate()` retries everything, because compiling has no side effects. Also: `RunnerPool::Options::readTimeoutSec` **must exceed** the runner's `max_wall_time_ms`, or our read times out before the runner can report its own timeout and the caller gets a misleading 503 instead of a 504.
 - **`ctx.collections(...)` is a direct gateway call, never loopback HTTP**, and `ctx.fetch` pins the connection to the single address the guard approved (`set_hostname_addr_map`) rather than re-resolving — re-resolving IS the rebinding window. One resolution, one classification.
-- **`ctx.env` is empty and functions cannot hold a secret yet**: nothing has decided where a project's secrets live or who may read them, and an empty env is the only answer that cannot leak one. The one piece of slice 1 deliberately deferred.
+- **`ctx.env` comes from the runner's environment, scoped per project**: `SVAPI_FN_<project>__<NAME>` in `/etc/smartbotic-vectorapi/runner.env` reaches that project's functions as `ctx.env.<NAME>`. The project is part of the variable name because one runner serves every project; nothing outside the `SVAPI_FN_` prefix is ever exposed, so the runner's own token and database address stay invisible to functions. Matched exactly and case-sensitively; the split is at the **first** `__`, so a project whose name contains `__` cannot carry secrets.
+- **The runner authenticates a shared bearer token and fails closed.** No token plus a non-loopback bind address means it **refuses to start**. `isLoopbackBind()` answers "not loopback" for anything it cannot parse, so an unrecognised address produces the refusal. The comparison is constant-time, `/health` is authenticated too, and both sides prefer `SVAPI_RUNNER_TOKEN` in the `.env` over the conffile.
 - **`ctx.fetch` egress goes through the SSRF guard** (`functions/net_guard.hpp`): fail closed on anything unparseable, and classify **every** address a name resolves to, not the first. A custom blocklist from settings *replaces* the defaults rather than extending them.
 
 ## Data model & runtime config
@@ -79,13 +80,16 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **Document write bodies accept two shapes, via one reader.** `documentBody()` in `handlers/documents.cpp` is used by POST, PUT and PATCH: it unwraps `{"data":{...}}`, strips `id` (the document's identity, from the body on POST and from the URL on PUT/PATCH), and rejects `data` alongside any other top-level key with **422** `ambiguous_body`. Before 0.3.3 only POST unwrapped, so a `{"data":...}` PUT stored the wrapper as a literal field and a `data`-plus-siblings POST dropped the siblings silently. A literal top-level `data` field is still writable as `{"data":{"data":...}}`.
 - **QuickJS is pinned to an exact quickjs-ng tag** (`SVAPI_QUICKJS_TAG`, `runner/CMakeLists.txt`). QuickJS bytecode carries **no version stamp**, so a silent upgrade makes a cached blob *misread* rather than fail. quickjs-ng, not Bellard's tree: the module/promise/stack entry points the core needs (`JS_GetModuleNamespace`, `JS_PromiseState`, `JS_SetMaxStackSize`, `JS_IsJobPending`) are public API there. `JsBytecode` is an in-process cache only - never persist it without a QuickJS build fingerprint.
 - **QuickJS's job queue belongs to the `JSRuntime`, not the `JSContext`.** A fresh context per run is therefore *not* enough to isolate tenants: a run that times out mid-microtask leaves its jobs queued, and they would execute inside the next tenant's run. The core flushes them with the deadline forced into the past and marks the runtime `poisoned()` if anything survives; the pool destroys a poisoned runtime instead of leasing it out. An OOM poisons it too.
+- **`/etc/smartbotic-vectorapi` must stay mode 0751, not 0750.** The runner runs as its own user and needs `+x` to traverse the directory to `runner.json`; it still cannot list it, and the server's `0640` files stay unreadable to it. Both `server.postinst` and `runner.postinst` set it, and a server upgrade resetting it to `0750` breaks the runner on its **next restart** - a failure that surfaces weeks later with no obvious cause.
+- **Installing the runner does not enable functions.** `config.json` ships with no `functions.runners` endpoints, and the server disables the function routes when the list is empty (answering 503). An operator has to add the endpoint by hand, and set the same `SVAPI_RUNNER_TOKEN` in both `vectorapi.env` and `runner.env`.
 - **Monaco** is bundled locally (`webui/src/monacoSetup.ts`) so the editor works offline — do not revert to the CDN loader.
 - systemd unit is `Type=notify`; the binary must be built with `libsystemd` (it is, when `libsystemd-dev` is present) or change to `Type=exec`.
 
 ## Deploy / publish
 
 ```bash
-./packaging/build.sh                                # Debian-13 .debs → dist/debian13/
+./packaging/build.sh                                # Debian-13 .debs → dist/debian13/ (3 packages: server, webui, runner)
+./packaging/build.sh --no-runner                    # skip the runner package
 ./packaging/build.sh --repo --suite trixie --sync   # + publish to repository.smartbotics.ai (outward-facing!)
 ```
 Publishing uploads to the live apt repo — only with explicit confirmation. The deb-repo tooling is `/data/dev/smartbotics/smartbotics-deb-repo/scripts/` (override with `DEB_REPO_DIR`).

+ 22 - 11
docs/superpowers/specs/2026-10-06-function-runtime-design.md

@@ -271,13 +271,15 @@ the QuickJS engine and pool, the runner service (`ctx.*`, `/run`, `/validate`,
 `/health`, the binary), functions CRUD, HTTP dispatch at `/fn/{project}/*`,
 manual invoke, and run logs.
 
-**Deferred, and the only piece of slice 1 that did not ship: `ctx.env`.** The
-field exists and is always empty. Nothing in the design decides where a
-project's secrets are stored or who may read them, and an empty env is the only
-answer that cannot leak one. Two independent implementations arrived at the same
-refusal to guess. A function therefore cannot hold a credential, which also
-means `ctx.fetch` can currently only reach endpoints that need none. This wants
-its own cycle, next to the per-project embedding key that already exists.
+`ctx.env` shipped after the first pass, once secrets had somewhere to live:
+the runner's own environment, loaded by systemd from runner.env, with the
+project encoded in each variable name (`SVAPI_FN_<project>__<NAME>`). A flat
+namespace was the thing to avoid - one runner serves every project.
+
+The runner now authenticates a shared bearer token and refuses to start
+unauthenticated on any address but loopback, which closes the "newly open"
+item below that mattered most. Packaging ships it as a third deb with its own
+system user, so a sandbox escape inherits none of the server's credentials.
 
 ### Resolved from "Still open"
 
@@ -298,10 +300,6 @@ its own cycle, next to the per-project embedding key that already exists.
 
 ### Newly open
 
-- **The runner has no authentication** and binds `127.0.0.1`. `RunnerPool` sends
-  no credential, so none was invented. This needs deciding before runners ever
-  sit on a shared network - which was the stated reason for making the runner a
-  separate service.
 - `listProjects()` runs on every `/fn/*` request: a database round trip on the
   hot path, and the first thing to cache once anyone measures this.
 - `JsLimits` is fixed at construction, unlike every other setting in this
@@ -309,3 +307,16 @@ its own cycle, next to the per-project embedding key that already exists.
 - Repeated query keys (`?tag=a&tag=b`) collapse to the last value, because the
   trigger's `query` is an object. Widening it is a protocol change on both sides.
 - `HEAD` on `/fn/*` is unroutable: cpp-httplib has no `Server::Head` registrar.
+
+### Still open after packaging
+
+- **A QuickJS memory-safety bug is a cross-tenant compromise**, not a crashed
+  run: every function in a project shares one runner process and one engine
+  pool, and after a native escape the Principal/KeyOp mapping that separates
+  tenants is gone. The unit hardening bounds the blast radius; it does not make
+  an escape harmless. Per-project runner processes would, at a cost.
+- `MemoryMax=1G` is a cgroup backstop behind the in-engine limits, so if those
+  ever fail to fire the kernel OOM kill takes every concurrent tenant's run with
+  it. Bounded damage over an unbounded host, but a shared-fate failure mode.
+- The runner unit has not been checked with `systemd-analyze verify`; Void has
+  no systemd. Run it on the first Debian target.