Skip to content

feat(auth): a request narrows its key to the scopes it names, a key can require that, manage get reads up to 16 ids at once, and keyset-provision mints a set of narrowed keys - #595

Open
GottZ wants to merge 15 commits into
rootfrom
feat/access-binding-server

Conversation

@GottZ

@GottZ GottZ commented Dec 6, 2026 •

Copy link
Copy Markdown
Owner

What this changes

Per-request scope narrowing. X-Context-Read-Scopes: a,b,… (1 to 8 scopes the key reads) and optionally X-Context-Write-Scope: a (one of them, writable by the key) narrow a request's key. The Auth middleware decides this once, before any handler (handler.narrowAuth); handlers get a copy of the key's AuthResult with the named read set, no server-admin tier and role member. home_scope (backend chain, quota, settings overlay, archive read) and the #555 request key stay the key's own. A narrowed request may only use POST /api/query, /api/search, /api/store, /api/manage (get, type-list) and GET /api/whoami. The client chooses the narrowing: it shrinks what one request may do and never widens it, and the boundary stays the key's own scope set. whoami adds write_scopes, confirm_writes, narrowed, rate_limit_write and scope_narrowing.

Required narrowing per key (migration 198). context_api_keys.scope_narrowing is either optional (every existing key, and the default of api-key-create) or required. A required key answers every request without a narrowing with 403 scope_narrowing_required on every route behind the API authentication (reads, writes, /mcp, the session surface, the event streams), except GET /api/whoami. The sign-in flows (POST /auth/login, POST /authorize with /token, the SSO key selection) accept such a key and mint a session or tokens; those carry the requirement, so without a narrowing they too reach only GET /api/whoami. The value is set through api-key-create and api-key-update (tenant-admin), listed by api-key-list, and minted by ctx keys create --require-narrowing. Both event streams end at their next re-auth once their key requires narrowing. /register in admin mode applies the narrowing rules itself.

manage get with ids. {"action":"get","ids":[…]} reads up to 16 blocks and returns one entry per id, in request order. Each entry is either the block object a single get returns (fields and the content window apply) or a miss {id, code, error} with not_found, invalid_id or ambiguous_id. A miss never fails the request. Ids resolve as they do in a single get. All full ids are read with one statement (store.GetBlocksOmitting, id = ANY($1::uuid[])), sharing select list, scan and visibility with the single read. An id the caller may not see answers like an id with no block, and only delivered blocks enter the read record.

keyset-provision. This new manage action (tenant-admin; a server-admin may name data.tenant_id) creates up to 64 scopes and 64 keys in one transaction under the tenant row lock, all or nothing. Keys are member keys with exactly the scopes named and their own principal, minted through insertApiKeyTx with the caller's audit stamp. replace_label: true deactivates the tenant's active member keys of that label in the same transaction. Plaintext keys appear only in the answer. No migration.

Why

The Hermes plugin ctx_checkpoint uses these parts to bind groups of a bot's users to their own scopes of one tenant; the plugin part comes in a separate PR.

  • Narrowing. The client names the group's scopes on every request and checks the echo. A group key is minted with exactly the group's scopes, so the key's scope set is the boundary; required makes a missing narrowing fail closed — an old client, a client that forgets the headers, or another tool that sends none gets nothing but whoami. It is no boundary against whoever holds the key and sends the headers: they reach, request by request, everything the key may read. Rejected alternative: a scope parameter per handler, which would touch the 30 files that read ReadScopes (112 reads), each a chance to miss one.
  • ids. The plugin renders up to 16 base blocks per group. At 2 000 groups and a 900 s render cache, that is about 2.2 requests per second instead of 36 (computed, not measured). Rejected alternative: resolving prefixes in the same statement (unnest … WITH ORDINALITY plus a LATERAL range probe), where array-bound ranges can lead the planner off the primary key.
  • keyset-provision. Done one call at a time, an interrupted run leaves half a set, a repeated run leaves two active keys per label, and limits are checked per call instead of per set. Rejected alternative: a fixed layout per community.

