Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
080ea19
feat(gateway): a consumer a server-admin sets to record keeps every r…
GottZ Nov 27, 2026
77c1921
feat(web): the consumer list and detail show a recording consumer
GottZ Nov 27, 2026
5b39461
test(gateway): the recording switch's locked re-check, its stream cap…
GottZ Nov 27, 2026
c3019d2
feat(gateway): the status frame shows what recorded texts hold of the…
GottZ Nov 27, 2026
0a20dbb
feat(gateway): a recorded rerank row keeps its answer; the export's f…
GottZ Nov 27, 2026
86cd661
test(web): the status fixtures carry the recording fields
GottZ Nov 27, 2026
b78ddfe
feat(gateway): a recording consumer's request is held in context_llm_…
GottZ Nov 27, 2026
cc6c2cf
test(gateway): the recording account gets back what a stream's and a …
GottZ Nov 27, 2026
451a334
fix(gateway): recording statements take one of four slots, a stream's…
GottZ Nov 27, 2026
3198712
test(gateway): at most four recording statements run at once while th…
GottZ Nov 27, 2026
3bbbba5
test(gateway): the recording latency probe sends 32 embedding inputs …
GottZ Nov 27, 2026
3c51ee0
test(gateway): the counts-balance test gives its consumer its own id,…
GottZ Nov 27, 2026
85a6aee
fix(llmlog): the retention janitor skips the recordings on a schema w…
GottZ Nov 27, 2026
851e571
fix(gateway): a recording consumer's LLM-log row carries no bodies un…
GottZ Nov 27, 2026
4e73404
fix(handler): model-consumer-update names the recording switch as rea…
GottZ Nov 27, 2026
a44cf27
fix(gateway): an answer of a recording consumer that is not a 2xx is …
GottZ Nov 27, 2026
2620572
fix(gateway): a recorded answer the client does not get is superseded…
GottZ Nov 27, 2026
214549f
fix(gateway): the recording's texts name the embedding vectors as the…
GottZ Nov 27, 2026
4a08d29
fix(gateway): the check between a held answer's commit and its write …
GottZ Nov 27, 2026
efc5cb0
fix(llmlog): the retention clears a refusal's answer whose request bo…
GottZ Nov 27, 2026
0771ec3
fix(gateway): a refused request's row is written while its in-flight …
GottZ Nov 27, 2026
dada1c7
fix(gateway): a captured answer's forced copies are booked once its s…
GottZ Nov 27, 2026
1d4d698
fix(gateway): an answer whose commit ended past the request's deadlin…
GottZ Nov 27, 2026
a069bc9
fix(gateway): the row of a request a panic ended holds the 503 intern…
GottZ Nov 27, 2026
0f4910c
fix(gateway): a held error answer whose key is revoked after its comm…
GottZ Nov 27, 2026
1414216
test(gateway): the recording store double refuses a canceled statemen…
GottZ Nov 27, 2026
f002ea0
docs(gateway): recorded is a process count a deleted row does not low…
GottZ Nov 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions docs/api.md

Large diffs are not rendered by default.

60 changes: 60 additions & 0 deletions docs/operations.md

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions docs/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ How the system defends itself is below. How to **report** a vulnerability — pr

