فهرست منبع

docs: record the function-runtime decisions that were not in the design

CLAUDE.md gains the two facts a reader would otherwise relearn the hard
way: the exact QuickJS pin and why bytecode has no version stamp, and
that the job queue lives on the JSRuntime, so poisoning a runtime is not
an optimisation to simplify away. Also the function-runtime conventions -
a push never widens access, the default policy floor grants nothing, the
SSRF guard fails closed and classifies every resolved address.

The spec gains an addendum recording each decision against the design it
corrects, including that the Principal refactor touched zero handler call
sites rather than "every handler's auth call" as its own risk list
predicted, and a "Still open" list so the next cycle does not have to
rediscover what was deliberately left undecided.
fszontagh 1 ماه پیش
والد
کامیت
c6a8305d2b
2فایلهای تغییر یافته به همراه72 افزوده شده و 0 حذف شده
  1. 11 0
      CLAUDE.md
  2. 61 0
      docs/superpowers/specs/2026-10-06-function-runtime-design.md

+ 11 - 0
CLAUDE.md

@@ -32,6 +32,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
   - `db_gateway` (`qualify(project,coll)` + `DbGateway` over `smartbotic::database::Client`), `settings_store` (global settings **and per-project embedding overrides**, hot-reload, one subscribe stream for both), `project_settings` (`ProjectEmbeddingSettings` + the pure `resolveEmbedding()`), `outbound_http` (User-Agent + TLS defaults for every external call), `key_store` (API keys, hot-reload, bootstrap admin key), `collection_registry` (per-project metadata), `embeddings` (OpenAI), `auth` (sessions, bearer/cookie), `server` (ApiServer + auth helpers), `handlers/*` (one file per route group).
   - Auth model: pre-routing **authenticates** `/api/*` (401); each handler **authorizes** via `requireKey` → `requireAdmin` / `requireProjectAccess` (403). Keys are referenced by a stable **`id`** (not the secret).
 - `webui/` — React 19 + Vite + TS (strict, `erasableSyntaxOnly`) + Tailwind + Monaco. Cookie-session auth (`credentials:'include'`). Pages read `currentProject`/`admin` from `useAuthStore`; all calls go through `src/api/client.ts`. **Documents keeps `collection`, the filter triple (`field`/`op`/`value`) and `open` in the URL**, so relation links are ordinary links and any filtered view is shareable; changing collection closes an open editor (it belongs to the collection being left). `pages/Settings.tsx` is a tab shell over `pages/settings/*` (Embeddings, Cache & performance, Access & security, Web UI are admin-only; the per-project embeddings tab is not, so `/settings` is **not** admin-gated in `App.tsx`). Shared controls live in `components/form.tsx`.
+- `runner/` — the function runner's QuickJS execution core (`runner_core`). **Builds as its own top-level project** (`cmake -S runner -B build-runner`), which is the one part of this repo that compiles on the Void dev host, since it links neither `vectorapi_core` nor the database client. `BUILD_RUNNER=ON` wires it into the root build; it is **OFF by default** because it vendors QuickJS from GitHub at configure time and an ordinary build must not start depending on a network fetch.
 - `api/` — `openapi.json` (3.1), `llms.txt` (llmstxt.org), `docs/` (Redoc page). Served at `/openapi.json`, `/llms.txt`, `/docs`. Shipped in the server `.deb`. **Keep these in sync when changing routes.**
 - `packaging/` — `build.sh` (`--local` + Docker trixie), `deb/create-debs.sh`, control templates, systemd unit, maintainer scripts. `docs/superpowers/` — design spec (esp. **Addendum A**) + the 3 implementation plans.
 
@@ -44,6 +45,14 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - TS: no `any`, no TS `enum`, no constructor parameter-property shorthand (tsconfig `erasableSyntaxOnly`). Iterating parsed JSON: bind to a named var first (range-for over `nlohmann::json::parse(...)[...]` dangles).
 - Commits: conventional prefixes (`feat`/`fix`/`build`/`docs`/`test`). Branch for feature work; `main` is pushed to `ssh://git.smartbotics.ai:10022/fszontagh/smartbotic-vectorapi.git`.
 