Behaviour changes (intended)

  • New headers and echo. Besides the two request headers, every answer to an accepted narrowing carries X-Context-Narrowed: <read,…>;<write>, including refusals from handlers. A narrowing that the middleware refuses gets no echo.
  • New refusal codes.
    • scope_narrowing_invalid (400): malformed or repeated headers, an empty element, a scope named twice, or more than 8 scopes.
    • scope_narrowing_route (403): a route or manage action outside the list. /mcp refuses every narrowed request. A listed route spelled with percent escapes matches no route and answers 404 before authentication, with no data.
    • scope_narrowing_required (403).
    • A narrowing beyond the key's read or write rights is 403 scope_denied, and so is a narrowed write without a write scope.
  • Required keys. Unnarrowed, a required key reaches GET /api/whoami and the sign-in flows, whose session and tokens carry the requirement; every other route answers 403 scope_narrowing_required. A switch applies from the next authentication.
  • Owner rule. Only an owner or a server-admin may switch an owner key to required; a tenant-admin gets 403. A required owner administers nothing and no longer counts as an owner. The last active optional owner cannot be demoted, deactivated, revoked or switched to required (409). api-key-update and api-key-delete now decide on the target as read under the tenant lock, closing the same pre-existing race for role and active.
  • keyset-provision default and refusals. Mints scope_narrowing: required unless the call names optional; api-key-create stays optional. Refusals: 403 for a foreign or unknown scope (same answer); 400 for malformed input, an unknown field, a duplicate label, a top-level id or more than 64 entries; 429 with limit, count, requested; 409 when the tenant is being deleted or an owner, admin or server-admin key holds the label. None carries a code, like other manage actions. Action table: 116 → 117 actions.
  • get with ids. These are refused with 400 invalid_body before any lookup: ids together with id, an empty list or more than 16 ids, an element that is not a string (including null), and include_archived. ids: null counts as not sent. A NUL in a top-level ids of any manage action is now 400.
  • Guard verdicts in answers. The duplicate guard matches blocks across the scopes of a tenant, so a block's guard verdict can name a block the caller cannot read. Every answer that returns block metadata now drops the three verdict keys guard_matched_id, guard_similarity and guard_is_cross_scope when the matched block lies outside the request's read scopes (the named ones under a narrowing). New for the write answers of POST /api/store and /api/store/batch: before, an overwrite answered with the stored verdict, the id of a block in another scope included, also to a key that cannot read that scope. New for the read paths (get, full search/list rows, issue reads) and the manage update answer: they dropped only guard_matched_id and now drop the similarity and the cross-scope flag with it. A caller that reads the matched block's scope gets the verdict as stored, byte for byte. The block's own guard_status stays, and guard-list keeps its similarity column for a partner shown [redacted] (the review page sorts by it) — documented as what remains visible.
  • Clients without the new headers (holding an optional key) see no change except additions and the guard-verdict rule above: five whoami fields after capabilities (optional in TS WhoamiResponse); scope_narrowing in the answers of api-key-create/-update/-list and in api_key audit rows after 198; one more field named in the nothing to update text of api-key-update. A single-id get is byte-identical: 35 answers (plain, narrowed, archived, prefixes, misses, fields/window, refusals) compared base vs. change.

Migration

198 adds context_api_keys.scope_narrowing TEXT NOT NULL DEFAULT 'optional' CHECK (optional | required). It extends the api_key audit projection and trigger and rebuilds ctx_auth_by_id and ctx_auth with it as their last column. ctx_auth_by_id reads the value from the row its last_used_at update locks, and sentinel rows read required.

No row is rewritten. The CHECK scans the table once under ACCESS EXCLUSIVE, and authentication waits meanwhile. Measured: 46 ms at 100 000 keys and 215 ms at 1 000 000 keys, where an authentication that started 50 ms in waited 167 ms. Before the scan, the ALTER TABLE may wait for its lock behind a transaction holding the key table for up to lock_timeout (3 s), and every authentication queues behind it meanwhile; then the boot fails and the next start retries.