**Rationale.** Before this gate, ANY valid key of any `home_scope` could mint keys for arbitrary scopes — read access to foreign tenants — and the settings/secrets API must not inherit that model. The per-tenant admin tier (owner/admin/member) that layers on top is documented in [multi-tenancy](multi-tenancy.md#admin-tiers).

**Self-service stage (`tierSelfService`, W01-5).** The model consumer actions that grant a new credential — `model-consumer-create` and `model-key-rotate` — carry a fourth stage in the dispatch table: server-admin, and a tenant-admin of its own tenant only while `gateway.enabled` **and** `gateway.tenant_self_service` are on (both default off; a missing config snapshot counts as off). The switch is a setting, so it cannot be a payload-shaped tier function; as a stage of its own the lock sits in the pinned table, and the handlers check the same switch a second time. With the gateway off nobody below server-admin grants anything, whatever the self-service switch says (dark launch). The refusal is the shared `403 admin key required` — no tier, switch or field oracle. Inside `model-consumer-update` the rule is **revoking is always allowed, granting needs a release** ([api](api.md#model-consumer-administration)): narrowing a consumer stays open to tenant-admins; widening it needs self-service; `kind = ctx-peer`, a lower `prompt_sensitivity` (egress of foreign prompts to less trusted backends), `allow_plaintext = true` (credential transport without TLS), a higher `fair_weight` and `admission_lane = urgent` (the GPU is a host-global good) stay server-admin with self-service on. **Peer row tier:** any granting change of a `ctx-peer` consumer is server-admin only. The comparison runs against the row under its lock, so a concurrent server-admin write cannot be undone by a tenant-admin re-submitting the old value.
**Self-service stage (`tierSelfService`, W01-5).** The model consumer actions that grant a new credential — `model-consumer-create` and `model-key-rotate` — carry a fourth stage in the dispatch table: server-admin, and a tenant-admin of its own tenant only while `gateway.enabled` **and** `gateway.tenant_self_service` are on (both default off; a missing config snapshot counts as off). The switch is a setting, so it cannot be a payload-shaped tier function; as a stage of its own the lock sits in the pinned table, and the handlers check the same switch a second time. With the gateway off nobody below server-admin grants anything, whatever the self-service switch says (dark launch). The refusal is the shared `403 admin key required` — no tier, switch or field oracle. Inside `model-consumer-update` the rule is **revoking is always allowed, granting needs a release** ([api](api.md#model-consumer-administration)): narrowing a consumer stays open to tenant-admins; widening it needs self-service; `kind = ctx-peer`, a lower `prompt_sensitivity` (egress of foreign prompts to less trusted backends), `allow_plaintext = true` (credential transport without TLS), a higher `fair_weight` and `admission_lane = urgent` (the GPU is a host-global good) and `record_bodies = true` (every request and answer of the consumer in clear text in `context_llm_recordings`, [below](#gateway-telemetry-v1-v2); also needs `confirm_record_bodies: true`) stay server-admin with self-service on. **Peer row tier:** any granting change of a `ctx-peer` consumer is server-admin only. The comparison runs against the row under its lock, so a concurrent server-admin write cannot be undone by a tenant-admin re-submitting the old value.

**Admin bootstrap** (one-time, host access required). Promote by `id`, never by label — `label` has no UNIQUE constraint and an UPDATE by label would escalate every same-named key, including inactive ones:

Expand Down Expand Up @@ -160,13 +160,14 @@ Every refusal carries `x-should-retry: false`: the same request against the same
- **Request identity.** ctx mints the answer id and a fresh upstream request id per attempt; the client's `X-Request-ID` is only recorded (`metadata.gw.client_req_id`), never sent to a backend — a client-chosen id would become the engine's request id (vLLM) or a correlation handle at a third party.
- **Kill switch and revocation while running.** A watcher per request (streamed or not) ends a running request within 5 s when `gateway.enabled` goes `false` or the alias is disabled or removed; a non-streamed request checks the alias and the grant once more right before the answer is written. The lease is released with the aborted upstream call.
- **Revocation of running requests.** Every request the door accepts runs on a context the door's in-flight registry can end (one registry per process, entries indexed by model key, consumer, tenant and tenant scope, gone when the request ends — a panic included). A key that stops authenticating — revoked, its expiry passed, its consumer deactivated, its tenant suspended, offboarded or pruned, its `tenant_scope` moved to another tenant or deleted (gates 1–4 of `ctx_model_auth`) — ends the requests running on it: `401 invalid_api_key` before anything is written, the error frame `invalid_api_key` in a committed stream; the upstream call is aborted, the lease and the consumer's concurrency slot are freed, and the key's hash leaves the door's known-good set (its next request pays the probe token). Four triggers: `model-key-revoke` and `model-consumer-delete` end them right after their commit and answer how many requests of this process they ended (`cancelled_inflight`); every write that can end a key's validity — psql and other ctx processes on the same database included — fires `NOTIFY ctx_model_access_write` (migration 165), and the registry checks the keys it touches with `ctx_model_auth_live` (one statement); a key's expiry ends its requests at that instant through one timer per key (a rotation's grace moves it through the same signal); and every `gateway.inflight_sweep_interval` (30 s) one `ctx_model_auth_live` statement over the keys of all running requests is the second line behind the signal — and the sweep right after the listener reconnects covers a signal lost while it was away. A failed sweep ends nothing (the next one, or the signal, does). **Boundary:** the registry checks liveness only (gates 1–4); the door's other checks run at a request's entry and are not repeated while it runs. A narrowed policy — `allowed_cidrs` narrowed so the request's client address is outside (gate 5), `allow_plaintext` set to `false` under a plaintext request (gate 6), a withdrawn `all_models`, a withdrawn alias grant (except as below), another `tenant_scope` that still belongs to the tenant, a lower `prompt_sensitivity`, another lane or weight — applies from the next request; none of these writes ends a request that is already running, and none fires the database signal. A running request keeps what it was admitted with (its egress has already happened, an abort would not take it back). A withdrawn grant of a consumer without `all_models` is read again right before a non-streamed answer is written (`404 model_not_found`) and by a stream's watcher when the alias registry changes during the stream; otherwise it too applies from the next request. A key's expiry is the one the request was authenticated with, moved by the database signal; a rotation's grace that lands while the listener is away ends the predecessor's requests at the first sweep after the grace (at most one `gateway.inflight_sweep_interval` late), and an expiry extended by hand in psql during such a gap still ends them at the old expiry (no admin action extends an expiry). The kill switch and a removed or disabled alias still end a running request through the watcher. Every grant read of a running request — and the one at its entry — has the door's 1-second deadline, and the kill switch and the alias registry are checked in memory before it: while the database hangs (an exhausted pool, a locked grants table) the kill switch and a removed or disabled alias still end a running request within one watcher tick (5 s) plus that second, and a new request whose grant read does not answer in time gets `503 internal_error`. With the database down, a revoked key's running requests end through the local action of the same process or at its expiry timer; the signal and the sweep need the database.
- **Telemetry.** The request's one LLM-log row stores only `<class> <status> <code>` as its error, never the backend's body (which can echo the prompt), and bodies only as `gateway.body_logging` allows (see below).
- **Telemetry.** The request's one LLM-log row stores only `<class> <status> <code>` as its error, never the backend's body (which can echo the prompt), and bodies only as `gateway.body_logging` allows; a consumer a server-admin set to record has every request held whole in a table of its own (see below).

## Gateway telemetry (`/v1`, `/v2`)

What the gateway writes about a request, and what it never writes (design 06 §4.6):

- **One body policy.** `gateway.body_logging` is the only switch for prompt and answer bodies of gateway rows in `context_llm_log` — global-only, so no tenant can raise it for itself. `none` (default) stores none; `errors` stores the serialized request and the answer on rows with an error only; `full` on every row, each capped at 64 KiB. Every row is then slimmed as for a tenant without developer mode: a credentials-class row stays sealed under every policy, whatever the tenant's `tenant.devmode` says — and so does a row whose sensitivity is empty or unknown (fail-closed, logged as a wiring defect). Embedded NUL bytes and invalid UTF-8 are cleaned before the write, so a crafted body cannot make the row — and its attribution — vanish.
- **One body policy.** `gateway.body_logging` is the only switch for prompt and answer bodies of gateway rows in `context_llm_log` — of every consumer, a recording one (next point) included — global-only, so no tenant can raise it for itself. `none` (default) stores none; `errors` stores the serialized request and the answer on rows with an error only; `full` on every row, each capped at 64 KiB. Every row is then slimmed as for a tenant without developer mode: a credentials-class row stays sealed under every policy, whatever the tenant's `tenant.devmode` says — and so does a row whose sensitivity is empty or unknown (fail-closed, logged as a wiring defect). Embedded NUL bytes and invalid UTF-8 are cleaned before the write, so a crafted body cannot make the row — and its attribution — vanish.
- **The one exception: a recording consumer (migration 197, issue #571).** A model consumer with `record_bodies` on has every request it sends through the gateway held in `context_llm_recordings` — chat (a stream included), embeddings, rerank, and every request the gateway refuses after the door accepted its key: the body **as the gateway read it, byte for byte** (whatever `gateway.body_logging`, the alias, the consumer's `prompt_sensitivity`, the body scan or `Ctx-Sensitivity` say — no cut, no credentials seal), the answer the client got (a non-streamed chat or rerank answer; a stream's relayed lines; the error body of every answer that is not a `2xx`, a backend's relayed rejection included; no embedding vectors), the status and the gateway's code. **Such a row can carry credentials in clear text** — a password or key a client puts into a prompt is stored as sent. Only a server-admin can switch it on (also with self-service, and only with `confirm_record_bodies: true`); switching it off is open to the consumer's tenant-admin; both are audited. **No ctx surface reads the table's bodies:** no REST, MCP, CLI or web route, no export, no pipeline (distill, dream, digest) — `TestRecordingsReadersCensus` fails on any production statement that names the table outside its writer and the retention janitor; a server operator reads them in the database ([operations — Recording a consumer](operations.md#recording-a-consumer)). The consumer's `context_llm_log` rows carry **no bodies under any `gateway.body_logging` value** — the recording is the one place of its request and answer, so no reader of the LLM log (its list, detail and export) has them — and are marked `metadata.gw.recorded` with the `recording_id`; their other columns are those of every consumer's. **Held before served:** the request is committed to the table before the first backend attempt; a request that cannot be held — the database refuses it or does not answer within 5 s, or the recording's memory account has no room within the request's wait budget — is answered `503 recording_unavailable` (`x-should-retry: true`, `Retry-After: 1`) and reaches no backend; a non-streamed answer the table does not take is that `503` instead of the answer, and a request that stops being served while its answer is committed (a key revoked, a consumer deactivated) — or whose deadline passes during the commit — gets the refusal, never the answer (an error answer held for its row likewise, when the key is revoked before it goes out) — its row then holds that refusal. One case is left: when the answer's commit went through and the write of the superseding refusal fails as well, the row keeps the answer and its `200`, so a row's `200` alone does not prove the client got the answer; such a request counts as `unfinished` and its `ERROR` line names the recording ([operations — Recording a consumer](operations.md#recording-a-consumer)). **What the switch does not change:** the required sensitivity, the chain and its egress rule, the body scan and its `413`, the limits, the in-flight budget's bookings and the answer are the same with and without it — the one new refusal is `recording_unavailable`, and every database write of the recording is in the request's time; deactivating and reactivating the consumer (the switch stays as it was); every other consumer (no stage, no write, no wait — their requests pass the recording stage untouched); the retention — the bodies are NULLed after `scheduler.llmlog_retention_days` (90) like every body; and a database backup (`backup.sh`), which carries them like every other content of the database.
- **Error redaction.** The `error` column of a gateway row holds only class, status and ctx code. The upstream response body (which can echo prompt fragments, and which tenant-admins would read in the LLM log list) never reaches it; class and code must have the shape of vocabulary words (lower snake case, at most 64 characters), anything else is stored as `[redacted]`; the writer takes the code from the gateway's own code vocabulary, never from the upstream answer.
- **One identity.** A gateway row is attributed to the consumer (`consumer_id`); a knowledge key id that reached the row anyway is cleared with an ERROR line, and the database refuses any row carrying both. The model key id is kept in `metadata.gw.model_key_id` for key-leak forensics, never as a column.
- **Access log.** A successful request is one `gateway request` line with ids, op, alias, status, token counts and timings (`gateway.access_log`, default on) — no consumer label, no content, never a key, its hint or a query string. Refusals are counted per (consumer, reason — a code of the gateway or door vocabulary, else `http_<status>`) and logged as one `gateway rejections` WARN line per minute with the count, so a flood of `401`/`429` answers cannot rotate the error and security lines out of the 50 MB × 3 container log. The global request log stays silent for these requests.
Expand Down
8 changes: 7 additions & 1 deletion go/cmd/ctxd/gateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,9 @@ type modelGateway struct {
// counts top_consumers_1h for the status (W06-16).
events *usageevents.Recorder
ring *handler.ConsumerRing
// recorder is the recording stage of /v1 and /v2 (issue #571): one per
// process, over the process pool (llmlog.Recordings).
recorder *oai.RecordingStage
}

// usageEventsFlushTimeout bounds the final flush of the usage events at
Expand Down Expand Up @@ -263,6 +266,9 @@ func newModelGateway(pool *pgxpool.Pool, cfgStore *config.Store, meterClock ...f
usage: usage,
binder: auth.PeerBindings{Pool: pool},
requirePeerHop: federationRequirePeerHopGetter(cfgStore),
recorder: oai.NewRecordingStage(llmlog.Recordings{Pool: pool}, handler.ConsumerAuthFromContext, get, func() time.Duration {
return cfgStore.Snapshot().Dispatch.ExternalMaxWait //nolint:forbidigo // MT 06 BLIND: dispatch.external_max_wait is global-only (one dispatcher per process); the recording's wait for room is the wait budget of every consumer alike.
}),
}
}

Expand All @@ -272,7 +278,7 @@ func newModelGateway(pool *pgxpool.Pool, cfgStore *config.Store, meterClock ...f
// the in-flight budget (stage 5). routes are the group's endpoints.
func (g *modelGateway) group(ingress *fedhop.Ingress, maxDepth func() int, routes []modelRoute) modelGroupDeps {
return modelGroupDeps{
access: g.access, gate: oai.EnabledGate(g.settings), door: g.door, ingress: ingress, maxDepth: maxDepth,
access: g.access, gate: oai.EnabledGate(g.settings), door: g.door, recorder: g.recorder, ingress: ingress, maxDepth: maxDepth,
binder: g.binder, requirePeerHop: g.requirePeerHop, events: g.peerNoter(),
inner: []func(http.Handler) http.Handler{
handler.MaxBodySizeStrictWith(func() int64 { return g.settings().MaxRequestBytes }, oai.RefuseRequestTooLarge),
Expand Down
12 changes: 11 additions & 1 deletion go/cmd/ctxd/model_group.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ type modelGroupDeps struct {
// failure lock, probe bucket and DB semaphore, so two groups never hold
// twice the database share.
door *handler.ModelDoor
// recorder is the recording stage right behind the door (issue #571,
// oai.RecordingStage): a recording consumer's requests are held before
// they are served; every other consumer passes it untouched. nil mounts
// none — a recording consumer's request is then refused at its route
// (fail-closed), never served unrecorded.
recorder *oai.RecordingStage
// ingress is the federation-ingress registration of the router the group
// is mounted on (F-W8, design/04 §4.6): mountModelGroup marks it, the
// boot assert and the gateway.enabled settings write read it. The
Expand Down Expand Up @@ -104,7 +110,11 @@ func mountModelGroup(r chi.Router, prefix string, deps modelGroupDeps) {
Binder: deps.binder, RequirePeerHop: deps.requirePeerHop, Events: deps.events,
})
r.Route(prefix, func(g chi.Router) {
g.Use(deps.access.Handler, oai.Recover, deps.gate, deps.door.Handler, loopGuard, peerIngress)
g.Use(deps.access.Handler, oai.Recover, deps.gate, deps.door.Handler)
if deps.recorder != nil {
g.Use(deps.recorder.Handler)
}
g.Use(loopGuard, peerIngress)
g.Use(deps.inner...)
g.NotFound(oai.NotFound)
g.MethodNotAllowed(methodNotAllowed(g, routeMethods(deps.routes)))
Expand Down
Loading
Loading