Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(grants): no_source_grant refusals name the token at submission and POST /ingest
garrytanaec879f6284b
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 9b382d4db4..804856300d 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -87,7 +87,7 @@ a receipt can report has a row here.| `storage_error` | `storage_error` | The write did not commit for a reason with no more specific code. | Inspect the durable request with `gbrain write-request <id>` on the source host and follow its message. || `cancelled` | `cancelled` | The request was cancelled before it committed. Nothing was written. | Submit the write again if you still want it. || `permission_denied` | `permission_denied` | The caller is not allowed to make this write (a trust boundary, slug fence or lock). | Run it as a caller that has the permission, usually the trusted local CLI on the brain host. |-| <a id="no_source_grant"></a>`fence=no_source_grant` | `permission_denied` | The legacy bearer token's source grant is an explicit empty list (`gbrain auth rescope --token <name> --sources none`), or its sources axis has drifted (an older gbrain edited its `permissions` JSON after the grant moved to columns; doctor `legacy_token_grant_drift`), so it reads and writes no source. A write accepted before that change is refused at publication. It never falls back to the `default` source. | On the brain host: `gbrain auth rescope --token <name>` shows the grant and any drift. Empty grant: `gbrain auth rescope --token <name> --sources <id,...>`. Drift: ask the user which grant is intended, then `gbrain auth rescope --token <name> --adopt-permissions` or `--adopt-columns` (see [grant drift](../mcp/ADMIN.md#grant-drift)). Then retry with the **same** request ID. |+| <a id="no_source_grant"></a>`fence=no_source_grant` | `permission_denied` | The legacy bearer token's source grant is an explicit empty list (`gbrain auth rescope --token <name> --sources none`), or its sources axis has drifted (an older gbrain edited its `permissions` JSON after the grant moved to columns; doctor `legacy_token_grant_drift`), so it reads and writes no source. A write accepted before that change is refused at publication. It never falls back to the `default` source. | On the brain host: `gbrain auth rescope --token <name>` shows the grant and any drift. Empty grant: the refusal's `fix` carries the command with this token's id filled in (`gbrain auth rescope-token --id <token-id> --sources <id,...>`; the agent asks the user for the sources), or `gbrain auth list` when the token cannot be named. Drift: ask the user which grant is intended, then `gbrain auth rescope --token <name> --adopt-permissions` or `--adopt-columns` (see [grant drift](../mcp/ADMIN.md#grant-drift)). Then retry with the **same** request ID. || `scope_denied` | `scope_denied` | The caller's token or grant does not cover this operation or source. | Use a client with the needed scope and source grant. || `not_found` | `not_found` | The request, source or object named by the call does not exist. | Check the id; `gbrain sources list` lists sources. || `page_not_found` | `page_not_found` | The target page does not exist in that source, or disappeared during the write. | Check the slug and `--source`, then retry. |diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex 11ceb48cfd..51c2a968c0 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -449,7 +449,7 @@ retain request history, audit records, spending reservations, and settlement.| Duplicate client name | Inspect the reported existing client ID; recover its setup instead of creating another client. | brain host | none | the client list || Mutation response lost or timed out | Outcome may be unknown. Inspect the client/list before retrying; a transport error does not prove nothing changed. | brain host | none | the client list || `grant_conflict` | Inspect the current revision and preview the intended action again. | brain host | none | the preview of the intended action |-| `permission_denied` with `fence=no_source_grant` | The legacy token's source grant is an explicit empty list. Grant sources with `gbrain auth rescope --token <name> --sources <id,...>` ([legacy token grants](#legacy-token-grants)). | brain host | none | the token's grant in the client list |+| `permission_denied` with `fence=no_source_grant` | The legacy token's source grant is an explicit empty list. Grant sources with `gbrain auth rescope --token <name> --sources <id,...>` ([legacy token grants](#legacy-token-grants)); the refusal's `fix` names the token by `--id`. | brain host | none | the token's grant in the client list || Client/source list failed | Retry the failed request; an error is not an empty registration list or a missing source. | agent | none | the same list request || Public OAuth setup has no secret | Expected for authentication method `none`. Connect using native PKCE. | user | none | a native PKCE connection || Confidential secret delivery interrupted | Use `mcp admin setup … --credentials-out PRIVATE_FILE` to recover the retained delivery; never expose it in ordinary output. | brain host | `credentials` | the private credentials file exists |diff --git a/src/commands/serve-http-webhooks.ts b/src/commands/serve-http-webhooks.tsindex 058743c5ca..ac04f5a6b4 100644--- a/src/commands/serve-http-webhooks.ts+++ b/src/commands/serve-http-webhooks.ts@@ -26,6 +26,7 @@ import {import type { ServeHttpContext } from './serve-http.ts';import { NO_SOURCES } from '../core/source-id.ts';import { noSourceGrantError } from '../core/ops/context.ts';+import { renderAction } from '../core/agent-output.ts';/*** v0.46: normalize the per-event GitHub webhook payload shape into@@ -323,8 +324,9 @@ async function handleIngest(// operation grant through execution. A snapshot-bound client must use the// shared MCP write path until ingestion has that same policy contract.if (authInfo.sourceId === NO_SOURCES) {- const refusal = noSourceGrantError('POST /ingest');- res.status(403).json({ error: refusal.code, message: refusal.message, detail: refusal.detail, hint: refusal.suggestion, docs_url: refusal.docs });+ const refusal = noSourceGrantError('POST /ingest', authInfo);+ res.status(403).json({ error: refusal.code, message: refusal.message, detail: refusal.detail, hint: refusal.suggestion, docs_url: refusal.docs,+ fix: renderAction(refusal.fix!, { transport: 'http', isCallable: () => false, preapproved: () => false }) });return;}if (authInfo.allowedOperations != null || authInfo.grantProjectionDegraded) {diff --git a/src/core/ops/context.ts b/src/core/ops/context.tsindex acf219f36f..f67fb349b4 100644--- a/src/core/ops/context.ts+++ b/src/core/ops/context.ts@@ -494,10 +494,13 @@ export function opAllowedForBoundClient(* it never falls back to the `default` floor for reads or writes.*/export function noSourceGrantError(operation?: string, auth?: Pick<AuthInfo, 'clientId' | 'principal'>): OperationError {+ const fix = sourceGrantFix(auth);const err = opError('permission_denied',`${operation ? `${operation}: ` : ''}this token is granted no sources (its source grant is an explicit empty list).`,- "Ask the brain host's operator to grant this token at least one source (command in fix), then reconnect.",- { docs: 'docs/mcp/ADMIN.md#legacy-token-grants', fix: sourceGrantFix(auth) });+ fix.inputs+ ? "Ask the brain host's operator to grant this token at least one source (command in fix), then reconnect."+ : "Ask the brain host's operator to find this token in the token list (command in fix) and grant it at least one source, then reconnect.",+ { docs: 'docs/mcp/ADMIN.md#legacy-token-grants', fix });err.detail = 'fence=no_source_grant';return err;}diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.tsindex 7d246a3a2f..d994caf7cc 100644--- a/src/core/persistence/authority.ts+++ b/src/core/persistence/authority.ts@@ -25,7 +25,7 @@ function assertSkillWriteScopes(scopes: readonly string[], operation: string, re}}export async function submissionAuthority(ctx: OperationContext, operation: string, sourceId: string, sourceIncarnation: string, slug: string): Promise<WriteAuthority> {- if (ctx.auth?.sourceId === NO_SOURCES || sourceId === NO_SOURCES) throw noSourceGrantError(operation);+ if (ctx.auth?.sourceId === NO_SOURCES || sourceId === NO_SOURCES) throw noSourceGrantError(operation, ctx.auth);if (ctx.auth?.fenceProjectionDegraded || ctx.auth?.grantProjectionDegraded) deny('The grant projection is incomplete.');let principal: Principal;let localGrant: LocalGrant | undefined;diff --git a/test/auth-rescope-token.serial.test.ts b/test/auth-rescope-token.serial.test.tsindex f0fbab7fc8..6b06c56a7b 100644--- a/test/auth-rescope-token.serial.test.ts+++ b/test/auth-rescope-token.serial.test.ts@@ -19,7 +19,7 @@ import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { createEngine } from '../src/core/engine-factory.ts';import type { BrainEngine } from '../src/core/engine.ts';-import type { AuthInfo, OperationContext } from '../src/core/ops/contract.ts';+import type { AuthInfo, OperationContext, OperationError } from '../src/core/ops/contract.ts';import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';import { sqlQueryForEngine } from '../src/core/sql-query.ts';import { dispatchToolCall } from '../src/mcp/dispatch.ts';@@ -193,7 +193,11 @@ describe('explicit no-source grant is enforced (O-ENG-7)', () => {const response = await fetch(`http://127.0.0.1:${(server.address() as AddressInfo).port}/ingest`, { method: 'POST',headers: { authorization: `Bearer ${token}`, 'content-type': 'text/markdown' }, body: '# Capture\n\nno-source prose' });expect(response.status).toBe(403);- expect(await response.json()).toMatchObject({ error: 'permission_denied', detail: 'fence=no_source_grant', docs_url: 'docs/mcp/ADMIN.md#legacy-token-grants' });+ const [{ id }] = await engine.executeRaw<{ id: string }>("SELECT id::text AS id FROM access_tokens WHERE name = 'tok-ingest'");+ const body = await response.json();+ expect(body).toMatchObject({ error: 'permission_denied', detail: 'fence=no_source_grant', docs_url: 'docs/mcp/ADMIN.md#legacy-token-grants',+ fix: { argv: ['gbrain', 'auth', 'rescope-token', '--id', id, '--sources', '<sources>'], actor: 'host_admin', next: 'tell_user_to_run', inputs: [{ name: 'sources' }] } });+ expect(JSON.stringify(body)).not.toContain('<name>');const [jobs] = await engine.executeRaw<{ n: number }>("SELECT COUNT(*)::int AS n FROM minion_jobs WHERE name = 'ingest_capture'");expect(jobs.n).toBe(0);} finally { await new Promise<void>(resolve => server.close(() => resolve())); }@@ -220,4 +224,22 @@ describe('explicit no-source grant is enforced (O-ENG-7)', () => {await expect(authorizeStoredRequest(engine, row)).rejects.toMatchObject({ code: 'permission_denied' });});}, 120_000);++ test('a no-source refusal at submission names the token, and its fix restores the grant when run', async () => {+ const token = await mint('tok-submit');+ expect((await cli('auth', 'rescope-token', 'tok-submit', '--sources', 'none')).exitCode).toBe(0);+ const refusal = await withBrain(async engine => {+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ const auth = await provider.verifyAccessToken(token) as unknown as AuthInfo;+ const ctx = { engine, config: { engine: 'pglite' }, sourceId: 'default', auth, remote: true, transport: 'http', dryRun: false,+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'");+ return submissionAuthority(ctx, 'put_page', 'default', source.incarnation, 'notes/shared').then(() => null, (e: OperationError) => e);+ });+ const [{ id }] = await withBrain(engine => engine.executeRaw<{ id: string }>("SELECT id::text AS id FROM access_tokens WHERE name = 'tok-submit'"));+ expect(refusal).toMatchObject({ code: 'permission_denied', detail: 'fence=no_source_grant',+ fix: { argv: ['gbrain', 'auth', 'rescope-token', '--id', id, '--sources', '<sources>'], actor: 'host_admin' } });+ expect((await cli(...refusal!.fix!.argv!.slice(1).map(a => a === '<sources>' ? 'default' : a))).exitCode).toBe(0);+ expect((await permissions('tok-submit')).source_id).toEqual(['default']);+ }, 120_000);});diff --git a/test/ops-error-fixes-g1.test.ts b/test/ops-error-fixes-g1.test.tsindex 72540a3833..14ae6dd655 100644--- a/test/ops-error-fixes-g1.test.ts+++ b/test/ops-error-fixes-g1.test.ts@@ -51,6 +51,17 @@ describe('context.ts grant and fence refusals (B6/B7)', () => {expect(env.fix).toMatchObject({ next: 'tell_user_to_run', actor: 'host_admin' });});+ test('no-source grant without a nameable token lists the tokens instead of printing a placeholder', () => {+ for (const auth of [undefined, oauth({ clientId: 'tok', principal: { kind: 'legacy_token', id: 'not-a-uuid' } })]) {+ const e = noSourceGrantError('POST /ingest', auth);+ expect(e.fix).toMatchObject({ argv: ['gbrain', 'auth', 'list'], actor: 'host_admin', consent: [] });+ expect(e.fix?.inputs).toBeUndefined();+ expect(e.suggestion).toContain('token list');+ const env = toAgentError(e, { transport: 'http', op: 'put_page', render: render('http') });+ expect(JSON.stringify(env)).not.toMatch(/<name>|<sources>|<id/);+ }+ });+test('operation-snapshot refusal regrants the exact op for an OAuth client', async () => {const e = await caught(() => enforceBoundClientOpAllowList(oauth({ allowedOperations: ['get_page'] }), { name: 'put_page', scope: 'write', mutating: true }));expect(e.detail).toBe('fence=operation_grant');