Binary rollback: an older binary still works on 198 (it uses named selects), but it serves required keys without the requirement. docs/operations.md gives the query that counts and names the active required keys before a rollback, with what to do with them (deactivate, or accept that each reaches its whole scope set). The schema way back is in the header and run by TestMigration198WayBack.

Consumers of the changed contracts

Changed Callers and readers Covered by
narrowed AuthResult, writableBlockScopes, resolveWriteScope, resolveGrants, readBlockForGet every handler behind Auth (40 call sites of writableBlockScopes); reachable narrowed: query, search, store, manage get/type-list, whoami TestC1* (20), TestNarrowAuth* (2)
whoami (+5 fields) SPA (fields optional, unread), CLI ingest/backends seed (read other fields), plugin ctx_checkpoint TestWhoamiGoldenShape, TestC1Whoami*, TestC2*
ctx_auth/ctx_auth_by_id (+1 column), api_key audit projection auth.Authenticate, auth.AuthenticateByID (named selects), older binaries, GET /api/audit TestMigration198*, TestKeyAudit*, TestAuditClassification*
insertApiKeyTx, MintKeyWithQuota, UpdateApiKey, owner rules api-key-create/-update/-delete, MintOwnerKey, ProvisionProject, keyset-provision TestC2*, TestOwnerRulesReadTheTargetUnderTheLock_*, TestUpdateApiKey*, TestDeleteApiKey*
guard verdict in answers (guardMatchReadableSQL, guardRedactedMetadataSQL, store.RedactGuardVerdicts) POST /api/store, /api/store/batch; get (one id, ids), full search/list, MCP get/search with content, issue reads, manage update; no reader of block metadata uses guard_similarity/guard_is_cross_scope (SPA and plugins read guard-list) TestGuardVerdict* (3, verdict from a real guard run), TestGuardMatchedIDRedacted*, TestRedactGuardVerdictsFailsClosed
sign-in flows with a required key /auth/login, /authorize + /token + refresh, SSO TestC2RequiredKeyThrough* (2)
stream re-auth, /register admin mode /api/events, /api/project/events, OAuth dynamic client registration TestW9SSERequiredNarrowingEndsStream, TestEventsReAuthEndsStreamOnRequiredNarrowing, TestDCRRegister*
manage get with ids, store.GetBlocksOmitting plugin CtxClient.get_blocks TestC4* (8), TestGetBlocksOmitting_CostIndependentOfCorpus, plugin run
readBlockByID (select list, scan, visibility extracted), manageRequest.IDs single get (CLI, web, MCP), every manage body 35-answer byte probe, TestGetOptionsLeaveColumnsUnread, TestManageNULFieldReadsEveryField
keyset-provision, store.ProvisionKeyset, action table (+1 row) plugin access provision; handleManage, tier gate TestC3* (19), TestKeyset* (store), TestManageTable_*, TestManageActionFixture_*

Cost

  • Narrowing. One header lookup per request, or a set comparison over at most 8 scopes. No extra query: the column comes with ctx_auth_by_id.
  • get with ids. Statements: the block-grant set (none when narrowed), one per prefix, and one read for all blocks. 16 full ids take 2 statements unnarrowed, 1 narrowed (pinned by a statement tracer). The read costs 9 buffers for 16 ids at both 2 000 and 20 000 blocks in scope.
  • keyset-provision. 41 ms for 64 new scopes and 64 keys, and 34 ms for the same set with 64 replacements, in a tenant with 20 000 other keys and 2 000 other scopes. That is how long the tenant lock is held; scope and key writes of the tenant, inserts referencing its row, writes of never-embedded types into its scopes and authentication of replaced keys wait for it, other authentications do not.
  • Owner rules. api-key-update/-delete add one primary-key read.
  • Guard verdict in write answers. One statement per /api/store or /api/store/batch answer that carries a verdict (a primary-key probe per verdict), none otherwise.
  • Web bundle. Unchanged at 768 927 of 769 000 bytes.

