Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(mcp): retain an OAuth job's id so its delegated write replays (#5920)
time-attackfc7b57717697
diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.tsindex 39c4511002..1f2e9ac432 100644--- a/src/core/persistence/authority.ts+++ b/src/core/persistence/authority.ts@@ -18,6 +18,16 @@ function operationAllowed(ops: unknown, operation: string): boolean { return opsfunction prefixAllowed(prefixes: string[] | null | undefined, slug: string): boolean {return prefixes == null || slugUnderBoundPrefixes(prefixes, slug);}+function nativeJobId(id: unknown): id is number { return typeof id === 'number' && Number.isSafeInteger(id) && id > 0; }+/**+ * The delegated namespace the client's CURRENT grant allows: its stored+ * prefixes, or for the native job namespace (prefixes stored NULL) only the+ * retained job's own `wiki/agents/<id>/*`. Anything else allows nothing.+ */+function currentDelegatedPrefixes(row: Record<string, unknown>, subagentId: unknown): string[] {+ if (row.delegated_namespace === 'job') return row.delegated_slug_prefixes === null && nativeJobId(subagentId) ? [`wiki/agents/${subagentId}/*`] : [];+ return row.delegated_namespace === 'prefixes' && strings(row.delegated_slug_prefixes) ? row.delegated_slug_prefixes : [];+}function skillWrite(operation: string): boolean {return ['put_skill', 'delete_skill', 'adopt_skillpack'].includes(operation);}@@ -49,6 +59,7 @@ export async function submissionAuthority(ctx: OperationContext, operation: strioperations: ctx.auth?.allowedOperations ? [...ctx.auth.allowedOperations] : localGrant?.operations ?? null,slugPrefixes: ctx.auth?.boundSlugPrefixes ? [...ctx.auth.boundSlugPrefixes] : localGrant?.slugPrefixes ?? null,...(ctx.viaSubagent ? { restrictedNamespace: true, delegated: !!ctx.auth,+ ...(nativeJobId(ctx.subagentId) ? { subagentId: ctx.subagentId } : {}),delegatedPrefixes: ctx.allowedSlugPrefixes?.length ? [...ctx.allowedSlugPrefixes]: typeof ctx.subagentId === 'number' ? [`wiki/agents/${ctx.subagentId}/*`] : [] } : {}),};@@ -68,7 +79,7 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, operaconst suffix = lock ? ' FOR SHARE' : '';if (a.principal.kind === 'oauth_client') {const [row] = await engine.executeRaw<Record<string, unknown>>(`SELECT deleted_at,scope,source_id,allowed_operations,- bound_slug_prefixes,bound_tools,delegated_slug_prefixes FROM oauth_clients WHERE client_id=$1${suffix}`, [a.principal.id]);+ bound_slug_prefixes,bound_tools,delegated_slug_prefixes,delegated_namespace FROM oauth_clients WHERE client_id=$1${suffix}`, [a.principal.id]);if (!row || row.deleted_at != null || row.source_id !== a.sourceId) deny('The owning OAuth client is revoked or its source changed.');const scopes = typeof row.scope === 'string' ? row.scope.split(/\s+/) : [];assertSkillWriteScopes(scopes, operation, a.remote);@@ -76,7 +87,7 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, operaif (!hasScope(scopes, a.delegated ? 'agent' : 'write')) deny('The current OAuth grant no longer permits this write.');if (a.delegated) {if (!strings(row.bound_tools) || !row.bound_tools.some(t => t.replace(/^(?:brain_|mcp__gbrain__)/, '') === operation)) deny('The delegated tool was removed from the current grant.');- if (!strings(row.delegated_slug_prefixes) || !matchesSlugAllowList(slug, row.delegated_slug_prefixes)) deny('The delegated namespace was narrowed.');+ if (!matchesSlugAllowList(slug, currentDelegatedPrefixes(row, a.subagentId))) deny('The delegated namespace was narrowed.');} else if (!operationAllowed(row.allowed_operations, operation) ||(row.bound_slug_prefixes != null && (!strings(row.bound_slug_prefixes) || !prefixAllowed(row.bound_slug_prefixes, slug)))) deny('The current operation or slug grant excludes this write.');return;diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex 6b3858edcc..3aeae27c14 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -18,6 +18,8 @@ export interface WriteAuthority {slugPrefixes: string[] | null;delegatedPrefixes?: string[] | null;delegated?: boolean;+ /** The native job id (positive safe integer) a job-namespace delegated write was accepted under; replay derives the current job prefix from it. */+ subagentId?: number;takesHolders?: string[] | null;/** Actual holders touched by a published take mutation; retained after intent compaction. */takeHoldersUsed?: string[];diff --git a/test/e2e/minions-authority-parity.test.ts b/test/e2e/minions-authority-parity.test.tsindex 3c2d48a937..056ba350ca 100644--- a/test/e2e/minions-authority-parity.test.ts+++ b/test/e2e/minions-authority-parity.test.ts@@ -11,6 +11,11 @@ import { prepareRemoteJob, authorizeJobExecution, assertNoUnreviewedJobs } fromimport { authorizeLegacyJobs } from '../../src/core/minions/authorize-legacy.ts';import type { OperationContext } from '../../src/core/ops/contract.ts';import { withEnv } from '../helpers/with-env.ts';+import { randomUUID } from 'node:crypto';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { authorizeStoredRequest } from '../../src/core/persistence/authority.ts';+import { getWriteRequest } from '../../src/core/persistence/journal.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';const suite = hasDatabase() ? describe : describe.skip;suite('Postgres queued authority parity', () => {@@ -29,6 +34,7 @@ suite('Postgres queued authority parity', () => {afterAll(async () => {// Later files on the same database start real workers, which refuse to run while any unreviewed job remains.await getEngine().executeRaw('DELETE FROM minion_jobs');+ await disposePersistenceConsumer(getEngine());await teardownDB();if (sandbox) rmSync(sandbox, { recursive: true, force: true });});@@ -53,6 +59,36 @@ suite('Postgres queued authority parity', () => {await getEngine().executeRaw("UPDATE oauth_clients SET deleted_at = now() WHERE client_id = 'authority-test-client'");await expect(queue.replayJob(job.id)).rejects.toThrow('revoked');});+ test('an OAuth job-namespace write retains its job id in JSONB authority and replays only for that job (#5920)', async () => {+ const engine = getEngine();+ const clientId = `job-writer-${randomUUID()}`;+ await engine.executeRaw(`INSERT INTO oauth_clients+ (client_id, client_name, client_secret_hash, scope, source_id, bound_source_id, federated_read, bound_tools, delegated_namespace)+ VALUES ($1, 'example-job-writer', 'fixture-hash', 'read agent', 'default', 'default', ARRAY['default']::text[], ARRAY['put_page'], 'job')`, [clientId]);+ const jobCtx: OperationContext = { ...ctx(), viaSubagent: true, subagentId: 382,+ auth: { token: 'test-only', clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['read', 'agent'], sourceId: 'default' } };+ const request_id = randomUUID();+ await withEnv({ GBRAIN_HOME: sandbox }, async () => {+ const result = await submitPageMutation(jobCtx, { operation: 'put_page', params: { slug: 'wiki/agents/382/result', content: 'Owned job output', request_id } });+ expect(result.state).toBe('committed');+ });+ const [stored] = await engine.executeRaw<{ kind: string; id: number }>(+ `SELECT jsonb_typeof(authority->'subagentId') AS kind, (authority->>'subagentId')::int AS id+ FROM persistence_requests WHERE principal_id = $1 AND request_id = $2::uuid`, [clientId, request_id]);+ expect(stored).toEqual({ kind: 'number', id: 382 });+ const row = (await getWriteRequest(engine, jobCtx.auth!.principal!, request_id))!;+ await authorizeStoredRequest(engine, row);+ for (const subagentId of [383, Number.NaN, undefined]) {+ await expect(authorizeStoredRequest(engine, { ...row, authority: { ...row.authority, subagentId } }))+ .rejects.toMatchObject({ code: 'permission_denied' });+ }+ await engine.executeRaw("UPDATE oauth_clients SET bound_tools = ARRAY['get_page'] WHERE client_id = $1", [clientId]);+ await expect(authorizeStoredRequest(engine, row)).rejects.toMatchObject({ code: 'permission_denied' });+ await engine.executeRaw("UPDATE oauth_clients SET bound_tools = ARRAY['put_page'], delegated_namespace = 'prefixes', delegated_slug_prefixes = ARRAY['notes/*'] WHERE client_id = $1", [clientId]);+ await expect(authorizeStoredRequest(engine, row)).rejects.toMatchObject({ code: 'permission_denied' });+ await engine.executeRaw("UPDATE oauth_clients SET delegated_namespace = 'job', delegated_slug_prefixes = NULL, deleted_at = now() WHERE client_id = $1", [clientId]);+ await expect(authorizeStoredRequest(engine, row)).rejects.toMatchObject({ code: 'permission_denied' });+ });test('legacy CAS rollback, NULL cutover gate, and raw-object stamp match PGLite', async () => {const job = await queue.add('maintenance', { example: true });await getEngine().executeRaw('UPDATE minion_jobs SET submission_authority = NULL WHERE id = $1', [job.id]);diff --git a/test/persistence-page-authority.test.ts b/test/persistence-page-authority.test.tsindex f70384c7a2..2ddc3b8bb4 100644--- a/test/persistence-page-authority.test.ts+++ b/test/persistence-page-authority.test.ts@@ -97,3 +97,71 @@ test('sandboxed subagents keep intentional database-only writes despite a configexpect(bindings).toHaveLength(0);}});++test('OAuth job namespaces survive publication and replay without authorizing another job', async () => {+ for (const engine of engines) {+ const clientId = `job-writer-${randomUUID()}`;+ await engine.executeRaw(`INSERT INTO oauth_clients+ (client_id,client_name,client_secret_hash,scope,source_id,bound_source_id,federated_read,bound_tools,delegated_namespace)+ VALUES($1,'Job writer','test-only','read agent',$2,$2,ARRAY[$2]::text[],ARRAY['put_page'],'job')`, [clientId, sourceId]);+ const ctx: OperationContext = { ...context(engine), viaSubagent: true, subagentId: 382,+ auth: { token: 'test-only', clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['read', 'agent'], sourceId } };+ const request_id = randomUUID(), slug = 'wiki/agents/382/result';+ const params = { slug, content: 'Owned job output', request_id };+ const result = await submitPageMutation(ctx, { operation: 'put_page', params });+ expect(result.state).toBe('committed');+ expect((await engine.getPage(slug, { sourceId }))!.compiled_truth).toContain('Owned job output');+ const row = (await getWriteRequest(engine, ctx.auth!.principal!, request_id))!;+ expect(row.authority.subagentId).toBe(382);+ await authorizeStoredRequest(engine, row);+ expect((await submitPageMutation(ctx, { operation: 'put_page', params })).state).toBe('committed');+ for (const foreign of ['wiki/agents/383/result', 'wiki/agents/382evil/result', 'wiki/agents/382']) {+ await expect(submitPageMutation(ctx, { operation: 'put_page', params: {+ slug: foreign, content: 'Outside namespace', request_id: randomUUID(),+ } })).rejects.toMatchObject({ code: 'permission_denied' });+ expect(await engine.getPage(foreign, { sourceId })).toBeNull();+ }+ // Legacy or malformed retained receipts cannot infer a job ID from their target.+ for (const subagentId of [undefined, null, 0, -1, 1.5, Number.NaN, '382']) {+ await expect(authorizeStoredRequest(engine, { ...row, authority: { ...row.authority, subagentId: subagentId as number } }))+ .rejects.toMatchObject({ code: 'permission_denied' });+ }+ // A retained authority naming a foreign job cannot replay this job's write.+ await expect(authorizeStoredRequest(engine, { ...row, authority: { ...row.authority, subagentId: 383 } }))+ .rejects.toMatchObject({ code: 'permission_denied' });+ // A job context without a native id is never retained and gains no namespace.+ for (const subagentId of [Number.NaN, 0, -382]) {+ await expect(submitPageMutation({ ...ctx, subagentId }, { operation: 'put_page', params: {+ slug: 'wiki/agents/382/result', content: 'No native job id', request_id: randomUUID(),+ } })).rejects.toMatchObject({ code: 'permission_denied' });+ }+ await engine.executeRaw("UPDATE oauth_clients SET bound_tools=ARRAY['get_page'] WHERE client_id=$1", [clientId]);+ await expect(authorizeStoredRequest(engine, row)).rejects.toMatchObject({ code: 'permission_denied' });+ await engine.executeRaw("UPDATE oauth_clients SET bound_tools=ARRAY['put_page'] WHERE client_id=$1", [clientId]);+ await engine.executeRaw("UPDATE oauth_clients SET delegated_namespace='prefixes', delegated_slug_prefixes=ARRAY['notes/*'] WHERE client_id=$1", [clientId]);+ await expect(authorizeStoredRequest(engine, row)).rejects.toMatchObject({ code: 'permission_denied' });+ await engine.executeRaw("UPDATE oauth_clients SET delegated_namespace='job', delegated_slug_prefixes=NULL, scope='read' WHERE client_id=$1", [clientId]);+ await expect(authorizeStoredRequest(engine, row)).rejects.toMatchObject({ code: 'permission_denied' });+ }+});++test('explicit delegated prefixes still intersect the retained and current grants', async () => {+ for (const engine of engines) {+ const clientId = `prefix-writer-${randomUUID()}`;+ await engine.executeRaw(`INSERT INTO oauth_clients+ (client_id,client_name,client_secret_hash,scope,source_id,bound_source_id,federated_read,bound_tools,delegated_namespace,delegated_slug_prefixes)+ VALUES($1,'Prefix writer','test-only','read agent',$2,$2,ARRAY[$2]::text[],ARRAY['put_page'],'prefixes',ARRAY['notes/delegated/*'])`, [clientId, sourceId]);+ const ctx: OperationContext = { ...context(engine), viaSubagent: true, subagentId: 383, allowedSlugPrefixes: ['notes/delegated/*'],+ auth: { token: 'test-only', clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['read', 'agent'], sourceId } };+ const request_id = randomUUID();+ expect((await submitPageMutation(ctx, { operation: 'put_page', params: {+ slug: 'notes/delegated/result', content: 'Explicitly delegated output', request_id,+ } })).state).toBe('committed');+ const row = (await getWriteRequest(engine, ctx.auth!.principal!, request_id))!;+ await authorizeStoredRequest(engine, row);+ await engine.executeRaw("UPDATE oauth_clients SET delegated_slug_prefixes=ARRAY['notes/*'] WHERE client_id=$1", [clientId]);+ await expect(authorizeStoredRequest(engine, { ...row, slug: 'notes/other/result' })).rejects.toMatchObject({ code: 'permission_denied' });+ await engine.executeRaw("UPDATE oauth_clients SET delegated_slug_prefixes=ARRAY['notes/narrower/*'] WHERE client_id=$1", [clientId]);+ await expect(authorizeStoredRequest(engine, row)).rejects.toMatchObject({ code: 'permission_denied' });+ }+});