Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(grants): OAuth clients take --sources none and per-client takes holders
garrytan931c05726961
diff --git a/TODOS.md b/TODOS.mdindex 47d9c605e6..8f9eee6f22 100644--- a/TODOS.md+++ b/TODOS.md@@ -93,10 +93,10 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md` (Deferred list). Contract: `docs/pro**What:** the refresh needs the writer lock; with a resident serve on PGLite it waits or refuses. **Fix:** delegate the refresh over the local persistence IPC socket. **Effort:** M. **Priority:** P2 (Foundations 2).- [ ] **P3 — The consumer's idle probe ignores the refresh effect fence.****What:** the resident consumer's idle tick does not consult an active refresh's fence before probing. Harmless today (the probe writes nothing). **Effort:** S. **Priority:** P3 (Foundations 2).-- [ ] **P2 — Drop the JSONB grant authority for legacy tokens.**- **What:** migrated tokens still mirror `permissions` JSON for older binaries, and admin-dashboard-created tokens are still born on the JSONB shape. **Fix:** after one release window, read only the unified columns and have the dashboard mint through `insertUnifiedToken`. **Effort:** M. **Priority:** P2 (Foundations 2).-- [ ] **P2 — `--sources none` for OAuth clients.**- **What:** refused for clients in F3 (no behavior change); needs per-client takes holders. **Effort:** M. **Priority:** P2 (Foundations 2).+- [x] **P2 — Drop the JSONB grant authority for legacy tokens.** **Completed: Foundations 2** — the dashboard mints through `mintLegacyToken`, migration v201 converts every legacy grant, the HTTP auth paths read the columns (a later legacy row converts on its first read), and minting no longer writes a JSONB-only grant.+- [ ] **P2 — Remove the `permissions` grant mirror after its window.**+ **What:** tokens still write the `permissions` JSONB mirror and enforce drift until `GRANT_MIRROR_WINDOW_ENDS` (2026-11-04, `src/core/grants/model.ts`) so older binaries keep working. **Fix:** after that date stop writing the mirror, drop the drift comparison and `legacy_token_grant_drift`, and keep `migrateLegacyTokens` only for brains that skipped v201. **Effort:** M. **Priority:** P2.+- [x] **P2 — `--sources none` for OAuth clients.** **Completed: Foundations 2** — `auth rescope --client <id> --sources none` and `--takes-holders a,b|none` (migration v202).- [ ] **P2 — Seat follow-ups (#4618).****What:** Codex hooks' trust hash changes when a seat is added; the harness Codex note should say so; OpenClaw's heartbeat does not report a seat write failure; a pattern page's `seat` is never removed when its sessions age out. **Effort:** M. **Priority:** P2 (Foundations 2).- [ ] **P2 — Large-brain ceilings in the 50k nightly.**@@ -3338,16 +3338,14 @@ which inverts the intent of the metric.Deferred from the #2529/#2477 security-fix wave (plan-eng-review + codex outsidevoice CLEARED). None block the wave.-- [ ] **P2 — Per-OAuth-client `takes_holders` storage (#2529 follow-up).** Legacy- bearer tokens honor `access_tokens.permissions.takes_holders` through- `verifyAccessToken`; OAuth clients have no equivalent column on `oauth_clients`,- so OAuth-minted tokens fail closed to `['world']`. Needs a schema migration- (`oauth_clients.takes_holders` JSONB or TEXT[]) + a `register-client` flag +- the `verifyAccessToken` JOIN projection. Include surfacing the EFFECTIVE- takes-holder scope in `whoami` output as part of this follow-up, so operators- can self-diagnose the legacy-vs-OAuth semantic split instead of reading docs.- Where: `src/schema.sql`, `src/core/migrate.ts`, `src/core/oauth-provider.ts`,- `src/commands/auth.ts`, `src/core/operations.ts` (whoami).+- [x] **P2 — Per-OAuth-client `takes_holders` storage (#2529 follow-up).**+ **Completed: Foundations 2** — `oauth_clients.takes_holders` (migration v202),+ set with `gbrain auth rescope --client <id> --takes-holders a,b|none`, read by+ `verifyAccessToken` and the publication holder reauthorization.+- [ ] **P3 — `register-client --takes-holders` and effective holders in `whoami`.**+ **What:** a client's holders are set after registration with+ `auth rescope --client`; registration takes no holder flag, and `whoami` does+ not print the effective takes-holder scope. **Effort:** S. **Priority:** P3.- [ ] **P3 — agent-voice Host-header allowlist (DNS-rebinding hardening).** The#2477 fix ships default-deny CORS + an Origin gate on `/session`/`/tool`, butthe gate derives self-origin from the `Host` header, so a DNS-rebound pagediff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.mdindex 3f4e9ce2fc..aa5974fa89 100644--- a/docs/architecture/key-files/security.md+++ b/docs/architecture/key-files/security.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/env-trust.ts` — Trust boundary for environment variables Bun auto-loaded from the cwd `.env` family. `CWD_DOTENV_FILES` (the eight names Bun auto-loads across NODE_ENV values), `splitDotenvLines` (Bun's line grammar: `\n`, `\r\n` AND a bare `\r` terminate a line, leading BOM stripped — shared with gbrain-env-file.ts), `dotenvValuesForKey(key, dir)` (value set across all assignments; the #427 `DATABASE_URL` value-match guard in config.ts, which re-exports both), `cwdDotenvAssignsKey(key, dir | assignments)` (KEY-PRESENCE predicate; an empty assignment counts) and `parseCwdDotenv(dir)` → `DotenvAssignment[]` (one read the two preflight consumers share). The assignment RHS is matched as `([^\r\n]*)`, never `.*$`. Protection is one predicate, `isCwdDotenvProtectedKey(key)`: `CWD_DOTENV_PROTECTED_KEYS` (code-loading / exec-target / root- and endpoint-redirect incl. `GBRAIN_DATABASE_URL` (key-presence; the #427 config.ts VALUE guard is separate and covers only bare `DATABASE_URL`), `GBRAIN_DIRECT_DATABASE_URL`, `GBRAIN_REMOTE_MCP_URL`, `GBRAIN_REMOTE_ISSUER_URL`, `GBRAIN_OAUTH_RELAY_URL` / posture-widening `GBRAIN_*`, plus the re-run marker `GBRAIN_CWD_ENV_QUARANTINED`; one why-comment per key, plus the deliberate exclusions and deferrals) PLUS `CWD_DOTENV_PROTECTED_PREFIXES` (`LD_`, `DYLD_`, `GIT_`, `BUN_`, `NPM_CONFIG_`, `npm_config_`, `BASH_FUNC_`) and `CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS` (NODE_OPTIONS/NODE_PATH/CA/TLS, SSH_ASKPASS*, XDG_CONFIG/DATA/CACHE_HOME, GNUPGHOME, SSL_CERT_FILE/DIR, CURL_CA_BUNDLE, REQUESTS_CA_BUNDLE, OPENSSL_CONF/ENGINES/MODULES, TMPDIR/TMP/TEMP, HOME/USERPROFILE, the shell-startup / interpreter-home group BASH_ENV, SHELLOPTS, PS4, BASHOPTS, PROMPT_COMMAND, ZDOTDIR, PYTHONHOME, PERLLIB, GCONV_PATH (sh/ksh `ENV` deliberately excluded: interactive-only and a routine project key), EDITOR/VISUAL/PAGER, PYTHON/PERL/RUBY preload, proxy vars both spellings, CLAUDE_CONFIG_DIR, ANTHROPIC_*/OPENAI/OPENROUTER/LITELLM/OLLAMA/LMSTUDIO/LLAMA_SERVER(_RERANKER)_BASE_URL) — the families a cwd .env could plant for the programs gbrain spawns; a denylist that grows as families are identified. `quarantineCwdDotenv(env = process.env, dir = process.cwd(), { warn, assignments })` iterates the keys the cwd .env files ASSIGN, deletes each protected one present in `env`, prints ONE stderr line (`formatQuarantineWarning`, composed from the exported `CWD_DOTENV_REMEDIATION` that guardrails.ts reuses) naming them sorted, returns them sorted. INVARIANTS: key presence, never value match; the parser accepts every line shape Bun's loader does; in-process only — children spawned without an explicit `env` see Bun's startup snapshot, which is why `cli-preflight.ts` re-runs gbrain from a neutral cwd whenever the list is non-empty; fs/path only, no config import. Pinned by `test/env-trust.test.ts`; the GBRAIN list is guarded against rot by the structural `test/env-trust-protected-keys.test.ts` (every `process.env.GBRAIN_*` / `Bun.env.GBRAIN_*` / `env.GBRAIN_*` read in src/ whose name matches `_BIN|_CLI|_MODULE|_PATH|_HOME|_URL` suffix or `GBRAIN_ALLOW_` prefix must be on the list or carry a `cwd-dotenv-ok: <why>` annotation).-- `src/core/grants/` — canonical OAuth client grant model shared by CLI, admin HTTP, provisioning, and worker admission. `model.ts` validates active sources, independent direct/delegated fences, explicit reviewed tools, namespaces, concurrency, spend, and TTL; `host`/`current` brain aliases normalize to the serving brain (`null`), while other IDs need independently verified host identity. `profiles.ts` snapshots current eligible operation names for six explicit profiles; new defaults are renewable 1 hour (static 30 days), concurrency 1, and unlimited delegated spend. `allowed_operations = NULL` preserves legacy scope-based behavior; a new profile missing its snapshot fails closed. `service.ts` locks the client, checks `grant_revision`, and commits the grant, secret-free audit, and original ceilings for pending/active legacy jobs atomically; stale edits fail, repeated repair is a no-op, and repair preserves populated limits. Issued scopes intersect live scopes on access and refresh; source/path/operation/delegation changes are live, newly added scopes require new issuance, and TTL changes do not rewrite existing expiry. `migration.ts` splits legacy fences and removes only invalid `agent` grants with repair reasons; it loads registry validation lazily only after locking existing delegated clients, so empty engine imports and cold migrations do not register unrelated background sinks. This justified engine-live import is line-marked; constraints still install when no clients exist. F3 one grant shape: `model.ts` also holds `PrincipalGrant` (`GrantSources` = `default` | `scalar` | `federated` | `none`), `grantFromTokenRow` (unified rows read the `access_tokens` grant columns and any axis whose `permissions` mirror disagrees evaluates deny-all and is listed in `drift`; an unconverted `source_grant IS NULL` row reads as the conversion `migrateLegacyTokens` would write, and a malformed `permissions` value denies every axis), `GRANT_MIRROR_WINDOW_ENDS` (the date until which the `permissions` mirror is written and drift is enforced; doctor reports it), `authSourcesFromGrant` (the AuthInfo source fields every token reader uses: both HTTP transports, publication `authority.ts`, job admission, shared-skill membership and policy), `grantFromClient`, `validatePrincipalGrant` (tokens may hold `none`; clients refuse it with `client_sources_none_unsupported`) and `permissionsMirror`. `access-token-schema.ts` is the column fragment (migration `f3_access_token_grants`); v201 (`lane_e_legacy_token_grant_conversion`) converts every legacy grant in bulk. Tests: `test/legacy-token-grant-conversion.test.ts`. `legacy-token.ts` is the token grant editor behind `gbrain auth rescope --token` (aliases `rescope-token`, `permissions set-takes-holders`): one `FOR UPDATE` transaction that writes the columns, bumps `grant_revision` (`--if-version` compare-and-set) and rewrites `permissions` as a mirror with every other key preserved; `none` = explicit empty list; refresh previews and widens only by named operations; a drifted token refuses edits until `--adopt-permissions` or `--adopt-columns`; `migrateLegacyTokens` (`--migrate-legacy` and schema migration v201) writes the columns for every unmigrated token without changing a grant and skips malformed JSONB; `resolveTokenGrant` is the HTTP auth read (both transports): a legacy-shape row converts on that read with one `source_grant IS NULL`-guarded UPDATE (concurrent first reads convert once; a failed write such as a read-only role authorizes with the identical in-memory conversion); `resolveRescopeTarget` refuses a bare name that matches a token and a client. `cli.ts` splits `auth rescope` targets and maps the unified client flags onto `auth rescope-client`'s patch. An explicit empty `permissions.source_id` decodes (`parseLegacyTokenScope` in `src/core/legacy-token-scope.ts`) to the `NO_SOURCES` sentinel, which `sourceScopeOpts`, the dispatch fence (`enforceBoundClientOpAllowList`, `fence=no_source_grant`), `submissionAuthority` and `POST /ingest` refuse and publication reauthorization rejects; it never regains the `default` floor. `schema.ts` supplies migration147/bootstrap columns and invariants for both engines. SQL JSON passes through `text::jsonb` for driver parity. Tests: `test/client-grants.test.ts`, OAuth compatibility suites, and `test/e2e/client-grants.test.ts` (Postgres CAS, job ceilings, and actual HTTP preview/edit).+- `src/core/grants/` — canonical OAuth client grant model shared by CLI, admin HTTP, provisioning, and worker admission. `model.ts` validates active sources, independent direct/delegated fences, explicit reviewed tools, namespaces, concurrency, spend, and TTL; `host`/`current` brain aliases normalize to the serving brain (`null`), while other IDs need independently verified host identity. `profiles.ts` snapshots current eligible operation names for six explicit profiles; new defaults are renewable 1 hour (static 30 days), concurrency 1, and unlimited delegated spend. `allowed_operations = NULL` preserves legacy scope-based behavior; a new profile missing its snapshot fails closed. `service.ts` locks the client, checks `grant_revision`, and commits the grant, secret-free audit, and original ceilings for pending/active legacy jobs atomically; stale edits fail, repeated repair is a no-op, and repair preserves populated limits. Issued scopes intersect live scopes on access and refresh; source/path/operation/delegation changes are live, newly added scopes require new issuance, and TTL changes do not rewrite existing expiry. `migration.ts` splits legacy fences and removes only invalid `agent` grants with repair reasons; it loads registry validation lazily only after locking existing delegated clients, so empty engine imports and cold migrations do not register unrelated background sinks. This justified engine-live import is line-marked; constraints still install when no clients exist. F3 one grant shape: `model.ts` also holds `PrincipalGrant` (`GrantSources` = `default` | `scalar` | `federated` | `none`), `grantFromTokenRow` (unified rows read the `access_tokens` grant columns and any axis whose `permissions` mirror disagrees evaluates deny-all and is listed in `drift`; an unconverted `source_grant IS NULL` row reads as the conversion `migrateLegacyTokens` would write, and a malformed `permissions` value denies every axis), `GRANT_MIRROR_WINDOW_ENDS` (the date until which the `permissions` mirror is written and drift is enforced; doctor reports it), `authSourcesFromGrant` (the AuthInfo source fields every token reader uses: both HTTP transports, publication `authority.ts`, job admission, shared-skill membership and policy), `grantFromClient`, `validatePrincipalGrant` (tokens and clients may hold `none`); `ClientGrant.sourcesNone` (`oauth_clients.source_grant = 'none'`: NULL `source_id`, empty `federated_read`, verified as `NO_SOURCES`) and `ClientGrant.takesHolders` (`oauth_clients.takes_holders`, NULL = `['world']`; read by `verifyAccessToken` and `authorizeTakeHolder`), both added by migration v202 (fragment `oauth-client-axes-schema.ts`) and set through `auth rescope --client --sources none|--takes-holders` and `permissionsMirror`. `access-token-schema.ts` is the column fragment (migration `f3_access_token_grants`); v201 (`lane_e_legacy_token_grant_conversion`) converts every legacy grant in bulk. Tests: `test/legacy-token-grant-conversion.test.ts`. `legacy-token.ts` is the token grant editor behind `gbrain auth rescope --token` (aliases `rescope-token`, `permissions set-takes-holders`): one `FOR UPDATE` transaction that writes the columns, bumps `grant_revision` (`--if-version` compare-and-set) and rewrites `permissions` as a mirror with every other key preserved; `none` = explicit empty list; refresh previews and widens only by named operations; a drifted token refuses edits until `--adopt-permissions` or `--adopt-columns`; `migrateLegacyTokens` (`--migrate-legacy` and schema migration v201) writes the columns for every unmigrated token without changing a grant and skips malformed JSONB; `resolveTokenGrant` is the HTTP auth read (both transports): a legacy-shape row converts on that read with one `source_grant IS NULL`-guarded UPDATE (concurrent first reads convert once; a failed write such as a read-only role authorizes with the identical in-memory conversion); `resolveRescopeTarget` refuses a bare name that matches a token and a client. `cli.ts` splits `auth rescope` targets and maps the unified client flags onto `auth rescope-client`'s patch. An explicit empty `permissions.source_id` decodes (`parseLegacyTokenScope` in `src/core/legacy-token-scope.ts`) to the `NO_SOURCES` sentinel, which `sourceScopeOpts`, the dispatch fence (`enforceBoundClientOpAllowList`, `fence=no_source_grant`), `submissionAuthority` and `POST /ingest` refuse and publication reauthorization rejects; it never regains the `default` floor. `schema.ts` supplies migration147/bootstrap columns and invariants for both engines. SQL JSON passes through `text::jsonb` for driver parity. Tests: `test/client-grants.test.ts`, OAuth compatibility suites, and `test/e2e/client-grants.test.ts` (Postgres CAS, job ceilings, and actual HTTP preview/edit).- `src/core/grants/lifecycle.ts` + `src/commands/serve-http-clients.ts` — owner-authenticated client inspection, setup, export and lifecycle endpoints. Token invalidation/revoke/delete lock the OAuth client row, require reviewed revisions and explicit application, and commit an audit record atomically. Deletion records a tombstone while preserving request history and spending reservations/settlement; missing clients become terminal delegated denials while transient lookup failures remain retryable.- `src/commands/serve-http-api-keys.ts` — owner-dashboard legacy API keys (`/admin/api/api-keys`). Mint validates the request (`parseApiKeyMintRequest`: name 1-128 printable characters, registered scopes, active source ids, holder grammar) and goes through `mintLegacyToken`, so keys are born on the unified grant columns; omitted fields take the `gbrain auth create` defaults (scopes `read,write`, never `admin` unless listed; no source grant; holders `['world']`), reported in `defaults_applied` beside the effective grant. Refusals are `invalid_params` agent envelopes with `why` and a `fix`; nothing is minted. The token appears only in the mint response, never in logs or SSE. The list returns ids, scopes, sources and holders through `grantFromTokenRow`; revoke takes the row id (`revokeLegacyTokenById`) and refuses a name. Pinned by `test/serve-http-api-keys.test.ts`.diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex 39b151290d..b4e594ba1c 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -291,13 +291,15 @@ gbrain auth rescope --token agent-example --sources none # deny-allgbrain auth rescope --token agent-example --reset-default sources,takes-holdersgbrain auth rescope --id TOKEN_ID --sources default --if-version 3 --dry-run --jsongbrain auth rescope --client CLIENT_ID --sources workspace,default --operations get_page,search+gbrain auth rescope --client CLIENT_ID --takes-holders world,brain+gbrain auth rescope --client CLIENT_ID --sources none # deny-all, secret unchanged```| Flag | Value | Effect || --- | --- | --- |-| `--sources` | `a,b` or `none` | Source grant; the first id is the write source, the list is the read set. `default` is the source named `default`; to restore the no-grant floor use `--reset-default sources`. Tokens: `none` grants no source, so reads and writes to every source are refused (`permission_denied`, `fence=no_source_grant`), including writes accepted before the change. Clients: `none` refuses (`client_sources_none_unsupported`); cut a client off with `gbrain auth revoke-client <client_id>`. |+| `--sources` | `a,b` or `none` | Source grant; the first id is the write source, the list is the read set. `default` is the source named `default`; to restore the no-grant floor use `--reset-default sources`. `none` grants no source, so reads and writes to every source are refused (`permission_denied`, `fence=no_source_grant`), including writes accepted before the change; the token or client keeps its scopes and secret. A client with `none` takes no `--read-sources`, and a delegating agent client cannot hold it. || `--read-sources` | `a,b` | Client only: a read set that differs from `--sources`. |-| `--takes-holders` | `a,b` or `none` | Token only: takes-holder allow-list; `none` hides every take. |+| `--takes-holders` | `a,b` or `none` | Takes-holder allow-list for a token or client (default `world`); `none` hides every take. || `--operations` | `op,...` or `none` | Operation snapshot; `none` refuses every operation. || `--scopes` | `read,write,...` | Replaces the scopes. || `--reset-default` | `sources,takes-holders,operations` | Token only: restores the `auth create` default for those axes: no source grant (the historical `default` floor), holders `world`, no operation snapshot. |diff --git a/src/commands/auth.ts b/src/commands/auth.tsindex 68ea876fdb..b1f8b58696 100644--- a/src/commands/auth.ts+++ b/src/commands/auth.ts@@ -836,8 +836,9 @@ async function rescopeClientWith(engine: BrainEngine, clientId: string, parsed:console.log(`OAuth client ${parsed.dryRun ? 'grant preview' : 'rescoped'}: ${result.after.clientName} (${clientId})`);console.log(` Revision: ${result.before.revision} -> ${result.after.revision}`);console.log(` Scopes: ${result.after.scopes.join(' ') || '<none>'}`);- console.log(` Write source: ${result.after.sourceId}`);- console.log(` Federated reads: ${result.after.federatedRead.join(', ')}`);+ console.log(` Write source: ${result.after.sourcesNone ? 'none (every read and write refused)' : result.after.sourceId}`);+ console.log(` Federated reads: ${result.after.federatedRead.join(', ') || '<none>'}`);+ console.log(` Takes holders: ${result.after.takesHolders === null ? 'world (default)' : result.after.takesHolders.join(', ') || 'none (every take hidden)'}`);console.log(` Tool surface: ${result.after.surface ?? '<server default>'}`);console.log(` Delegated spending: ${result.after.budgetUsdPerDay === null ? 'unlimited' : '$' + result.after.budgetUsdPerDay + '/day'}`);console.log('Restrictions apply on the next request. Added scopes require a new access token; the client secret is unchanged.');@@ -1122,9 +1123,9 @@ Usage:grants. A bare name matching both a token and aclient refuses; pass --token or --client.--sources <id1,id2,...|none> Source grant (first = write source; 'none' = deny-all,- tokens only — revoke a client with revoke-client)+ scopes and secret unchanged)--read-sources <id1,id2,...> Client only: a read set that differs from --sources- --takes-holders <h1,h2,...|none> Token only: takes-holder allow-list ('none' = deny-all)+ --takes-holders <h1,h2,...|none> Takes-holder allow-list (default world; 'none' = deny-all)--operations <op1,op2,...|none> Operation snapshot ('none' = deny-all)--scopes <read,write,...> Replace the scopes--reset-default <sources,takes-holders,operations> Token only: restore the auth create default for those axesdiff --git a/src/core/company-brain/admission.ts b/src/core/company-brain/admission.tsindex 5c058a9a30..0afddd7192 100644--- a/src/core/company-brain/admission.ts+++ b/src/core/company-brain/admission.ts@@ -202,7 +202,7 @@ export async function checkCompanyBrainDestination(engine: BrainEngine, input: C}const [broad] = await engine.executeRaw<{ count: string }>(`SELECT count(*)::text AS count FROM (- SELECT client_id AS id FROM oauth_clients WHERE deleted_at IS NULL AND source_id IS NULL AND cardinality(federated_read)=0+ SELECT client_id AS id FROM oauth_clients WHERE deleted_at IS NULL AND source_id IS NULL AND cardinality(federated_read)=0 AND source_grant IS DISTINCT FROM 'none'AND (scope IS NULL OR scope ~ '(^|\\s)(read|admin)(\\s|$)') AND (allowed_operations IS NULL OR cardinality(allowed_operations)>0)UNION ALL SELECT id::text FROM persistence_local_writers WHERE lane='stdio' AND revoked_at IS NULLAND grant_ceiling->'sourceIds' ? '*' AND grant_ceiling->'scopes' ? 'read'diff --git a/src/core/grants/cli.ts b/src/core/grants/cli.tsindex 3038e8d8a4..3dda9b6525 100644--- a/src/core/grants/cli.ts+++ b/src/core/grants/cli.ts@@ -1,5 +1,6 @@import { GRANT_PROFILES, GrantError, validatePrincipalGrant, type GrantPatch, type GrantProfileId } from './model.ts';import { parseScopeString, assertAllowedScopes } from '../scope.ts';+import { isValidHolder } from '../takes-fence.ts';export interface RescopeGrantArgs {patch: GrantPatch;@@ -112,7 +113,6 @@ export function splitRescopeTarget(args: string[]): RescopeCommand {}const TOKEN_ONLY_FLAGS: Record<string, string> = {- '--takes-holders': 'client_takes_holders_unsupported','--reset-default': 'client_reset_default_unsupported','--refresh-operations': 'client_refresh_operations_unsupported','--add': 'client_refresh_operations_unsupported',@@ -122,24 +122,25 @@ const TOKEN_ONLY_FLAGS: Record<string, string> = {};/**- * Client flags of `auth rescope --client`: the unified `--sources a,b`+ * Client flags of `auth rescope --client`: the unified `--sources a,b|none`* (element 0 = write source, the list = read set unless `--read-sources`- * names a different one), `--read-sources`, `--operations a,b|none` and every- * `auth rescope-client` flag. `--sources none` refuses (decision 4: client- * deny-all is `auth revoke-client`).+ * names a different one; `none` is the explicit no-source grant that refuses+ * every read and write), `--read-sources`, `--operations a,b|none`,+ * `--takes-holders a,b|none` and every `auth rescope-client` flag.*/export function parseClientRescopeArgs(clientId: string, args: string[]): RescopeGrantArgs {const legacy: string[] = [];let sources: string[] | undefined;let readSources: string[] | undefined;let operations: string[] | undefined;+ let takesHolders: string[] | undefined;const csv = (value: string): string[] => [...new Set(value.split(',').map(s => s.trim()).filter(Boolean))];for (let i = 0; i < args.length; i++) {const flag = args[i];if (TOKEN_ONLY_FLAGS[flag]) {throw new GrantError('invalid_grant', `${flag} applies to legacy tokens only; OAuth client ${clientId} has no such grant in this release (see gbrain auth rescope --help)`, [TOKEN_ONLY_FLAGS[flag]]);}- if (!['--sources', '--read-sources', '--operations'].includes(flag)) {+ if (!['--sources', '--read-sources', '--operations', '--takes-holders'].includes(flag)) {legacy.push(flag);if (!BOOLEAN_FLAGS.has(flag) && args[i + 1] !== undefined) legacy.push(args[++i]);continue;@@ -149,6 +150,7 @@ export function parseClientRescopeArgs(clientId: string, args: string[]): Rescopif (flag === '--sources') sources = value === 'none' ? [] : csv(value);if (flag === '--read-sources') readSources = csv(value);if (flag === '--operations') operations = value === 'none' ? [] : csv(value);+ if (flag === '--takes-holders') takesHolders = value === 'none' ? [] : csv(value);}const result = parseRescopeGrantFlags(legacy);if (sources !== undefined) {@@ -157,11 +159,18 @@ export function parseClientRescopeArgs(clientId: string, args: string[]): Rescopshape: 'unified', drift: [], permissionsMalformed: false,sources: sources.length === 0 ? { kind: 'none' } : { kind: 'federated', writeSource: sources[0], readSources: sources },}, { operationNames: new Set() });- result.patch.sourceId = sources[0];+ result.patch.sourceId = sources.length === 0 ? null : sources[0];+ result.patch.sourcesNone = sources.length === 0;}if (readSources !== undefined && readSources.length === 0) throw new GrantError('invalid_grant', '--read-sources needs at least one source id');+ if (sources?.length === 0 && readSources !== undefined) throw new GrantError('invalid_grant', '--sources none grants no source, so it takes no --read-sources');if (sources !== undefined || readSources !== undefined) result.patch.federatedRead = readSources ?? sources;if (operations !== undefined) result.patch.allowedOperations = operations;+ if (takesHolders !== undefined) {+ const invalid = takesHolders.filter(h => !isValidHolder(h));+ if (invalid.length) throw new GrantError('invalid_grant', `Invalid takes holder: ${invalid.join(', ')} (use world, brain, people/<slug>, companies/<slug> or a bare slug)`, ['takes_holders_invalid']);+ result.patch.takesHolders = takesHolders;+ }if (!result.profile && Object.keys(result.patch).length === 0) throw new GrantError('invalid_grant', 'Pass a grant field or --profile to rescope');return result;}diff --git a/src/core/grants/model.ts b/src/core/grants/model.tsindex 01a233a4f4..14c10e4adb 100644--- a/src/core/grants/model.ts+++ b/src/core/grants/model.ts@@ -14,6 +14,10 @@ export interface ClientGrant {scopes: string[];sourceId: string | null;federatedRead: string[];+ /** The explicit no-source grant: `sourceId` null, `federatedRead` empty, every read and write refused. */+ sourcesNone: boolean;+ /** Takes-holder allow-list; null = the default ['world'], [] = deny-all. */+ takesHolders: string[] | null;boundSlugPrefixes: string[] | null;allowedOperations: string[] | null;boundTools: string[] | null;@@ -70,6 +74,7 @@ export function grantFromRow(row: Record<string, unknown>): ClientGrant {clientId: String(row.client_id), clientName: String(row.client_name ?? ''),scopes: parseScopeString(nullable(row.scope) ?? ''),sourceId: nullable(row.source_id), federatedRead: stringArray(row.federated_read) ?? [],+ sourcesNone: row.source_grant === 'none', takesHolders: stringArray(row.takes_holders),boundSlugPrefixes: legacyPrefixes, allowedOperations: stringArray(row.allowed_operations),boundTools: stringArray(row.bound_tools), boundSourceId: nullable(row.bound_source_id),boundBrainId: normalizeGrantBrain(nullable(row.bound_brain_id)),@@ -115,8 +120,13 @@ export function validateClientGrant(grant: ClientGrant, ctx: GrantValidationContassertAllowedScopes(grant.scopes);const reasons: string[] = [];if (grant.revoked) reasons.push('client_revoked');- if (!grant.sourceId || !ctx.activeSourceIds.has(grant.sourceId)) reasons.push('source_inactive');- if (grant.federatedRead.length === 0 || grant.federatedRead.some(id => !ctx.activeSourceIds.has(id))) reasons.push('read_source_inactive');+ if (grant.sourcesNone === true) {+ if (grant.sourceId !== null || grant.federatedRead.length > 0) reasons.push('sources_none_inconsistent');+ } else {+ if (!grant.sourceId || !ctx.activeSourceIds.has(grant.sourceId)) reasons.push('source_inactive');+ if (grant.federatedRead.length === 0 || grant.federatedRead.some(id => !ctx.activeSourceIds.has(id))) reasons.push('read_source_inactive');+ }+ if (grant.takesHolders != null && grant.takesHolders.some(h => typeof h !== 'string' || !h || /[\s,{}"]/.test(h))) reasons.push('takes_holders_invalid');if (grant.boundSlugPrefixes !== null && !validGrantPrefixes(grant.boundSlugPrefixes)) reasons.push('direct_prefixes_invalid');if (grant.allowedOperations?.some(name => !ctx.operationNames.has(name))) reasons.push('operations_unavailable');if (grant.profile !== null && grant.allowedOperations === null) reasons.push('operations_snapshot_missing');@@ -266,12 +276,13 @@ export function grantFromTokenRow(row: Record<string, unknown>): PrincipalGrant}export function grantFromClient(grant: ClientGrant): PrincipalGrant {- const sources: GrantSources = grant.sourceId === null ? { kind: 'default' }+ const sources: GrantSources = grant.sourcesNone === true ? { kind: 'none' }+ : grant.sourceId === null ? { kind: 'default' }: grant.federatedRead.length === 0 ? { kind: 'scalar', writeSource: grant.sourceId }: { kind: 'federated', writeSource: grant.sourceId, readSources: [...grant.federatedRead] };return {principal: { kind: 'oauth_client', id: grant.clientId }, scopes: [...grant.scopes], sources,- allowedOperations: grant.allowedOperations, takesHolders: null, revision: grant.revision,+ allowedOperations: grant.allowedOperations, takesHolders: grant.takesHolders ?? null, revision: grant.revision,shape: 'unified', drift: [], permissionsMalformed: false,};}@@ -288,14 +299,12 @@ export function authSourcesFromGrant(g: PrincipalGrant): { sourceId: string; all/*** Shape rules for a grant about to be written. Whether named sources are- * active is the caller's database check. Tokens may hold the explicit- * deny-all `none`; OAuth clients may not in F3 (client deny-all is- * `auth revoke-client`).+ * active is the caller's database check. Tokens and OAuth clients may both+ * hold the explicit deny-all `none`.*/export function validatePrincipalGrant(g: PrincipalGrant, ctx: { operationNames: ReadonlySet<string> }): void {const reasons: string[] = [];const client = g.principal.kind === 'oauth_client';- if (g.sources.kind === 'none' && client) reasons.push('client_sources_none_unsupported');if (g.sources.kind === 'scalar' || g.sources.kind === 'federated') {const ids = g.sources.kind === 'scalar' ? [g.sources.writeSource] : [g.sources.writeSource, ...g.sources.readSources];if (ids.some(id => !isValidSourceId(id))) reasons.push('source_invalid');@@ -303,10 +312,7 @@ export function validatePrincipalGrant(g: PrincipalGrant, ctx: { operationNames:}if (g.allowedOperations?.some(name => !ctx.operationNames.has(name))) reasons.push('operations_unavailable');if (!reasons.length) return;- const fix = reasons.includes('client_sources_none_unsupported')- ? ` OAuth clients cannot hold an explicit no-source grant yet; to cut client ${g.principal.id} off run gbrain auth revoke-client ${g.principal.id}, or narrow it with gbrain auth rescope --client ${g.principal.id} --sources <id>.`- : '';- throw new GrantError('invalid_grant', `Invalid ${client ? 'client' : 'token'} grant: ${reasons.join(', ')}.${fix}`, reasons);+ throw new GrantError('invalid_grant', `Invalid ${client ? 'client' : 'token'} grant: ${reasons.join(', ')}.`, reasons);}/**diff --git a/src/core/grants/oauth-client-axes-schema.ts b/src/core/grants/oauth-client-axes-schema.tsnew file mode 100644index 0000000000..71f8d07e12--- /dev/null+++ b/src/core/grants/oauth-client-axes-schema.ts@@ -0,0 +1,18 @@+/**+ * Two OAuth client grant axes that legacy tokens already had: an explicit+ * no-source grant and a per-client takes-holder allow-list.+ *+ * `source_grant` is NULL (the source grant is `source_id` + `federated_read`)+ * or `none` (the client holds no source: `source_id` NULL, `federated_read`+ * empty, every read and write refused). `takes_holders` NULL is the default+ * `['world']`; `[]` hides every take.+ *+ * The schema blob declares both after `created_at` (src/schema.sql), so a+ * fresh install and an upgrade, which appends them here, end with the same+ * column order.+ */+export const OAUTH_CLIENT_GRANT_AXES_SQL = `+ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS source_grant TEXT+ CHECK (source_grant IN ('none'));+ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS takes_holders TEXT[];+`;diff --git a/src/core/grants/service.ts b/src/core/grants/service.tsindex ce5846a466..d1d455eceb 100644--- a/src/core/grants/service.ts+++ b/src/core/grants/service.ts@@ -27,7 +27,7 @@ export interface GrantMutationOptions {servingBrainId?: string;}export interface GrantMutationResult { before: ClientGrant; after: ClientGrant; revision: number; dryRun: boolean }-const PATCH_FIELDS = new Set<keyof GrantPatch>(['scopes', 'sourceId', 'federatedRead', 'boundSlugPrefixes', 'allowedOperations', 'boundTools', 'boundSourceId', 'boundBrainId', 'delegatedSlugPrefixes', 'delegatedNamespace', 'boundMaxConcurrent', 'budgetUsdPerDay', 'surface', 'surfaceSetBy', 'tokenTtlSeconds', 'profile', 'repairReasons']);+const PATCH_FIELDS = new Set<keyof GrantPatch>(['scopes', 'sourceId', 'federatedRead', 'sourcesNone', 'takesHolders', 'boundSlugPrefixes', 'allowedOperations', 'boundTools', 'boundSourceId', 'boundBrainId', 'delegatedSlugPrefixes', 'delegatedNamespace', 'boundMaxConcurrent', 'budgetUsdPerDay', 'surface', 'surfaceSetBy', 'tokenTtlSeconds', 'profile', 'repairReasons']);export function assertGrantPatch(patch: GrantPatch): void {for (const key of Object.keys(patch)) {if (!PATCH_FIELDS.has(key as keyof GrantPatch)) throw new GrantError('invalid_grant', `Unknown grant field: ${key}`);@@ -80,7 +80,7 @@ export async function rescopeClientGrantInTransaction(db: GrantDatabase, clientIconst sql = query(db);const rows = await sql`SELECT * FROM oauth_clients WHERE client_id = ${clientId} FOR UPDATE`;if (!rows.length) throw new GrantError('client_not_found', `No OAuth client found with id "${clientId}"`);- if (!('grant_revision' in rows[0])) throw new GrantError('grant_schema_required', 'Run gbrain apply-migrations --yes before changing client grants');+ if (!('grant_revision' in rows[0]) || !('takes_holders' in rows[0])) throw new GrantError('grant_schema_required', 'Run gbrain apply-migrations --yes before changing client grants');const before = grantFromRow(rows[0]);if (opts.expectedRevision !== undefined && before.revision !== opts.expectedRevision) {throw new GrantError('grant_conflict', `Grant changed (expected revision ${opts.expectedRevision}, current ${before.revision}); review a fresh preview`);@@ -101,6 +101,7 @@ export async function rescopeClientGrantInTransaction(db: GrantDatabase, clientIchanges.scopes = [...new Set([...before.scopes, 'agent'])];}const after: ClientGrant = { ...before, ...changes, revision: before.revision + 1, repairReasons: [] };+ if (changes.sourceId != null && changes.sourcesNone === undefined) after.sourcesNone = false;after.boundBrainId = normalizeGrantBrain(after.boundBrainId);validateClientGrant(after, await grantValidationContext(db, opts.servingBrainId));if (JSON.stringify({ ...after, revision: before.revision }) === JSON.stringify(before)) {@@ -118,6 +119,8 @@ export async function persistGrant(sql: SqlQuery, before: ClientGrant, after: ClUPDATE oauth_clients SETscope = ${after.scopes.join(' ')}, source_id = ${after.sourceId},federated_read = ARRAY(SELECT jsonb_array_elements_text(${JSON.stringify(after.federatedRead)}::text::jsonb)),+ source_grant = ${after.sourcesNone === true ? 'none' : null},+ takes_holders = CASE WHEN ${after.takesHolders == null} THEN NULL ELSE ARRAY(SELECT jsonb_array_elements_text(${JSON.stringify(after.takesHolders ?? [])}::text::jsonb)) END,bound_slug_prefixes = CASE WHEN ${after.boundSlugPrefixes === null} THEN NULL ELSE ARRAY(SELECT jsonb_array_elements_text(${JSON.stringify(after.boundSlugPrefixes ?? [])}::text::jsonb)) END,allowed_operations = CASE WHEN ${after.allowedOperations === null} THEN NULL ELSE ARRAY(SELECT jsonb_array_elements_text(${JSON.stringify(after.allowedOperations ?? [])}::text::jsonb)) END,bound_tools = CASE WHEN ${after.boundTools === null} THEN NULL ELSE ARRAY(SELECT jsonb_array_elements_text(${JSON.stringify(after.boundTools ?? [])}::text::jsonb)) END,diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.tsindex 64a0bdc121..75fcb03de6 100644--- a/src/core/oauth-provider.ts+++ b/src/core/oauth-provider.ts@@ -42,6 +42,7 @@ import { assertValidSlugPrefixes, pgArray } from './grants/encoding.ts';import { rescopeOAuthClient, type RescopeClientOptions, type RescopeClientResult } from './grants/rescope.ts';import { grantValidationContext, validateClientGrant, insertClientGrant, assertGrantPatch } from './grants/service.ts';import { resolveTokenGrant } from './grants/legacy-token.ts';+import { NO_SOURCES } from './source-id.ts';/*** A slug-prefix write binding is only meaningful if every entry actually@@ -851,6 +852,11 @@ export class GBrainOAuthProvider implements OAuthServerProvider {// fail-open by design: the server ceiling still bounds every request.const rowSurface = typeof row.surface === 'string' ? row.surface : undefined;const rowSurfaceSetBy = typeof row.surface_set_by === 'string' ? row.surface_set_by : undefined;+ // The explicit no-source grant: every read and write refuses+ // (NO_SOURCES, the same sentinel a `--sources none` token carries).+ const sourcesNone = currentGrant.source_grant === 'none';+ const clientHolders = Array.isArray(currentGrant.takes_holders)+ ? (currentGrant.takes_holders as unknown[]).filter((h): h is string => typeof h === 'string') : undefined;return {token,clientId: row.client_id as string,@@ -875,11 +881,14 @@ export class GBrainOAuthProvider implements OAuthServerProvider {// v0.34.1 (#861, D2): source-isolation scope from oauth_clients.// Undefined when the row predates v60 or when the brain itself// predates v60 (fell through to the legacy projection above).- sourceId: rowSourceId,+ sourceId: sourcesNone ? NO_SOURCES : rowSourceId,// v0.34.1 (#876): federated read scope. sourceScopeOpts in// operations.ts prefers this array over scalar sourceId when set// and non-empty.- allowedSources,+ allowedSources: sourcesNone ? [] : allowedSources,+ ...(sourcesNone ? { hasSourceGrant: true } : {}),+ // Per-client takes holders; undefined → the /mcp dispatch site's fail-closed ['world'].+ ...(clientHolders ? { takesHoldersAllowList: clientHolders } : {}),// v0.42.72.0: write fence — consumed by enforceClientSlugFence in// operations.ts on every direct slug-mutating write op.boundSlugPrefixes,diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.tsindex 9508ff8e8b..12dc6e73a9 100644--- a/src/core/persistence/authority.ts+++ b/src/core/persistence/authority.ts@@ -177,6 +177,10 @@ export async function authorizeTakeHolder(engine: SqlEngine, authority: WriteAutconst [row] = await engine.executeRaw<Record<string, unknown>>('SELECT * FROM access_tokens WHERE id=$1 AND revoked_at IS NULL', [authority.principal.id]);if (!row) deny('The owning token is revoked.');current = grantFromTokenRow(row).takesHolders ?? ['world'];+ } else if (authority.principal.kind === 'oauth_client') {+ const [row] = await engine.executeRaw<{ takes_holders: unknown }>('SELECT takes_holders FROM oauth_clients WHERE client_id=$1 AND deleted_at IS NULL', [authority.principal.id]);+ if (!row) deny('The owning OAuth client is revoked.');+ current = row.takes_holders == null ? ['world'] : strings(row.takes_holders) ? row.takes_holders : [];}if (!current.includes(holder)) deny('The current holder grant excludes this write.');}diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex f9af4910a2..f5f0adedd6 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -324,7 +324,9 @@ CREATE TABLE IF NOT EXISTS oauth_clients (grant_profile TEXT NULL,grant_revision INTEGER NOT NULL DEFAULT 0,grant_repair_reasons TEXT[] NOT NULL DEFAULT '{}',- created_at TIMESTAMPTZ NOT NULL DEFAULT now()+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ source_grant TEXT NULL CHECK (source_grant IN ('none')),+ takes_holders TEXT[] NULL);CREATE INDEX IF NOT EXISTS idx_oauth_clients_source_idON oauth_clients(source_id) WHERE source_id IS NOT NULL;diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 01044b0e99..d90f2fabf9 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -694,7 +694,11 @@ CREATE TABLE IF NOT EXISTS oauth_clients (grant_profile TEXT NULL,grant_revision INTEGER NOT NULL DEFAULT 0,grant_repair_reasons TEXT[] NOT NULL DEFAULT '{}',- created_at TIMESTAMPTZ NOT NULL DEFAULT now()+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ -- Explicit no-source grant ('none') and per-client takes holders (NULL =+ -- ['world']); upgrades add both through src/core/grants/oauth-client-axes-schema.ts.+ source_grant TEXT NULL CHECK (source_grant IN ('none')),+ takes_holders TEXT[] NULL);-- v0.34.1 (#861, D13 + #876): source_id is the write-source scope;-- federated_read is the read-source array. Migrations v60-v65 land bothdiff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex a98ead8498..2261bc5f58 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -202,6 +202,7 @@ import { v198 } from './v198-publication-failure-detail.ts';import { v199 } from './v199-chronicle-page-state.ts';import { v200 } from './v200-sync-hold-page-index.ts';import { v201 } from './v201-lane-e-legacy-token-grant-conversion.ts';+import { v202 } from './v202-lane-e-oauth-client-grant-axes.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -402,4 +403,5 @@ export const MIGRATIONS: Migration[] = [v199,v200,v201,+ v202,];diff --git a/src/core/schema-migrations/v202-lane-e-oauth-client-grant-axes.ts b/src/core/schema-migrations/v202-lane-e-oauth-client-grant-axes.tsnew file mode 100644index 0000000000..e0110e6e07--- /dev/null+++ b/src/core/schema-migrations/v202-lane-e-oauth-client-grant-axes.ts@@ -0,0 +1,16 @@+import { OAUTH_CLIENT_GRANT_AXES_SQL } from '../grants/oauth-client-axes-schema.ts';+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// OAuth clients gain the explicit no-source grant (`source_grant = 'none'`)+// and a per-client takes-holder allow-list (fragment+// src/core/grants/oauth-client-axes-schema.ts). Additive and metadata-only:+// every existing client keeps NULL in both, which is its current grant.+export const v202: Migration = {+ version: 202,+ name: 'lane_e_oauth_client_grant_axes',+ idempotent: true,+ sql: OAUTH_CLIENT_GRANT_AXES_SQL,+};diff --git a/src/schema.sql b/src/schema.sqlindex 43fed65c5e..a9299166e2 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -690,7 +690,11 @@ CREATE TABLE IF NOT EXISTS oauth_clients (grant_profile TEXT NULL,grant_revision INTEGER NOT NULL DEFAULT 0,grant_repair_reasons TEXT[] NOT NULL DEFAULT '{}',- created_at TIMESTAMPTZ NOT NULL DEFAULT now()+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ -- Explicit no-source grant ('none') and per-client takes holders (NULL =+ -- ['world']); upgrades add both through src/core/grants/oauth-client-axes-schema.ts.+ source_grant TEXT NULL CHECK (source_grant IN ('none')),+ takes_holders TEXT[] NULL);-- v0.34.1 (#861, D13 + #876): source_id is the write-source scope;-- federated_read is the read-source array. Migrations v60-v65 land bothdiff --git a/test/auth-rescope-unified.serial.test.ts b/test/auth-rescope-unified.serial.test.tsindex c24e77a34c..a12dd59b0f 100644--- a/test/auth-rescope-unified.serial.test.ts+++ b/test/auth-rescope-unified.serial.test.ts@@ -6,8 +6,8 @@* Protects (spec 4.5): `auth create` births a unified token; `rescope-token`* and `permissions set-takes-holders` stay exact aliases of* `rescope --token`; `rescope --client` and `rescope-client` write identical- * rows and `--sources none` on a client refuses with- * `client_sources_none_unsupported` (9); `--if-version` mismatch refuses with+ * rows and `--sources none` and `--takes-holders` on a client succeed+ * (9); `--if-version` mismatch refuses with* the current revision on stdout under --json (8); a bare name that matches a* token and a client refuses; `--migrate-legacy --dry-run` writes nothing (10);* harness rotation mints a unified token that keeps explicit empty lists (7).@@ -157,15 +157,17 @@ describe('9. OAuth clients', () => {expect(await clientRow(a.clientId)).toMatchObject({ source_id: 'other', federated_read: ['other', 'default'], allowed_operations: ['get_page', 'search'] });const none = await cli('auth', 'rescope', '--client', a.clientId, '--sources', 'none', '--json');- expect(none.exitCode).toBe(1);- const body = JSON.parse(none.stdout) as { error: { reasons: string[]; message: string } };- expect(body.error.reasons).toEqual(['client_sources_none_unsupported']);- expect(body.error.message).toContain(`gbrain auth revoke-client ${a.clientId}`);- expect((await clientRow(a.clientId)).source_id).toBe('other');-- const holders = await cli('auth', 'rescope', '--client', a.clientId, '--takes-holders', 'world');- expect(holders.exitCode).toBe(1);- expect(holders.stderr).toContain('--takes-holders applies to legacy tokens only');+ expect(none.exitCode).toBe(0);+ expect(JSON.parse(none.stdout).principal_grant.sources).toEqual({ kind: 'none' });+ expect(await clientRow(a.clientId)).toMatchObject({ source_id: null, federated_read: [] });++ const holders = await cli('auth', 'rescope', '--client', a.clientId, '--takes-holders', 'world,brain');+ expect(holders.exitCode).toBe(0);+ expect(holders.stdout).toContain('Takes holders: world, brain');++ const reset = await cli('auth', 'rescope', '--client', a.clientId, '--reset-default', 'sources');+ expect(reset.exitCode).toBe(1);+ expect(reset.stderr).toContain('--reset-default applies to legacy tokens only');}, 180_000);test('a bare name that matches both a token and a client refuses as ambiguous', async () => {diff --git a/test/e2e/oauth-client-grant-axes.test.ts b/test/e2e/oauth-client-grant-axes.test.tsnew file mode 100644index 0000000000..d0778980d0--- /dev/null+++ b/test/e2e/oauth-client-grant-axes.test.ts@@ -0,0 +1,45 @@+/**+ * OAuth client `--sources none` and per-client takes holders on real+ * Postgres: the text[] holder list round-trips with quoting intact through+ * the jsonb_array_elements bind, verifyAccessToken reads both axes from the+ * client row, and the no-source grant clears source_id under the FK.+ * PGLite coverage: test/oauth-client-grant-axes.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';+import { GBrainOAuthProvider } from '../../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../../src/core/sql-query.ts';+import { parseClientRescopeArgs } from '../../src/core/grants/cli.ts';+import { readClientGrant, rescopeClientGrant } from '../../src/core/grants/service.ts';+import { NO_SOURCES } from '../../src/core/source-id.ts';++const d = hasDatabase() ? describe : describe.skip;++beforeAll(async () => { if (hasDatabase()) await setupDB(); });+afterAll(async () => { if (hasDatabase()) await teardownDB(); });++const provider = () => { const engine = getEngine(); return new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) }); };+const rescope = async (clientId: string, ...args: string[]) => rescopeClientGrant(getEngine(), clientId, parseClientRescopeArgs(clientId, args).patch,+ { actor: 'e2e', expectedRevision: (await readClientGrant(getEngine(), clientId)).revision });++d('OAuth client grant axes on Postgres', () => {+ test('takes holders round-trip and verify; --sources none verifies as NO_SOURCES and restores', async () => {+ const p = provider();+ const { clientId, clientSecret } = await p.registerClientManual(`axes-e2e-${randomUUID().slice(0, 8)}`, ['client_credentials'], 'read write');+ const { access_token } = await p.exchangeClientCredentials(clientId, clientSecret!);+ const holders = ['world', 'people/alice-example', 'brain'];+ await rescope(clientId, '--takes-holders', holders.join(','));+ const [row] = await getEngine().executeRaw<Record<string, unknown>>('SELECT takes_holders, source_grant FROM oauth_clients WHERE client_id = $1', [clientId]);+ expect(row).toEqual({ takes_holders: holders, source_grant: null });+ expect(await p.verifyAccessToken(access_token)).toMatchObject({ takesHoldersAllowList: holders, sourceId: 'default' });++ await rescope(clientId, '--sources', 'none');+ expect(await p.verifyAccessToken(access_token)).toMatchObject({ sourceId: NO_SOURCES, allowedSources: [], hasSourceGrant: true, takesHoldersAllowList: holders });+ const [none] = await getEngine().executeRaw<Record<string, unknown>>('SELECT source_id, federated_read, source_grant FROM oauth_clients WHERE client_id = $1', [clientId]);+ expect(none).toEqual({ source_id: null, federated_read: [], source_grant: 'none' });++ await rescope(clientId, '--sources', 'default');+ expect(await p.verifyAccessToken(access_token)).toMatchObject({ sourceId: 'default', allowedSources: ['default'] });+ });+});diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 99a6d7000e..c19771b884 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -131,6 +131,7 @@"minion_self_fix_log.minion_self_fix_log_pkey": "p PRIMARY KEY (id)","oauth_clients.oauth_clients_complete_agent_grant": "c CHECK (((NOT (COALESCE(scope, ''::text) ~ '(^|[[:space:]])agent([[:space:]]|$)'::text)) OR ((COALESCE(cardinality(bound_tools), 0) > 0) AND (source_id IS NOT NULL) AND (bound_source_id IS NOT NULL) AND (bound_source_id = source_id) AND COALESCE((source_id = ANY (federated_read)), false) AND (((delegated_namespace = 'job'::text) AND (delegated_slug_prefixes IS NULL)) OR ((delegated_namespace = 'prefixes'::text) AND (COALESCE(cardinality(delegated_slug_prefixes), 0) > 0))) AND (bound_max_concurrent > 0))))","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))","oauth_clients.oauth_clients_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE RESTRICT","oauth_codes.oauth_codes_client_id_fkey": "f FOREIGN KEY (client_id) REFERENCES oauth_clients(client_id) ON DELETE CASCADE","oauth_codes.oauth_codes_pkey": "p PRIMARY KEY (code_hash)",@@ -1904,7 +1905,9 @@"25 grant_profile text/text NULL","26 grant_revision integer/int4 NOT NULL DEFAULT 0","27 grant_repair_reasons ARRAY/_text NOT NULL DEFAULT '{}'::text[]",- "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "29 source_grant text/text NULL",+ "30 takes_holders ARRAY/_text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex db8a7c1b35..2189f1ec93 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -131,6 +131,7 @@"minion_self_fix_log.minion_self_fix_log_pkey": "p PRIMARY KEY (id)","oauth_clients.oauth_clients_complete_agent_grant": "c CHECK (((NOT (COALESCE(scope, ''::text) ~ '(^|[[:space:]])agent([[:space:]]|$)'::text)) OR ((COALESCE(cardinality(bound_tools), 0) > 0) AND (source_id IS NOT NULL) AND (bound_source_id IS NOT NULL) AND (bound_source_id = source_id) AND COALESCE((source_id = ANY (federated_read)), false) AND (((delegated_namespace = 'job'::text) AND (delegated_slug_prefixes IS NULL)) OR ((delegated_namespace = 'prefixes'::text) AND (COALESCE(cardinality(delegated_slug_prefixes), 0) > 0))) AND (bound_max_concurrent > 0))))","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))","oauth_clients.oauth_clients_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE RESTRICT","oauth_codes.oauth_codes_client_id_fkey": "f FOREIGN KEY (client_id) REFERENCES oauth_clients(client_id) ON DELETE CASCADE","oauth_codes.oauth_codes_pkey": "p PRIMARY KEY (code_hash)",@@ -1904,7 +1905,9 @@"25 grant_profile text/text NULL","26 grant_revision integer/int4 NOT NULL DEFAULT 0","27 grant_repair_reasons ARRAY/_text NOT NULL DEFAULT '{}'::text[]",- "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "29 source_grant text/text NULL",+ "30 takes_holders ARRAY/_text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 796685335b..41d118a4d1 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -131,6 +131,7 @@"minion_self_fix_log.minion_self_fix_log_pkey": "p PRIMARY KEY (id)","oauth_clients.oauth_clients_complete_agent_grant": "c CHECK (((NOT (COALESCE(scope, ''::text) ~ '(^|[[:space:]])agent([[:space:]]|$)'::text)) OR ((COALESCE(cardinality(bound_tools), 0) > 0) AND (source_id IS NOT NULL) AND (bound_source_id IS NOT NULL) AND (bound_source_id = source_id) AND COALESCE((source_id = ANY (federated_read)), false) AND (((delegated_namespace = 'job'::text) AND (delegated_slug_prefixes IS NULL)) OR ((delegated_namespace = 'prefixes'::text) AND (COALESCE(cardinality(delegated_slug_prefixes), 0) > 0))) AND (bound_max_concurrent > 0))))","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))","oauth_clients.oauth_clients_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE RESTRICT","oauth_codes.oauth_codes_client_id_fkey": "f FOREIGN KEY (client_id) REFERENCES oauth_clients(client_id) ON DELETE CASCADE","oauth_codes.oauth_codes_pkey": "p PRIMARY KEY (code_hash)",@@ -1900,7 +1901,9 @@"25 grant_profile text/text NULL","26 grant_revision integer/int4 NOT NULL DEFAULT 0","27 grant_repair_reasons ARRAY/_text NOT NULL DEFAULT '{}'::text[]",- "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "29 source_grant text/text NULL",+ "30 takes_holders ARRAY/_text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.jsonindex 3a33f51e94..d6f2d673cd 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json@@ -88,6 +88,7 @@"minion_jobs.minion_jobs_pkey": "p PRIMARY KEY (id)","minion_jobs.minion_jobs_private_queue_owner_job_id_fkey": "f FOREIGN KEY (private_queue_owner_job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))","oauth_clients.oauth_clients_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE RESTRICT","oauth_codes.oauth_codes_client_id_fkey": "f FOREIGN KEY (client_id) REFERENCES oauth_clients(client_id) ON DELETE CASCADE","oauth_codes.oauth_codes_pkey": "p PRIMARY KEY (code_hash)",@@ -1375,7 +1376,9 @@"25 grant_profile text/text NULL","26 grant_revision integer/int4 NOT NULL DEFAULT 0","27 grant_repair_reasons ARRAY/_text NOT NULL DEFAULT '{}'::text[]",- "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "29 source_grant text/text NULL",+ "30 takes_holders ARRAY/_text NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.jsonindex 358ba68154..c3bf2e45b0 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json@@ -88,6 +88,7 @@"minion_jobs.minion_jobs_pkey": "p PRIMARY KEY (id)","minion_jobs.minion_jobs_private_queue_owner_job_id_fkey": "f FOREIGN KEY (private_queue_owner_job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))","oauth_clients.oauth_clients_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE RESTRICT","oauth_codes.oauth_codes_client_id_fkey": "f FOREIGN KEY (client_id) REFERENCES oauth_clients(client_id) ON DELETE CASCADE","oauth_codes.oauth_codes_pkey": "p PRIMARY KEY (code_hash)",@@ -1375,7 +1376,9 @@"25 grant_profile text/text NULL","26 grant_revision integer/int4 NOT NULL DEFAULT 0","27 grant_repair_reasons ARRAY/_text NOT NULL DEFAULT '{}'::text[]",- "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "29 source_grant text/text NULL",+ "30 takes_holders ARRAY/_text NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.jsonindex c53886296f..9e5c6ea9c4 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json@@ -88,6 +88,7 @@"minion_jobs.minion_jobs_pkey": "p PRIMARY KEY (id)","minion_jobs.minion_jobs_private_queue_owner_job_id_fkey": "f FOREIGN KEY (private_queue_owner_job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))","oauth_clients.oauth_clients_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE RESTRICT","oauth_codes.oauth_codes_client_id_fkey": "f FOREIGN KEY (client_id) REFERENCES oauth_clients(client_id) ON DELETE CASCADE","oauth_codes.oauth_codes_pkey": "p PRIMARY KEY (code_hash)",@@ -1374,7 +1375,9 @@"25 grant_profile text/text NULL","26 grant_revision integer/int4 NOT NULL DEFAULT 0","27 grant_repair_reasons ARRAY/_text NOT NULL DEFAULT '{}'::text[]",- "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "29 source_grant text/text NULL",+ "30 takes_holders ARRAY/_text NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.jsonindex 49158bae10..0ebe21b23b 100644--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json@@ -101,6 +101,7 @@"minion_jobs.minion_jobs_pkey": "p PRIMARY KEY (id)","minion_jobs.minion_jobs_private_queue_owner_job_id_fkey": "f FOREIGN KEY (private_queue_owner_job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))","oauth_clients.oauth_clients_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE RESTRICT","oauth_codes.oauth_codes_client_id_fkey": "f FOREIGN KEY (client_id) REFERENCES oauth_clients(client_id) ON DELETE CASCADE","oauth_codes.oauth_codes_pkey": "p PRIMARY KEY (code_hash)",@@ -1457,7 +1458,9 @@"25 grant_profile text/text NULL","26 grant_revision integer/int4 NOT NULL DEFAULT 0","27 grant_repair_reasons ARRAY/_text NOT NULL DEFAULT '{}'::text[]",- "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "29 source_grant text/text NULL",+ "30 takes_holders ARRAY/_text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 65013754c1..7ebb302f52 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -135,6 +135,7 @@"oauth_clients.fk_oauth_clients_bound_source": "f FOREIGN KEY (bound_source_id) REFERENCES sources(id) ON DELETE SET NULL","oauth_clients.oauth_clients_complete_agent_grant": "c CHECK (((NOT (COALESCE(scope, ''::text) ~ '(^|[[:space:]])agent([[:space:]]|$)'::text)) OR ((COALESCE(cardinality(bound_tools), 0) > 0) AND (source_id IS NOT NULL) AND (bound_source_id IS NOT NULL) AND (bound_source_id = source_id) AND COALESCE((source_id = ANY (federated_read)), false) AND (((delegated_namespace = 'job'::text) AND (delegated_slug_prefixes IS NULL)) OR ((delegated_namespace = 'prefixes'::text) AND (COALESCE(cardinality(delegated_slug_prefixes), 0) > 0))) AND (bound_max_concurrent > 0))))","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))","oauth_clients.oauth_clients_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE RESTRICT","oauth_codes.oauth_codes_client_id_fkey": "f FOREIGN KEY (client_id) REFERENCES oauth_clients(client_id) ON DELETE CASCADE","oauth_codes.oauth_codes_pkey": "p PRIMARY KEY (code_hash)",@@ -1916,7 +1917,9 @@"25 grant_profile text/text NULL","26 grant_revision integer/int4 NOT NULL DEFAULT 0","27 grant_repair_reasons ARRAY/_text NOT NULL DEFAULT '{}'::text[]",- "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "29 source_grant text/text NULL",+ "30 takes_holders ARRAY/_text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex ecdff86800..a93d775a9a 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -135,6 +135,7 @@"oauth_clients.fk_oauth_clients_bound_source": "f FOREIGN KEY (bound_source_id) REFERENCES sources(id) ON DELETE SET NULL","oauth_clients.oauth_clients_complete_agent_grant": "c CHECK (((NOT (COALESCE(scope, ''::text) ~ '(^|[[:space:]])agent([[:space:]]|$)'::text)) OR ((COALESCE(cardinality(bound_tools), 0) > 0) AND (source_id IS NOT NULL) AND (bound_source_id IS NOT NULL) AND (bound_source_id = source_id) AND COALESCE((source_id = ANY (federated_read)), false) AND (((delegated_namespace = 'job'::text) AND (delegated_slug_prefixes IS NULL)) OR ((delegated_namespace = 'prefixes'::text) AND (COALESCE(cardinality(delegated_slug_prefixes), 0) > 0))) AND (bound_max_concurrent > 0))))","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))","oauth_clients.oauth_clients_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE RESTRICT","oauth_codes.oauth_codes_client_id_fkey": "f FOREIGN KEY (client_id) REFERENCES oauth_clients(client_id) ON DELETE CASCADE","oauth_codes.oauth_codes_pkey": "p PRIMARY KEY (code_hash)",@@ -1916,7 +1917,9 @@"25 grant_profile text/text NULL","26 grant_revision integer/int4 NOT NULL DEFAULT 0","27 grant_repair_reasons ARRAY/_text NOT NULL DEFAULT '{}'::text[]",- "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "29 source_grant text/text NULL",+ "30 takes_holders ARRAY/_text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex a815cd1c99..c35b8be1e3 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -135,6 +135,7 @@"oauth_clients.fk_oauth_clients_bound_source": "f FOREIGN KEY (bound_source_id) REFERENCES sources(id) ON DELETE SET NULL","oauth_clients.oauth_clients_complete_agent_grant": "c CHECK (((NOT (COALESCE(scope, ''::text) ~ '(^|[[:space:]])agent([[:space:]]|$)'::text)) OR ((COALESCE(cardinality(bound_tools), 0) > 0) AND (source_id IS NOT NULL) AND (bound_source_id IS NOT NULL) AND (bound_source_id = source_id) AND COALESCE((source_id = ANY (federated_read)), false) AND (((delegated_namespace = 'job'::text) AND (delegated_slug_prefixes IS NULL)) OR ((delegated_namespace = 'prefixes'::text) AND (COALESCE(cardinality(delegated_slug_prefixes), 0) > 0))) AND (bound_max_concurrent > 0))))","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))","oauth_clients.oauth_clients_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE RESTRICT","oauth_codes.oauth_codes_client_id_fkey": "f FOREIGN KEY (client_id) REFERENCES oauth_clients(client_id) ON DELETE CASCADE","oauth_codes.oauth_codes_pkey": "p PRIMARY KEY (code_hash)",@@ -1912,7 +1913,9 @@"25 grant_profile text/text NULL","26 grant_revision integer/int4 NOT NULL DEFAULT 0","27 grant_repair_reasons ARRAY/_text NOT NULL DEFAULT '{}'::text[]",- "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "29 source_grant text/text NULL",+ "30 takes_holders ARRAY/_text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex ced7a2221d..cdea6832ac 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -507,7 +507,7 @@},{"category": "meta",- "message": "Version 201 (latest: 201)",+ "message": "Version 202 (latest: 202)","name": "schema_version","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 2c8c7f875d..f265bfb4a5 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -510,7 +510,7 @@},{"category": "meta",- "message": "Version 201 (latest: 201)",+ "message": "Version 202 (latest: 202)","name": "schema_version","status": "ok"},diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 412243d008..464012f932 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 196,+ "count": 197,"gaps": [17,18,@@ -29,7 +29,7 @@"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063","verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"},- "latest": 201,+ "latest": 202,"records": [{"handler": {@@ -2990,6 +2990,19 @@"transaction": "absent","verify": "absent","version": 201+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "lane_e_oauth_client_grant_axes",+ "sql": {+ "length": 179,+ "sha256": "3bc9490443e69f225bf65df711dbe889a52300ae2b1d5ab977206456c6ed22c8"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 202}],"versions": [@@ -3188,7 +3201,8 @@198,199,200,- 201+ 201,+ 202]},"normalizer": "migrations-record-v1"diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex 40df5ecbfd..c05832748d 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -131,6 +131,7 @@"minion_self_fix_log.minion_self_fix_log_pkey": "p PRIMARY KEY (id)","oauth_clients.oauth_clients_complete_agent_grant": "c CHECK (((NOT (COALESCE(scope, ''::text) ~ '(^|[[:space:]])agent([[:space:]]|$)'::text)) OR ((COALESCE(cardinality(bound_tools), 0) > 0) AND (source_id IS NOT NULL) AND (bound_source_id IS NOT NULL) AND (bound_source_id = source_id) AND COALESCE((source_id = ANY (federated_read)), false) AND (((delegated_namespace = 'job'::text) AND (delegated_slug_prefixes IS NULL)) OR ((delegated_namespace = 'prefixes'::text) AND (COALESCE(cardinality(delegated_slug_prefixes), 0) > 0))) AND (bound_max_concurrent > 0))))","oauth_clients.oauth_clients_pkey": "p PRIMARY KEY (client_id)",+ "oauth_clients.oauth_clients_source_grant_check": "c CHECK ((source_grant = 'none'::text))","oauth_clients.oauth_clients_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE RESTRICT","oauth_codes.oauth_codes_client_id_fkey": "f FOREIGN KEY (client_id) REFERENCES oauth_clients(client_id) ON DELETE CASCADE","oauth_codes.oauth_codes_pkey": "p PRIMARY KEY (code_hash)",@@ -1904,7 +1905,9 @@"25 grant_profile text/text NULL","26 grant_revision integer/int4 NOT NULL DEFAULT 0","27 grant_repair_reasons ARRAY/_text NOT NULL DEFAULT '{}'::text[]",- "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ "28 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "29 source_grant text/text NULL",+ "30 takes_holders ARRAY/_text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/oauth-client-grant-axes.test.ts b/test/oauth-client-grant-axes.test.tsnew file mode 100644index 0000000000..17b79c17c4--- /dev/null+++ b/test/oauth-client-grant-axes.test.ts@@ -0,0 +1,131 @@+/**+ * OAuth clients hold the two grant axes legacy tokens already had (Lane E):+ * `auth rescope --client <id> --sources none` (the explicit no-source grant)+ * and `--takes-holders a,b|none` (a per-client takes-holder allow-list).+ *+ * Protects: `--sources none` stores NULL source_id + empty federated_read ++ * source_grant 'none', verifies as NO_SOURCES, refuses reads, writes and the+ * publication of a write accepted before the change, and `--sources <id>`+ * restores it; per-client takes holders reach AuthInfo and the publication+ * reauthorization, `none` hides every take, invalid holders refuse; a+ * delegating agent cannot hold `none`; an untouched client keeps its grant.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { parseClientRescopeArgs } from '../src/core/grants/cli.ts';+import { rescopeClientGrant, readClientGrant } from '../src/core/grants/service.ts';+import { grantFromClient } from '../src/core/grants/model.ts';+import { NO_SOURCES } from '../src/core/source-id.ts';+import type { AuthInfo, OperationContext } from '../src/core/ops/contract.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { authorizeStoredRequest, authorizeTakeHolder, submissionAuthority } from '../src/core/persistence/authority.ts';+import { admitWrite } from '../src/core/persistence/journal.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('other','other') ON CONFLICT DO NOTHING");+ await engine.putPage('notes/axes', { type: 'note', title: 'Axes', compiled_truth: 'axes-marker prose', timeline: '', frontmatter: {} }, { sourceId: 'default' });+}, 120_000);++afterAll(async () => {+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+});++const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+const rescope = async (clientId: string, ...args: string[]) => {+ const parsed = parseClientRescopeArgs(clientId, args);+ return rescopeClientGrant(engine, clientId, parsed.patch, { actor: 'test', expectedRevision: (await readClientGrant(engine, clientId)).revision });+};+async function client(scopes = 'read write') {+ const p = provider();+ const { clientId, clientSecret } = await p.registerClientManual(`axes-${randomUUID().slice(0, 8)}`, ['client_credentials'], scopes, [], 'default', ['default', 'other']);+ const tokens = await p.exchangeClientCredentials(clientId, clientSecret!);+ return { clientId, token: tokens.access_token };+}+const verify = async (token: string) => await provider().verifyAccessToken(token) as unknown as AuthInfo;+const row = async (clientId: string) => (await engine.executeRaw<Record<string, unknown>>('SELECT * FROM oauth_clients WHERE client_id = $1', [clientId]))[0];++describe('--sources none for OAuth clients', () => {+ test('stores the explicit no-source grant, verifies as NO_SOURCES, refuses reads, writes and stale publication; --sources restores', async () => {+ const c = await client();+ const before = await verify(c.token);+ const ctx = { engine, config: { engine: 'pglite' }, sourceId: 'default', auth: before, remote: true, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'");+ const authority = await submissionAuthority(ctx, 'put_page', 'default', source.incarnation, 'notes/axes');+ const admitted = await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: 'default',+ sourceIncarnation: source.incarnation, slug: 'notes/axes', requestId: randomUUID(), callerIntent: {}, intent: {} });+ await authorizeStoredRequest(engine, admitted);++ const result = await rescope(c.clientId, '--sources', 'none');+ expect(result.after).toMatchObject({ sourcesNone: true, sourceId: null, federatedRead: [] });+ expect(grantFromClient(result.after).sources).toEqual({ kind: 'none' });+ expect(await row(c.clientId)).toMatchObject({ source_grant: 'none', source_id: null, federated_read: [] });+ await expect(authorizeStoredRequest(engine, admitted)).rejects.toMatchObject({ code: 'permission_denied' });++ const auth = await verify(c.token);+ expect(auth).toMatchObject({ sourceId: NO_SOURCES, allowedSources: [], hasSourceGrant: true, scopes: ['read', 'write'] });+ for (const [op, args] of [['search', { query: 'axes-marker' }], ['get_page', { slug: 'notes/axes' }], ['query', { query: 'axes-marker', source_id: 'other' }],+ ['put_page', { slug: 'notes/axes-new', content: 'x' }]] as const) {+ const out = await dispatchToolCall(engine, op, { ...args }, { remote: true, transport: 'http', sourceId: auth.sourceId, auth });+ expect({ op, error: JSON.parse(out.content[0].text).error }).toEqual({ op, error: 'permission_denied' });+ }++ const restored = await rescope(c.clientId, '--sources', 'default,other');+ expect(restored.after).toMatchObject({ sourcesNone: false, sourceId: 'default', federatedRead: ['default', 'other'] });+ expect(await row(c.clientId)).toMatchObject({ source_grant: null, source_id: 'default' });+ expect(await verify(c.token)).toMatchObject({ sourceId: 'default', allowedSources: ['default', 'other'] });+ }, 120_000);++ test('the legacy --source flag also leaves the no-source grant', async () => {+ const c = await client();+ await rescope(c.clientId, '--sources', 'none');+ const result = await rescope(c.clientId, '--source', 'other', '--federated-read', 'other');+ expect(result.after).toMatchObject({ sourcesNone: false, sourceId: 'other', federatedRead: ['other'] });+ });++ test('refuses --read-sources with none, and none on a delegating agent', async () => {+ expect(() => parseClientRescopeArgs('c', ['--sources', 'none', '--read-sources', 'other'])).toThrow(/takes no --read-sources/);+ const p = provider();+ const { clientId } = await p.registerClientManual(`axes-agent-${randomUUID().slice(0, 8)}`, ['client_credentials'], 'read agent', [], 'default', ['default'], undefined,+ { boundTools: ['search'], boundSourceId: 'default', boundSlugPrefixes: ['wiki/agents/'] });+ await expect(rescope(clientId, '--sources', 'none')).rejects.toMatchObject({ code: 'invalid_grant', reasons: expect.arrayContaining(['source_inactive']) });+ });+});++describe('per-client takes holders', () => {+ test('an untouched client keeps the default holders', async () => {+ const c = await client();+ expect((await verify(c.token)).takesHoldersAllowList).toBeUndefined();+ expect((await readClientGrant(engine, c.clientId)).takesHolders).toBeNull();+ });++ test('holders reach AuthInfo and publication reauthorization; none hides every take', async () => {+ const c = await client();+ const result = await rescope(c.clientId, '--takes-holders', 'world,brain,people/alice-example');+ expect(result.after.takesHolders).toEqual(['world', 'brain', 'people/alice-example']);+ expect(await row(c.clientId)).toMatchObject({ takes_holders: ['world', 'brain', 'people/alice-example'] });+ const auth = await verify(c.token);+ expect(auth.takesHoldersAllowList).toEqual(['world', 'brain', 'people/alice-example']);+ const authority = { remote: true, principal: { kind: 'oauth_client' as const, id: c.clientId }, takesHolders: auth.takesHoldersAllowList } as Parameters<typeof authorizeTakeHolder>[1];+ await authorizeTakeHolder(engine, authority, 'brain');+ await rescope(c.clientId, '--takes-holders', 'world');+ await expect(authorizeTakeHolder(engine, authority, 'brain')).rejects.toMatchObject({ code: 'permission_denied' });+ await rescope(c.clientId, '--takes-holders', 'none');+ expect((await verify(c.token)).takesHoldersAllowList).toEqual([]);+ expect(await row(c.clientId)).toMatchObject({ takes_holders: [] });+ });++ test('invalid holders refuse before any write', async () => {+ expect(() => parseClientRescopeArgs('c', ['--takes-holders', 'world,Not A Holder'])).toThrow(/Invalid takes holder/);+ });+});