Verification

  • Red before. Narrowing: 18 of 20 integration tests and 2 unit tests on inert stubs (the other 2 pin unchanged behaviour). Required narrowing: 5. get with ids: 3 (Missing required field: id). keyset-provision: 16 router tests (400 Unknown action), and the required default test before its one-line change.
  • Green after. TestC1* 20, TestNarrowAuth* 2, TestC2* 6, TestMigration198* 2 plus 1 measurement, TestC4* 8, TestC3* 19, 8 store tests including four interleavings on a second connection, and 12 rounds of concurrent replacements of one label. Every new test ran -count=5 with and without -race.
  • Mutants (each restored, tree checked clean): narrowing 18/18, required narrowing 13/13, review and lock fixes 8/8, get with ids 18/18, keyset-provision 33/33.
  • Independent review of the whole diff. No critical or high finding; one medium and five low, handled:
    • (Medium, pre-existing) The answers of /api/store and /api/store/batch carried a block's guard verdict unredacted, the id of a block in another scope included. Fixed (above, "Guard verdicts in answers"); three tests on a verdict from a real guard run (vectors written by the query backfill, guard.RunGuardBatch) were red for the write answers and for similarity and cross-scope flag on the read paths, then green; keys that read the matched scope get the verdict unchanged.
    • (Low) The read paths kept similarity and the cross-scope flag of an unreadable match; no reader of block metadata uses them, so they go with the id (the guard list keeps its similarity column, documented).
    • (Low) The sign-in flows take a required key: run for the web session, the access token and a refreshed one — each reaches only whoami unnarrowed (TestC2RequiredKeyThrough*); the docs list exactly what such a key reaches.
    • (Low) Docs and this text: the narrowing is the client's choice, the boundary stays the key's scope set; the rollback of 198 counts and names the required keys first (SQL); the migration's lock wait (up to 3 s) is named.
    • A percent-escaped spelling of a listed route answers 404 before authentication with no data (test).
    • Mutants of these fixes: 7 of 7 red (each write answer without the redaction, the read SQL dropping only the id, the write redaction dropping only the id or ignoring the scopes, the redaction not failing closed, a session or token without the requirement).
  • Review findings (earlier rounds). A fresh reviewer agent read each part's diff. Fixed:
    • (High) A tenant-admin could switch an owner key to required and lock it out of administration; now that counts as removing owner power, and the last-owner rule counts only active optional owners.
    • (High) Two audit tests on schema 160 broke with SQLSTATE 42703. (Low) Event streams survived a switch to required; /register bypassed the rules.
    • Deadlock in the lock order: keyset-provision took the migration-176 advisory groups out of order; a second-connection test deadlocked (40P01) until they were locked sorted before the INSERT.
    • A silently ignored top-level id (keyset-provision) and a null element in ids are now 400.
    • Checking the lock order also found the owner rules deciding on a read taken before the tenant lock; two interleaving tests were red until the target was read again under it.
  • Gate. On the final state, bash go/gates.sh wave --final returned rc 0: build, vet, lint, doccheck, short, census-tests, race (0 races), integration 9/9, python, web, deadcode, deadcode-testonly. New tests also ran -count=5 with and without -race.
  • Plugin run. Against a throwaway ctxd built from this branch (own database, stub embeddings), 24 plugin tests passed. They covered access provision through keyset-provision (required member keys, unnarrowed search 403, replacement, 429 at max_keys with nothing created), the echo on every route the plugin uses, refusals outside the route list, reads and writes confined to the group's scopes, and one get with ids for base blocks. Against v5.94.0, which has no narrowing, no group binds. 6 of 6 plugin mutants were killed. The run also led to a docs fix: whoami.rate_limit_write follows the settings overlay of the key's home scope, not of its tenant.