+## Function runtime (slice 1, in progress)
+
+- **A function is a principal, not a key holder** (`principal.hpp`). `requireCapabilityCore()` answers project/scope/rate-limit questions for any caller; the `ApiKey` overload adds the things only an HTTP request has (Origin allow-list, captcha), because those are meaningless for a cron or event run. One implementation, so function access and HTTP access cannot drift.
+- **A code push can never widen access.** `mergeForCodePush()` (`function_record.hpp`, pure) takes `policy` and `enabled` from the stored row and **never reads the ones in the payload** - not unioned, not used as a fallback. A first registration inherits the project default. Identity is `function_id` from the script's `on` block and `path` carries no meaning, so a rename keeps the row and its policy.
+- `builtinDefaultFunctionPolicy()` grants **nothing**: unreviewed code reaches no collection until an admin says so. Widening it is a security-posture change, and a test asserts the current floor.
+- **Descriptor parsing never throws** (`functions/descriptor.hpp`, pure): a script author's typo is data. Unknown keys are ignored so a script written for a later server still loads. 404 and 405 stay distinct, so a 405 can carry its `Allow:` union.
+- **`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
 
 - Bootstrap `config.json` is minimal: `log_level`, `http.{bind_address,port}`, `database.address`. Everything else lives in the DB and **hot-reloads** (subscribe + atomic snapshot swap).
@@ -63,6 +72,8 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **`relations_enforced` is readable since client 2.11.4** via `tryGetRelationsEnforced()`, which DECLINES to answer on a failed read rather than defaulting (`getRelationsEnforced()` is the fail-to-enforced variant, for code deciding whether it may rely on enforcement). The collection GET surfaces it, omitting the field when undetermined - absence never means disabled, so the web UI renders three states, not two.
 - **Database failures keep their classification** (`db_errors.hpp`, client 2.11.4). `Client::Error::code()` on the throwing calls and the `Failure&` overloads on `update`/`patch`/`remove` feed one `translate()`: AlreadyExists → 409 `duplicate_values`, FailedPrecondition → 422 `relation_violation`, NotFound → 404, Unavailable/DeadlineExceeded/Unknown → 503, everything else → 500. **`ErrorCode::Ok` on a call that returned false means "did not apply", not an error** - map it to 404, or a plain missing document becomes a 500 with an empty message.
 - **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.
 - **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`.
 

+ 61 - 0
docs/superpowers/specs/2026-10-06-function-runtime-design.md

@@ -200,3 +200,64 @@ FAIL - a denied collection, a wall-time timeout, a blocked egress.
 - The `Principal` refactor is broad, touching every handler's auth call.
 - HTTP functions gain a network hop; measure the latency before anyone builds a
   chatty endpoint on it.
+
+## Addendum: slice-1 implementation decisions
+
+Recorded as they were settled, because each one either corrects the design
+above or fills a gap it left open.
+
+**The job queue correction.** "A fresh `JSContext` per run so nothing leaks
+between tenants" is not sufficient: QuickJS keeps the microtask queue on the
+`JSRuntime`. A run that times out mid-microtask leaves 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 rather than leasing it. This is
+the one rule the implementation adds that the design did not state.
+
+**The Principal refactor is narrower than estimated.** The design calls it
+"mechanical but broad: it touches every handler's auth call". It touches none.
+`requireCapability()` split into a transport-free core plus an HTTP wrapper that
+keeps the Origin and captcha checks, so the 32 existing call sites are unchanged.
+The broad-refactor risk listed below did not materialise.
+
+**The default policy floor grants nothing.** `builtinDefaultFunctionPolicy()`
+returns an empty `KeyScope`: a newly registered function can run, log and call
+out, but reaches no collection until an admin grants one. The failure mode of
+the permissive choice is silent - a function quietly reading data nobody meant
+to expose looks exactly like a function that works. Marked `TODO(policy)` for
+confirmation, since it trades real developer friction for that.
+
+**A code push ignores, rather than validates, an incoming policy.** A
+validating version would have to answer "is this narrower than what is stored?",
+and subset-checking a glob-and-op-set grammar is where a privilege escalation
+bug would live. Ignoring the field has no such failure mode.
+
+**QuickJS: quickjs-ng, pinned to an exact tag.** Bytecode carries no version
+stamp, so an upgrade makes a cached blob misread rather than fail. `JsBytecode`
+is an in-process cache only; persisting it would need a build fingerprint.
+
+**The runner does not link `vectorapi_core` yet.** The design says it does. The
+execution core deliberately links neither it nor the database client, which is
+what lets it build and test on the dev host. The host-binding workstream adds a
+target that links both on top of `runner_core`; it does not move the dependency
+into the core.
+
+**`BUILD_RUNNER` is off by default.** The runner vendors QuickJS over the
+network at configure time, and neither an ordinary build nor the existing test
+cycle may start depending on a GitHub fetch.
+
+### Still open
+
+- **Status mapping at the dispatch edge.** `timed_out` and `out_of_memory` are
+  classified, but nothing says what HTTP status each becomes. `errors.hpp`
+  currently has no 504.
+- **The SSRF replace-vs-union question.** A custom blocklist replaces the
+  built-in defaults, so adding one CIDR silently unblocks loopback, RFC1918 and
+  the cloud metadata endpoint. The alternative is always-union plus an explicit
+  opt-out.
+- **TOCTOU on `ctx.fetch`.** The guard resolves the name and the HTTP client
+  resolves it again. `ctx.fetch` must connect to the approved address with a
+  `Host:` override, and must ignore `http_proxy`/`https_proxy`, or the rebinding
+  window stays open.
+- **Return shape** of the default export, and who validates it.
+- **Unhandled rejections** in background microtasks after the handler returned.