Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(persistence): our own implementation of the #5920 fix (#5920)

time-attackaf4fc0caa3e8
diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.ts
index 1f2e9ac432..4f9b7a4516 100644
--- a/src/core/persistence/authority.ts
+++ b/src/core/persistence/authority.ts
@@ -18,15 +18,20 @@ function operationAllowed(ops: unknown, operation: string): boolean { return ops
function 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; }
+/** A minions job id usable as a namespace key: a positive safe integer (never a string, NaN, zero or fraction). */
+function jobNamespaceKey(value: unknown): number | undefined {
+ return Number.isSafeInteger(value) && (value as number) > 0 ? value as number : undefined;
+}
/**
- * 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.
+ * Slug patterns an OAuth client's live grant delegates. A `prefixes` grant lists
+ * them; a `job` grant (prefixes stored NULL) delegates only the accepting job's
+ * own wiki/agents/<id>/ tree. Every other shape delegates 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 liveDelegation(row: Record<string, unknown>, jobId: unknown): readonly string[] {
+ const { delegated_namespace: mode, delegated_slug_prefixes: listed } = row;
+ if (mode === 'prefixes') return strings(listed) ? listed : [];
+ const key = jobNamespaceKey(jobId);
+ return mode === 'job' && listed === null && key !== undefined ? [`wiki/agents/${key}/*`] : [];
}
function skillWrite(operation: string): boolean {
return ['put_skill', 'delete_skill', 'adopt_skillpack'].includes(operation);
@@ -50,6 +55,7 @@ export async function submissionAuthority(ctx: OperationContext, operation: stri
localGrant = verified.grant;
if (!localGrant.sourceIds.includes('*') && !localGrant.sourceIds.includes(sourceId)) deny('The local grant excludes this source.');
}
+ const delegatedJobId = ctx.auth && ctx.viaSubagent ? jobNamespaceKey(ctx.subagentId) : undefined;
const a: WriteAuthority = {
version: 1, principal, remote: ctx.remote !== false, sourceId, sourceIncarnation,
excludePrivate: await excludesPrivateWrites(ctx.engine, ctx.remote !== false),
@@ -59,7 +65,7 @@ export async function submissionAuthority(ctx: OperationContext, operation: stri
operations: 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 } : {}),
+ ...(delegatedJobId === undefined ? {} : { delegatedJobId }),
delegatedPrefixes: ctx.allowedSlugPrefixes?.length ? [...ctx.allowedSlugPrefixes]
: typeof ctx.subagentId === 'number' ? [`wiki/agents/${ctx.subagentId}/*`] : [] } : {}),
};
@@ -79,7 +85,7 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, opera
const 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,delegated_namespace FROM oauth_clients WHERE client_id=$1${suffix}`, [a.principal.id]);
+ bound_slug_prefixes,bound_tools,delegated_namespace,delegated_slug_prefixes 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);
@@ -87,7 +93,7 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, opera
if (!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 (!matchesSlugAllowList(slug, currentDelegatedPrefixes(row, a.subagentId))) deny('The delegated namespace was narrowed.');
+ if (!matchesSlugAllowList(slug, liveDelegation(row, a.delegatedJobId))) 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.ts
index 3aeae27c14..3a3e2847ba 100644
--- a/src/core/persistence/model.ts
+++ b/src/core/persistence/model.ts
@@ -18,8 +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;
+ /** Minions job that accepted an OAuth-delegated write; a live `job` grant re-derives only that job's namespace from it. */
+ delegatedJobId?: 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.ts
index 056ba350ca..c4c1700462 100644
--- a/test/e2e/minions-authority-parity.test.ts
+++ b/test/e2e/minions-authority-parity.test.ts
@@ -59,35 +59,34 @@ 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 () => {
+ test('a delegated job id is a JSONB number and only that number replays (#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 clientId = `example-job-delegate-${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, 'example-delegate', 'fixture-hash', 'read agent', 'default', 'default', ARRAY['default']::text[], ARRAY['put_page'], 'job', NULL)`, [clientId]);
+ const principal = { kind: 'oauth_client' as const, id: clientId };
+ const delegated: OperationContext = { ...ctx(), viaSubagent: true, subagentId: 9031,
+ auth: { token: 'fixture-token', clientId, principal, 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 published = await submitPageMutation(delegated, { operation: 'put_page', params: { slug: 'wiki/agents/9031/digest', content: 'Job digest', request_id } });
+ expect(published.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' });
+ const typed = () => engine.executeRaw<{ kind: string | null }>(
+ `SELECT jsonb_typeof(authority->'delegatedJobId') AS kind FROM persistence_requests WHERE principal_id = $1 AND request_id = $2::uuid`, [clientId, request_id]);
+ expect((await typed())[0].kind).toBe('number');
+ await authorizeStoredRequest(engine, (await getWriteRequest(engine, principal, request_id))!);
+ for (const stored of ['"9031"', '9032', 'null', '9031.5']) {
+ await engine.executeRaw(`UPDATE persistence_requests SET authority = jsonb_set(authority, '{delegatedJobId}', $3::text::jsonb)
+ WHERE principal_id = $1 AND request_id = $2::uuid`, [clientId, request_id, stored]);
+ await expect(authorizeStoredRequest(engine, (await getWriteRequest(engine, principal, request_id))!)).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' });
+ await engine.executeRaw(`UPDATE persistence_requests SET authority = jsonb_set(authority, '{delegatedJobId}', '9031'::jsonb)
+ WHERE principal_id = $1 AND request_id = $2::uuid`, [clientId, request_id]);
+ await authorizeStoredRequest(engine, (await getWriteRequest(engine, principal, request_id))!);
+ await engine.executeRaw("UPDATE oauth_clients SET delegated_namespace = 'prefixes', delegated_slug_prefixes = ARRAY['wiki/agents/9032/*'] WHERE client_id = $1", [clientId]);
+ await expect(authorizeStoredRequest(engine, (await getWriteRequest(engine, principal, request_id))!)).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 });
diff --git a/test/persistence-page-authority.test.ts b/test/persistence-page-authority.test.ts
index 2ddc3b8bb4..96dece8c08 100644
--- a/test/persistence-page-authority.test.ts
+++ b/test/persistence-page-authority.test.ts
@@ -1,4 +1,4 @@
-import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -98,70 +98,117 @@ test('sandboxed subagents keep intentional database-only writes despite a config
}
});
-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();
+describe('OAuth delegated job namespace (#5920)', () => {
+ const JOB = 4107;
+ const delegatedClient = async (engine: BrainEngine, namespace: 'job' | 'prefixes', prefixes: string[] | null) => {
+ const clientId = `delegated-${namespace}-${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,'example-delegate','fixture-hash','read agent',$2,$2,ARRAY[$2]::text[],ARRAY['mcp__gbrain__put_page'],$3,$4::text[])`,
+ [clientId, sourceId, namespace, prefixes]);
+ return clientId;
+ };
+ const delegatedCtx = (engine: BrainEngine, clientId: string, extra: Partial<OperationContext> = {}): OperationContext => ({
+ ...context(engine), viaSubagent: true, subagentId: JOB, ...extra,
+ auth: { token: 'fixture-token', clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['read', 'agent'], sourceId },
+ });
+ const write = (ctx: OperationContext, slug: string, request_id: string = randomUUID()) =>
+ submitPageMutation(ctx, { operation: 'put_page', params: { slug, content: `Delegated body for ${slug}`, request_id } });
+ const grant = (engine: BrainEngine, clientId: string, assignments: string) =>
+ engine.executeRaw(`UPDATE oauth_clients SET ${assignments} WHERE client_id=$1`, [clientId]);
+ const denied = { code: 'permission_denied' };
+
+ test('a job grant publishes and replays inside its own job tree only', async () => {
+ for (const engine of engines) {
+ const clientId = await delegatedClient(engine, 'job', null);
+ const ctx = delegatedCtx(engine, clientId);
+ const request_id = randomUUID();
+ const own = `wiki/agents/${JOB}/summary`;
+ expect((await write(ctx, own, request_id)).state).toBe('committed');
+ expect((await engine.getPage(own, { sourceId }))?.compiled_truth).toContain('Delegated body');
+ const receipt = (await getWriteRequest(engine, ctx.auth!.principal!, request_id))!;
+ expect(receipt.authority.delegatedJobId).toBe(JOB);
+ await authorizeStoredRequest(engine, receipt);
+ expect((await write(ctx, own, request_id)).state).toBe('committed');
+ for (const outside of [`wiki/agents/${JOB + 1}/summary`, `wiki/agents/${JOB}0/summary`, `wiki/agents/${JOB}x/summary`,
+ `wiki/agents/${JOB}`, 'wiki/agents/summary', 'notes/summary']) {
+ await expect(write(ctx, outside)).rejects.toMatchObject(denied);
+ expect(await engine.getPage(outside, { 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' });
+ });
+
+ test('a stored receipt cannot borrow another job id or a malformed one', async () => {
+ for (const engine of engines) {
+ const clientId = await delegatedClient(engine, 'job', null);
+ const ctx = delegatedCtx(engine, clientId);
+ const request_id = randomUUID();
+ await write(ctx, `wiki/agents/${JOB}/ledger`, request_id);
+ const receipt = (await getWriteRequest(engine, ctx.auth!.principal!, request_id))!;
+ for (const forged of [JOB + 1, JOB - 1, undefined, null, 0, -JOB, JOB + 0.5, Number.NaN, Infinity, String(JOB),
+ Number.MAX_SAFE_INTEGER + 2, [JOB], { id: JOB }]) {
+ await expect(authorizeStoredRequest(engine, { ...receipt, authority: { ...receipt.authority, delegatedJobId: forged as number } }))
+ .rejects.toMatchObject(denied);
+ }
+ await expect(authorizeStoredRequest(engine, { ...receipt, slug: `wiki/agents/${JOB + 1}/ledger` })).rejects.toMatchObject(denied);
+ await expect(authorizeStoredRequest(engine, { ...receipt, authority: { ...receipt.authority, sourceId: 'example-foreign-source' } }))
+ .rejects.toMatchObject(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' });
+ });
+
+ test('a delegated job context without a usable job id is denied and writes nothing', async () => {
+ for (const engine of engines) {
+ const clientId = await delegatedClient(engine, 'job', null);
+ for (const subagentId of [Number.NaN, 0, -JOB, JOB + 0.25]) {
+ for (const slug of [`wiki/agents/${JOB}/note`, 'wiki/agents/0/note', 'wiki/agents/NaN/note']) {
+ await expect(write(delegatedCtx(engine, clientId, { subagentId }), slug)).rejects.toMatchObject(denied);
+ expect(await engine.getPage(slug, { sourceId })).toBeNull();
+ }
+ }
+ await expect(submitPageMutation(delegatedCtx(engine, clientId), { operation: 'put_page', params: {
+ slug: `wiki/agents/${JOB}/note`, content: 'Elsewhere', request_id: randomUUID(), source_id: 'example-foreign-source',
+ } })).rejects.toMatchObject(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' });
- }
+ test('narrowing, switching or revoking the live job grant stops replay', async () => {
+ for (const engine of engines) {
+ const clientId = await delegatedClient(engine, 'job', null);
+ const ctx = delegatedCtx(engine, clientId);
+ const request_id = randomUUID();
+ await write(ctx, `wiki/agents/${JOB}/plan`, request_id);
+ const receipt = (await getWriteRequest(engine, ctx.auth!.principal!, request_id))!;
+ const changes = [
+ ["bound_tools=ARRAY['mcp__gbrain__get_page']", "bound_tools=ARRAY['mcp__gbrain__put_page']"],
+ ["delegated_namespace='prefixes', delegated_slug_prefixes=ARRAY['notes/*']", "delegated_namespace='job', delegated_slug_prefixes=NULL"],
+ ["scope='read'", "scope='read agent'"],
+ ['deleted_at=now()', 'deleted_at=NULL'],
+ ];
+ for (const [narrow, restore] of changes) {
+ await grant(engine, clientId, narrow);
+ await expect(authorizeStoredRequest(engine, receipt)).rejects.toMatchObject(denied);
+ await grant(engine, clientId, restore);
+ await authorizeStoredRequest(engine, receipt);
+ }
+ }
+ });
+
+ test('explicit prefix grants keep intersecting and never gain a job tree', async () => {
+ for (const engine of engines) {
+ const clientId = await delegatedClient(engine, 'prefixes', ['notes/delegated/*']);
+ const ctx = delegatedCtx(engine, clientId, { allowedSlugPrefixes: ['notes/delegated/*'] });
+ const request_id = randomUUID();
+ expect((await write(ctx, 'notes/delegated/report', request_id)).state).toBe('committed');
+ await expect(write(ctx, `wiki/agents/${JOB}/report`)).rejects.toMatchObject(denied);
+ const receipt = (await getWriteRequest(engine, ctx.auth!.principal!, request_id))!;
+ await authorizeStoredRequest(engine, receipt);
+ await grant(engine, clientId, "delegated_slug_prefixes=ARRAY['notes/elsewhere/*']");
+ await expect(authorizeStoredRequest(engine, receipt)).rejects.toMatchObject(denied);
+ await grant(engine, clientId, "delegated_slug_prefixes=ARRAY['notes/*']");
+ await authorizeStoredRequest(engine, receipt);
+ await expect(authorizeStoredRequest(engine, { ...receipt, slug: 'notes/report' })).rejects.toMatchObject(denied);
+ await grant(engine, clientId, "delegated_namespace='job', delegated_slug_prefixes=NULL");
+ await expect(authorizeStoredRequest(engine, receipt)).rejects.toMatchObject(denied);
+ }
+ });
});