Not verified

  • rate_limit_write overrides (known limit). An override set on one scope of a tenant does not reach keys whose home is another scope of the same tenant: the owner set 40, and a group key reported the _global 100. This is pre-existing settings-resolution behaviour and is unchanged here; a follow-up issue takes it up.
  • Graph under narrowing. Graph expansion, applyClusterBoost and foldAggregates under a narrowing with the graph enabled were read, not run.
  • Migration at scale. The lock window at 10 M keys is extrapolated (about 2 s). A previous release binary on 198 was checked only at the SQL level.
  • get with ids at scale. Not measured beyond 20 000 blocks. Prefixes are not batched. Timing of "invisible" versus "absent" was only read.
  • keyset-provision at scale. Not measured at several hundred thousand keys per tenant (there is no label index), or with tenant block types registered.
  • SSO with a required key. The SSO session is minted through the same path as the login session that was run; the SSO flow itself was read, not run.
  • Graph under narrowing, see above; the guard-verdict redaction of the graph paths was not checked separately (they return no block metadata).

🤖 Generated with Claude Code

GottZ and others added 12 commits December 6, 2026 00:59
…tubs, fakes of ctx and the Hermes host, and the red tests of P-A to P-G behind a per-cluster shield

The plugin side of per-group ctx bindings is split into clusters P-A to P-G that are built in
parallel; this commit fixes what they build against. New modules hold the final data forms and
inert stubs: memory/access.py (field schema, detection, decision table, markers), memory/narrowing.py
(client narrowing, whoami proof), memory/base_blocks.py (the access_group_fields hook),
memory/access_cli.py (operator tools); CtxClient takes a narrowing and gains get_blocks,
status.py gains record_access/read_access, checkpoint.py gains window_writes. Nothing calls them
yet, so the plugin behaves as before (both suites unchanged: 763 passed + 2 skipped, 655 passed).
tests/fakes holds a ctx server with the target narrowing semantics and the Hermes surface of the
access-group core change (aligned to its code, not to the draft). Each cluster's red tests carry a
marker; while the cluster is listed in tests/fakes/s1_pending.py they are strict xfails that only
an assertion about the missing behaviour satisfies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… and call sites, the red tests of C-1 to C-4 behind per-cluster build tags

The contract the four server clusters of the access-group binding build
against, with behaviour unchanged: auth.Narrowing and the AuthResult fields
Narrowed and ScopeNarrowing, the scope_narrowing values, narrowAuth (headers
ignored) in the Auth middleware between the validity check and the context
value, fed only to the handlers while store.WithRequestKey keeps the
unnarrowed key, the action check of a narrowed /api/manage request on the one
decoded action, and insertApiKeyTx's scopeNarrowing parameter (every caller
passes optional; the column is migration 198's).

The red tests drive the production router and stay out of every gate behind
`integration && s1red_cN`; a cluster enables its file by shortening that line
to `//go:build integration`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nd write scope headers on a closed route list, echoed, and whoami reports the write side

A request may carry X-Context-Read-Scopes (1 to 8 scopes the key reads)
and X-Context-Write-Scope (one of them, which the key may write). The Auth
middleware decides the narrowing once, before any handler runs, and hands
the handlers a copy of the key's AuthResult: the named read set in header
order, no server-admin tier, tenant role member, and the narrowing. The
home scope and everything else stay the key's, so backend chain, quota,
settings overlay and archive read are the key's whatever scope comes
first, and the #555 write recheck still holds the unnarrowed key.

Three places read the narrowing: writableBlockScopes (its write scope
alone), resolveWriteScope (a write without a scope goes there, without
one it is scope_denied) and resolveGrants (no block grants). A narrowed
request may take POST /api/query, /api/search, /api/store, /api/manage
(get, type-list) and GET /api/whoami, compared by method and exact path;
everything else is 403 scope_narrowing_route, a malformed narrowing 400
scope_narrowing_invalid. Every answer of an accepted narrowing carries
X-Context-Narrowed. An archive read whose narrowing names no own scope
finds nothing instead of reaching the store's empty-scope guard.

whoami grows write_scopes, confirm_writes, narrowed and rate_limit_write
(after the tenant overlay); TS WhoamiResponse follows with optional
fields, the built bundle is byte-identical. The S1 red tests of C-1 are
switched on, with the probes they left open (a scope named twice, the
read set whoami reports, the overlay and the backend chain of a grant
scope first, an escaped path).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rowing on the key (migration 198), refused unnarrowed but for whoami

Migration 198 adds context_api_keys.scope_narrowing TEXT NOT NULL DEFAULT
'optional' CHECK (optional | required), rebuilds ctx_auth_by_id and
ctx_auth with it as their last column (read from the key row the
last_used_at update locks; the sentinel rows read 'required'), and adds
it to the api_key audit projection and update trigger, so a switch is an
audited update. Every existing key stays optional.

A required key answers every request without X-Context-Read-Scopes with
403 scope_narrowing_required — reads, writes, /mcp, the session surface —
GET /api/whoami excepted, which reports scope_narrowing. The check sits
in narrowAuth beside the narrowing it demands; /register in admin mode,
which resolves its key outside Auth, applies narrowAuth too, and both
event streams end at their next re-auth once their key requires it.
api-key-create and api-key-update take scope_narrowing (tenant-admin,
like write_scopes; any other value is 400), api-key-list lists it, ctx
keys create takes --require-narrowing.

A key that requires narrowing administers nothing, so on an owner key it
is owner power: a tenant-admin cannot switch an owner key to required,
and the last-owner rule of update and delete counts only owners that are
active and optional. Both decide on the target as read again under the
tenant row lock, not on the read before it (a concurrent switch of role,
active or scope_narrowing raced the owner guards).

insertApiKeyTx names the column only for a required key, so the mint
paths keep working on schemas before 198 (the migration tests mint keys
there); MintKeyWithQuota and UpdateApiKey take the value; the two key
audit tests on a 160 database call ctx_auth directly. The S1 red tests
of C-2 are switched on; added: the way back of the header, the lock
window measured at 100 000 and 1 000 000 keys (46 ms, 215 ms), an
authentication behind an uncommitted switch, the owner rules with and
without a concurrent key write, /register, the streams.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…h one statement — misses are entries, an unseen id answers like a missing one (C-4)

POST /api/manage {"action":"get","ids":[...]} answers {action, success,
blocks}: one entry per asked id, in the order asked — the object a single get
answers under "block" (fields and the content window apply to each), or a
miss entry {id, code, error} with the id as asked: not_found for an unknown,
foreign, ungranted or archived id alike, invalid_id for a short prefix,
ambiguous_id with matches. A miss never fails the request.

Each id resolves as the id of a single get does (ResolveBlockID over the read
scopes and the block grants), so a narrowed request reads its named scopes and
no grant. The blocks of all full ids are read with one statement
(store.GetBlocksOmitting: id = ANY($1::uuid[]), a primary-key probe per id),
which shares the select list, scan and visibility condition of GetBlock
(blockByIDColumns, scanBlockByID, liveVisibleSQL; the single read's SQL text
is unchanged). Only delivered blocks are booked in the read record, each once.

ids beside id, an empty list or more than 16 ids, anything but a list of
strings, and include_archived are a 400 invalid_body before any lookup; ids
sent as null counts as not sent, and a body without ids answers byte for byte
as before. The S1 contract tests of C-4 are switched on; probes for refusals,
entry parity with the single get, prefixes and misses, narrowed misses, the
read record and the statement count, unit tests, and a cost pin of the read
(custom and generic plan, random_page_cost 1.1 and 4).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…one transaction under the tenant lock — member keys with their own principal, replace_label for one active key per label

A new manage action, tenant-admin in the caller's own tenant (a
server-admin may name data.tenant_id): scope-create and api-key-create
for up to 64 scopes and 64 keys at once, all or nothing.
store.ProvisionKeyset takes the tenant row lock first and reads status,
max_scopes, max_keys, the owners of every named scope, the roles of the
keys replace_label would deactivate and the active key count under it;
a scope of another tenant, or one the tenant neither has nor creates, is
a 403; a set past max_scopes or max_keys a 429 with limit, count and
requested. The new scopes' groups of migration 176 are locked in sorted
order before the one INSERT, so assigning several scopes keeps the order
the scope trigger keeps (row by row it could deadlock with a block
write). Keys go through insertApiKeyTx (role member, a fresh principal,
exactly the scopes named, the audit row of the caller). replace_label
deactivates the tenant's active member keys of the label in the same
transaction and refuses a label an owner, admin or server-admin key
carries, so it never takes a key past the owner rules of api-key-delete.
A new scope refreshes the quota accountant like scope-create. No
migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…wing unless the call names optional

The action exists for the keys of restricted groups (design §7.3 C-3:
keys with required and a label), so a key whose scope_narrowing the call
leaves out — absent or empty — is now minted required: unnarrowed it
answers nothing but whoami. optional is minted only when the call names
it; api-key-create keeps optional as its default. The set's keys are
member keys, so the owner rule of migration 198 (required on an owner
key takes its administration) does not apply to them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…contract stubs land with the plugin

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… key's home scope, not the tenant

A run of the Hermes plugin against a server built from this branch showed that an override an owner sets on their own scope does not reach keys whose home scope is another scope of the tenant.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…home scope, as docs/api.md does

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@GottZ
GottZ requested a review from W4-NERF as a code owner December 6, 2026 05:35
@coderabbitai

coderabbitai Bot commented Dec 6, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 27 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9f40f919-e033-440e-8855-41f85be236c6
Commits

Reviewing files that changed from the base of the PR and between bcf686a and 8e91a3d.

Files selected for processing: 72

  • docs/api.md
  • docs/cli.md
  • docs/mcp.md
  • docs/multi-tenancy.md
  • docs/operations.md
  • docs/security.md
  • go/cmd/ctxd/guard_verdict_answers_integration_test.go
  • go/cmd/ctxd/keyset_provision_c3_integration_test.go
  • go/cmd/ctxd/keyset_provision_c3_more_integration_test.go
  • go/cmd/ctxd/manage_get_ids_c4_integration_test.go
  • go/cmd/ctxd/manage_get_ids_c4_more_integration_test.go
  • go/cmd/ctxd/narrowing_c1_integration_test.go
  • go/cmd/ctxd/narrowing_c1_more_integration_test.go
  • go/cmd/ctxd/scope_narrowing_required_c2_authflow_integration_test.go
  • go/cmd/ctxd/scope_narrowing_required_c2_integration_test.go
  • go/cmd/ctxd/scope_narrowing_required_c2_more_integration_test.go
  • go/cmd/ctxd/server.go
  • go/internal/auth/auth.go
  • go/internal/cli/commands.go
  • go/internal/handler/context_manage.go
  • go/internal/handler/context_manage_writescope_w3_integration_test.go
  • go/internal/handler/context_store.go
  • go/internal/handler/errcode.go
  • go/internal/handler/events.go
  • go/internal/handler/get_archived.go
  • go/internal/handler/get_fields_integration_test.go
  • go/internal/handler/get_ids.go
  • go/internal/handler/get_ids_test.go
  • go/internal/handler/ingest_target_scope_integration_test.go
  • go/internal/handler/keyset_provision.go
  • go/internal/handler/keyset_provision_quota_integration_test.go
  • go/internal/handler/keyset_provision_test.go
  • go/internal/handler/manage_action_fixture_test.go
  • go/internal/handler/manage_table.go
  • go/internal/handler/mcp.go
  • go/internal/handler/middleware.go
  • go/internal/handler/narrowing.go
  • go/internal/handler/narrowing_events_test.go
  • go/internal/handler/narrowing_streams_integration_test.go
  • go/internal/handler/narrowing_test.go
  • go/internal/handler/oauth_register.go
  • go/internal/handler/oauth_register_narrowing_integration_test.go
  • go/internal/handler/project_events.go
  • go/internal/handler/store_batch.go
  • go/internal/handler/whoami.go
  • go/internal/handler/whoami_test.go
  • go/internal/schemacontract/manifest.json
  • go/internal/store/api_keys.go
  • go/internal/store/api_keys_audit_integration_test.go
  • go/internal/store/api_keys_insert_test.go
  • go/internal/store/api_keys_mint_quota_integration_test.go
  • go/internal/store/api_keys_owner_interleave_integration_test.go
  • go/internal/store/api_keys_update_integration_test.go
  • go/internal/store/api_keys_write_scopes_integration_test.go
  • go/internal/store/api_keys_write_scopes_test.go
  • go/internal/store/audit_classification_test.go
  • go/internal/store/blocks.go
  • go/internal/store/blocks_get_many.go
  • go/internal/store/get_blocks_cost_integration_test.go
  • go/internal/store/guard_redact_integration_test.go
  • go/internal/store/guard_verdict.go
  • go/internal/store/guard_verdict_test.go
  • go/internal/store/keyset.go
  • go/internal/store/keyset_integration_test.go
  • go/internal/store/migration198_integration_test.go
  • go/internal/store/provision.go
  • go/internal/store/request_key_gate_integration_test.go
  • go/internal/store/request_key_gate_writes_integration_test.go
  • go/internal/store/tenant_prune_schema_integration_test.go
  • go/migrations/198_api_key_scope_narrowing.sql
  • go/web/src/lib/api/types.ts
  • test.sh
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

GottZ and others added 3 commits December 6, 2026 07:17
…request's read scopes — the /api/store and /api/store/batch answers too, and similarity and cross-scope flag with the id

The duplicate guard matches a block across the scopes of its tenant, and its
verdict in the block's metadata names (guard_matched_id) and describes
(guard_similarity, guard_is_cross_scope) the matched block. The read paths
dropped only guard_matched_id when that block lay outside the caller's
scopes; the answers of /api/store and /api/store/batch dropped nothing — an
overwrite keeps the stored verdict and the upsert RETURNING read it raw, so
the answer named a block of another scope, also to a key that cannot read
it and, since #595 lists /api/store for narrowed requests, outside a
narrowing.

One predicate now (guardMatchReadableSQL): the read paths' SQL expression
drops all three keys, and the write answers of /api/store and
/api/store/batch go through store.RedactGuardVerdicts against the
request's read scopes (the narrowed ones under a narrowing), one statement
per answer, fail-closed when it fails. A caller that reads the matched
block's scope gets the verdict as before. guard_status and the guard list's
similarity column stay (documented).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ry the requirement, and an escaped spelling of a listed route gives no data — docs name what such a key reaches unnarrowed

POST /auth/login, POST /authorize with /token (and a refresh) take a key
with scope_narrowing required unnarrowed and mint a web session, a code
and a token pair. The tests run both flows and pin that every credential
they mint reaches GET /api/whoami and, narrowed, the routes of a narrowed
request — every other request answers 403 scope_narrowing_required
(search, query, store, manage, session keys, /mcp). The SSO session is
minted through the same path. A listed route spelled with percent escapes
answers 404 before Auth, with no block, echo or write.

Docs: the exact list of what a required key reaches unnarrowed; the
narrowing is the client's choice and the boundary stays the key's scope
set (required makes a forgotten narrowing fail closed); the rollback of
migration 198 counts and names the required keys first (SQL); the lock
wait of the migration (up to lock_timeout 3 s, authentications queue
behind it) beside its measured run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ts new text — the three verdict keys go as one text[]

TestGetOptionsLeaveColumnsUnread tells a by-id read that reads metadata
from one that skips it by the SQL text of guardRedactedMetadataSQL. That
expression drops guard_matched_id, guard_similarity and
guard_is_cross_scope together since the previous commit, as
"metadata - '{guard_matched_id,…}'::text[]"; the probe now looks for
that text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant