Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(qm): scope-write lock order and grant checks from /ship review (GST-1113)

garrytan6c703c8adf6b
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 511eeb17ee..0989fde8c7 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -1173,13 +1173,18 @@ async function runFederate(engine: BrainEngine, args: string[], value: boolean):
console.error(`Source "${id}" not found.`);
process.exit(4);
}
- if (value) await (await import('../core/access/attest-sources.ts')).assertNotScopeSource(engine, id);
- const config = parseConfig(src.config);
- config.federated = value;
- await engine.executeRaw(
- `UPDATE sources SET config = $1::text::jsonb WHERE id = $2`,
- [JSON.stringify(normalizeSourceConfig(config)), id],
- );
+ // GST-1113: the mark check and the config write hold the source row, so a concurrent --attest-sources mark commits
+ // before (and federate refuses) or after (and sees federated, so it refuses), never between them.
+ await engine.transaction(async tx => {
+ const [row] = await tx.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id = $1 FOR UPDATE', [id]);
+ if (value) await (await import('../core/access/attest-sources.ts')).assertNotScopeSource(tx, id);
+ const config = parseConfig(row?.config ?? src.config);
+ config.federated = value;
+ await tx.executeRaw(
+ `UPDATE sources SET config = $1::text::jsonb WHERE id = $2`,
+ [JSON.stringify(normalizeSourceConfig(config)), id],
+ );
+ });
console.log(`Source "${id}" is now ${value ? 'federated (appears in cross-source default search)' : 'isolated (only searched when explicitly named)'}.`);
// v0.40 D19: auto-submit embed-backfill when coverage < 100%. Federation
diff --git a/src/core/access/attest-sources.ts b/src/core/access/attest-sources.ts
index 57e8001295..b214d386ea 100644
--- a/src/core/access/attest-sources.ts
+++ b/src/core/access/attest-sources.ts
@@ -54,16 +54,20 @@ type Db = BrainEngine | SqlQuery;
const sqlOf = (db: Db): SqlQuery => typeof db === 'function' ? db : sqlQueryForEngine(db);
/**
- * The marked scope sources among `ids`. `lock` takes their rows FOR UPDATE (inside the caller's transaction), so a grant
- * write and an attest_sources change on the same source serialize instead of each missing the other's commit.
+ * The marked scope sources among `ids`. `lock` takes their rows in id order inside the caller's transaction: a grant
+ * write FOR SHARE, an attest_sources change FOR UPDATE on the sources it marks, so the two serialize instead of each
+ * missing the other's commit, while grant writes and publications (source FOR SHARE, then credential) never wait on
+ * each other's source locks. Callers lock their credential row first.
*/
-export async function markedScopeSources(db: Db, ids: readonly string[], lock = false): Promise<Set<string>> {
+export async function markedScopeSources(db: Db, ids: readonly string[], lock?: 'share' | 'update'): Promise<Set<string>> {
if (!ids.length) return new Set();
const sql = sqlOf(db);
const list = JSON.stringify([...new Set(ids)]);
- const rows = lock
+ const rows = lock === 'update'
? await sql`SELECT id, config FROM sources WHERE id IN (SELECT jsonb_array_elements_text(${list}::text::jsonb)) ORDER BY id FOR UPDATE`
- : await sql`SELECT id, config FROM sources WHERE id IN (SELECT jsonb_array_elements_text(${list}::text::jsonb))`;
+ : lock === 'share'
+ ? await sql`SELECT id, config FROM sources WHERE id IN (SELECT jsonb_array_elements_text(${list}::text::jsonb)) ORDER BY id FOR SHARE`
+ : await sql`SELECT id, config FROM sources WHERE id IN (SELECT jsonb_array_elements_text(${list}::text::jsonb))`;
return new Set(rows.filter(r => isScopeSourceConfig(r.config)).map(r => String(r.id)));
}
@@ -119,7 +123,7 @@ export async function assertScopeSourceGrant(db: Db, self: CredentialRef | null,
}
const candidates = reads.filter(s => s !== 'default');
if (!candidates.length) return;
- const marked = await markedScopeSources(sql, candidates, true);
+ const marked = await markedScopeSources(sql, candidates, 'share');
if (!marked.size) return;
const own = self ? (await credentialSources(sql)).find(c => same(c.ref, self))?.attest ?? [] : [];
const reserved = [...marked].filter(s => !own.includes(s)).sort();
@@ -140,10 +144,12 @@ function attestInvalid(message: string, suggestion: string): OperationError {
*/
export async function applyAttestSources(db: Db, self: CredentialRef, next: readonly string[] | null, before: readonly string[] | null, opts: { dryRun?: boolean } = {}): Promise<boolean> {
const sql = sqlOf(db);
- const marked = await markedScopeSources(sql, next ?? [], true);
+ const marked = await markedScopeSources(sql, next ?? []);
const added = (next ?? []).filter(s => !(before ?? []).includes(s) || !marked.has(s));
const dropped = (before ?? []).filter(s => !(next ?? []).includes(s));
if (!added.length && !dropped.length) return false;
+ // The caller holds this credential's row FOR UPDATE; the sources it marks are locked before the other grants are read.
+ await markedScopeSources(sql, added, 'update');
const all = await credentialSources(sql);
const mine = all.find(c => same(c.ref, self));
const stillRead = dropped.filter(s => mine?.reads.includes(s));
diff --git a/src/core/access/members.ts b/src/core/access/members.ts
index 5e076e59e3..9e5ae90356 100644
--- a/src/core/access/members.ts
+++ b/src/core/access/members.ts
@@ -307,47 +307,50 @@ export async function bindCredential(engine: BrainEngine, target: { kind: 'token
if (patch.member != null) await requireEnabledMember(engine, patch.member);
const table = target.kind === 'token' ? 'access_tokens' : 'oauth_clients';
const key = target.kind === 'token' ? 'id::text' : 'client_id';
- const [before] = await engine.executeRaw<{ member_id: string | null; may_act_for: string[] | null; attest_actor: string | null; attest_ops: string[] | null; attest_sources: string[] | null; grant_types?: string[] | null; confidential?: boolean }>(
- `SELECT member_id, may_act_for, attest_actor, attest_ops, attest_sources${target.kind === 'client' ? ', grant_types, client_secret_hash IS NOT NULL AS confidential' : ''} FROM ${table} WHERE ${key} = $1`, [target.id]);
- if (!before) {
- throw opError('invalid_params', `No ${target.kind === 'token' ? 'token' : 'OAuth client'} "${target.id}" exists.`,
- target.kind === 'token' ? 'List tokens with gbrain auth list.' : 'List clients with gbrain auth clients --json.');
- }
- const member = patch.member === undefined ? before.member_id : patch.member;
- const mayActFor = patch.mayActFor === undefined ? before.may_act_for : patch.mayActFor;
- const attestActor = patch.attestActor === undefined ? before.attest_actor : patch.attestActor;
- const attestOps = attestActor === null ? null : patch.attestOps === undefined ? before.attest_ops : patch.attestOps;
- const attestSources = attestActor === null ? null : patch.attestSources === undefined ? before.attest_sources : patch.attestSources?.length ? [...new Set(patch.attestSources)].sort() : null;
- const what = target.kind === 'token' ? 'This token' : `OAuth client ${target.id}`;
- if (patch.attestOps != null && attestActor === null) throw attestRefused('--attest-ops needs the attest right.', 'Pass --attest-actor qm with it.');
- if (patch.attestSources != null && attestActor === null) throw attestRefused('--attest-sources needs the attest right.', 'Pass --attest-actor qm with it.');
- // GST-1113: a credential that writes scope memory runs only the memory operations as a person, never a general read.
- const outside = attestSources ? (attestOps ?? DEFAULT_ATTEST_OPS).filter(op => !SCOPE_ATTEST_OPS.has(op)) : [];
- if (outside.length) throw attestRefused(`${what} lists scope sources (--attest-sources), so its attested operations stay within ${[...SCOPE_ATTEST_OPS].join(', ')}; ${outside.join(', ')} is not.`, 'Drop those operations (--attest-ops), or use a separate credential for them.');
-
- const deferred = (patch.attestOps ?? []).filter(op => ACTOR_DEFERRED_OPS.has(op));
- if (deferred.length) throw attestRefused(`--attest-ops names ${deferred.join(', ')}, which an attested actor cannot run yet.`, `Leave them out. Not attestable yet: ${[...ACTOR_DEFERRED_OPS].join(', ')}.`);
- if (attestActor !== null && (patch.attestActor !== undefined || patch.member !== undefined)) {
- if (member !== null) throw attestRefused(`${what} is bound to member "${member}", so it cannot attest other people.`, 'Use a credential bound to no member (--member none), or a separate client for the trusted system.');
- if (target.kind === 'client' && (!(before.grant_types ?? []).includes('client_credentials') || before.confidential !== true)) {
- throw attestRefused(`${what} is not a confidential client-credentials client, so it cannot attest people.`,
- 'Register one for the trusted system: gbrain auth register-client <name> --grant-types client_credentials, then grant it --attest-actor qm.');
+ // GST-1113: lock the credential row first and read it under the lock (grant rescopes lock it first too), so a
+ // concurrent rescope commits before or after this change, never between its checks and its write.
+ return engine.transaction(async tx => {
+ const [before] = await tx.executeRaw<{ member_id: string | null; may_act_for: string[] | null; attest_actor: string | null; attest_ops: string[] | null; attest_sources: string[] | null; grant_types?: string[] | null; confidential?: boolean }>(
+ `SELECT member_id, may_act_for, attest_actor, attest_ops, attest_sources${target.kind === 'client' ? ', grant_types, client_secret_hash IS NOT NULL AS confidential' : ''} FROM ${table} WHERE ${key} = $1 FOR UPDATE`, [target.id]);
+ if (!before) {
+ throw opError('invalid_params', `No ${target.kind === 'token' ? 'token' : 'OAuth client'} "${target.id}" exists.`,
+ target.kind === 'token' ? 'List tokens with gbrain auth list.' : 'List clients with gbrain auth clients --json.');
}
- }
- let changed = member !== before.member_id || JSON.stringify(mayActFor ?? null) !== JSON.stringify(before.may_act_for ?? null)
- || attestActor !== before.attest_actor || JSON.stringify(attestOps ?? null) !== JSON.stringify(before.attest_ops ?? null)
- || JSON.stringify(attestSources ?? null) !== JSON.stringify(before.attest_sources ?? null);
- if (changed || patch.attestSources != null) {
- // GST-1113: the scope-source checks, the marks and the binding commit together, under the scope sources' row locks.
- // A restated list also re-marks a listed source that lost its mark.
- await engine.transaction(async tx => {
+ const member = patch.member === undefined ? before.member_id : patch.member;
+ const mayActFor = patch.mayActFor === undefined ? before.may_act_for : patch.mayActFor;
+ const attestActor = patch.attestActor === undefined ? before.attest_actor : patch.attestActor;
+ const attestOps = attestActor === null ? null : patch.attestOps === undefined ? before.attest_ops : patch.attestOps;
+ const attestSources = attestActor === null ? null : patch.attestSources === undefined ? before.attest_sources : patch.attestSources?.length ? [...new Set(patch.attestSources)].sort() : null;
+ const what = target.kind === 'token' ? 'This token' : `OAuth client ${target.id}`;
+ if (patch.attestOps != null && attestActor === null) throw attestRefused('--attest-ops needs the attest right.', 'Pass --attest-actor qm with it.');
+ if (patch.attestSources != null && attestActor === null) throw attestRefused('--attest-sources needs the attest right.', 'Pass --attest-actor qm with it.');
+ // GST-1113: a credential that writes scope memory runs only the memory operations as a person, never a general read.
+ const outside = attestSources ? (attestOps ?? DEFAULT_ATTEST_OPS).filter(op => !SCOPE_ATTEST_OPS.has(op)) : [];
+ if (outside.length) throw attestRefused(`${what} lists scope sources (--attest-sources), so its attested operations stay within ${[...SCOPE_ATTEST_OPS].join(', ')}; ${outside.join(', ')} is not.`, 'Drop those operations (--attest-ops), or use a separate credential for them.');
+
+ const deferred = (patch.attestOps ?? []).filter(op => ACTOR_DEFERRED_OPS.has(op));
+ if (deferred.length) throw attestRefused(`--attest-ops names ${deferred.join(', ')}, which an attested actor cannot run yet.`, `Leave them out. Not attestable yet: ${[...ACTOR_DEFERRED_OPS].join(', ')}.`);
+ if (attestActor !== null && (patch.attestActor !== undefined || patch.member !== undefined)) {
+ if (member !== null) throw attestRefused(`${what} is bound to member "${member}", so it cannot attest other people.`, 'Use a credential bound to no member (--member none), or a separate client for the trusted system.');
+ if (target.kind === 'client' && (!(before.grant_types ?? []).includes('client_credentials') || before.confidential !== true)) {
+ throw attestRefused(`${what} is not a confidential client-credentials client, so it cannot attest people.`,
+ 'Register one for the trusted system: gbrain auth register-client <name> --grant-types client_credentials, then grant it --attest-actor qm.');
+ }
+ }
+ let changed = member !== before.member_id || JSON.stringify(mayActFor ?? null) !== JSON.stringify(before.may_act_for ?? null)
+ || attestActor !== before.attest_actor || JSON.stringify(attestOps ?? null) !== JSON.stringify(before.attest_ops ?? null)
+ || JSON.stringify(attestSources ?? null) !== JSON.stringify(before.attest_sources ?? null);
+ if (changed || patch.attestSources != null) {
+ // GST-1113: the scope-source checks, the marks and the binding commit together, under this row's lock and then the
+ // marked sources' row locks. A restated list also re-marks a listed source that lost its mark.
if (await applyAttestSources(tx, target, attestSources ?? null, before.attest_sources ?? null, opts)) changed = true;
- if (opts.dryRun) return;
- await tx.executeRaw(`UPDATE ${table} SET member_id = $2, may_act_for = $3::text[], attest_actor = $4, attest_ops = $5::text[], attest_sources = $6::text[] WHERE ${key} = $1`,
- [target.id, member, mayActFor, attestActor, attestOps, attestSources]);
- });
- }
- return { member, may_act_for: mayActFor ?? null, ...(attestActor ? { attest_actor: attestActor, attest_ops: attestOps ?? null, attest_sources: attestSources ?? null } : {}), changed };
+ if (!opts.dryRun) {
+ await tx.executeRaw(`UPDATE ${table} SET member_id = $2, may_act_for = $3::text[], attest_actor = $4, attest_ops = $5::text[], attest_sources = $6::text[] WHERE ${key} = $1`,
+ [target.id, member, mayActFor, attestActor, attestOps, attestSources]);
+ }
+ }
+ return { member, may_act_for: mayActFor ?? null, ...(attestActor ? { attest_actor: attestActor, attest_ops: attestOps ?? null, attest_sources: attestSources ?? null } : {}), changed };
+ });
}
/** A credential bound to a member that cannot read: verification refuses it. */
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index e6bfb123f8..4f3cba05e1 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -6084,6 +6084,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
},
"max_chars": {
"type": "integer",
+ "minimum": 200,
"description": "Cap on fact (then results) text, 200-12000; whole items only, truncated says if cut.",
"fullSurfaceOnly": true
}
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 37bcc732ee..4a6a2663a4 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -318,7 +318,7 @@ const recall: Operation = {
return_unit: { type: 'string', enum: ['chunk', 'window', 'section', 'page', 'auto'], description: 'results[] unit (see search).', fullSurfaceOnly: true },
return_window: { type: 'number', description: 'Window 1-3.', fullSurfaceOnly: true },
min_trust: MIN_TRUST_PARAM,
- max_chars: { type: 'integer', description: `Cap on fact (then results) text, ${MEMORY_RECALL_MAX_CHARS.min}-${MEMORY_RECALL_MAX_CHARS.max}; whole items only, truncated says if cut.`, fullSurfaceOnly: true },
+ max_chars: { type: 'integer', minimum: MEMORY_RECALL_MAX_CHARS.min, description: `Cap on fact (then results) text, ${MEMORY_RECALL_MAX_CHARS.min}-${MEMORY_RECALL_MAX_CHARS.max}; whole items only, truncated says if cut.`, fullSurfaceOnly: true },
},
scope: 'read',
verb: true,
diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.ts
index 59c173ad1c..705784adc8 100644
--- a/src/core/persistence/authority.ts
+++ b/src/core/persistence/authority.ts
@@ -161,12 +161,13 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, opera
await storedActorIdentity(engine, a.principal, actor, a.attestedOp ?? operation, storedPerCallWriteSource(a, slug) ?? undefined);
}
// GST-1113: the one exception to the owner's single write source (the scope page), re-checked against the live attest_sources above.
- const ownSource = (source: unknown) => source === a.sourceId || storedPerCallWriteSource(a, slug) !== null;
+ // A live grant of no sources writes nothing, so it refuses before that exception.
+ const ownSource = (source: unknown, sourcesNone: boolean) => !sourcesNone && (source === a.sourceId || storedPerCallWriteSource(a, slug) !== null);
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,
+ const [row] = await engine.executeRaw<Record<string, unknown>>(`SELECT deleted_at,scope,source_id,source_grant,allowed_operations,
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 || !ownSource(row.source_id)) deny('The owning OAuth client is revoked or its source changed.');
+ if (!row || row.deleted_at != null || !ownSource(row.source_id, row.source_grant === 'none')) 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);
if (skillWrite(operation) && (!strings(row.allowed_operations) || !row.allowed_operations.includes(operation))) deny('The current skill operation grant was removed.');
@@ -186,7 +187,7 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, opera
assertSkillWriteScopes(normalizeTokenScopes(row.scopes) ?? [], operation, a.remote);
const liveOperations = grant.allowedOperations;
if (!operationAllowed(liveOperations, granted) || skillWrite(operation) && !liveOperations?.includes(operation)) deny('The current legacy operation grant excludes this write.');
- if (!hasScope(grant.scopes, 'write') || !ownSource(authSourcesFromGrant(grant).sourceId)) deny('The current token no longer permits this source write.');
+ if (!hasScope(grant.scopes, 'write') || !ownSource(authSourcesFromGrant(grant).sourceId, grant.sources.kind === 'none')) deny('The current token no longer permits this source write.');
return;
}
if (a.principal.kind === 'local_cli' || a.principal.kind === 'local_stdio') {
diff --git a/test/qm-memory-tools.test.ts b/test/qm-memory-tools.test.ts
index 265366625d..281b976e5f 100644
--- a/test/qm-memory-tools.test.ts
+++ b/test/qm-memory-tools.test.ts
@@ -34,6 +34,7 @@ import { attestRightOf, linkedMember, linkMember } from '../src/core/access/acto
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { boundFactLines, isoDate, memoryWriteRequestId, plainFactText, MEMORY_RECALL_MAX_CHARS } from '../src/core/ops/qm-memory.ts';
import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { operations } from '../src/core/operations.ts';
import { startHttpTransport } from '../src/mcp/http-transport.ts';
import { RateLimiter } from '../src/mcp/rate-limit.ts';
import { BEHAVIOR_CHANGES } from '../src/core/behavior-change-notice.ts';
@@ -493,6 +494,8 @@ for (const kind of testBackends()) {
expect(out.json.code ?? out.json.error).toBe('invalid_params');
expect(out.text).not.toContain('canaryharnrecall');
}
+ // A client that fills optional integers from the schema sends at least the minimum, never 0.
+ expect(operations.find(o => o.name === 'recall')!.params.max_chars).toMatchObject({ type: 'integer', minimum: MEMORY_RECALL_MAX_CHARS.min });
}, 120_000);
test('an unlinked person gets an empty success whose code rides structuredContent only', async () => {
diff --git a/test/qm-scope-writes.test.ts b/test/qm-scope-writes.test.ts
index 1a14b2a5b7..9f39caebce 100644
--- a/test/qm-scope-writes.test.ts
+++ b/test/qm-scope-writes.test.ts
@@ -39,6 +39,7 @@ import { restoreSource, softDeleteSource } from '../src/core/destructive-guard.t
import { proposeRevision } from '../src/core/access/policy.ts';
import { quarantineRestoredExecution } from '../src/core/backup/quarantine.ts';
import { registerScopedClient } from '../src/commands/auth.ts';
+import { runSources } from '../src/commands/sources.ts';
import type { AuthInfo } from '../src/core/ops/contract.ts';
import { attestRightFrom } from '../src/core/access/actor-model.ts';
import { testBackends } from './helpers/test-backends.ts';
@@ -368,6 +369,114 @@ for (const kind of testBackends()) {
expect((await refusal(bindCredential(engine, { kind: 'client', id: clients.plain!.id }, { attestSources: [SCOPE_A] })))?.message).toContain('attest right');
expect((await markedScopeSources(engine, [SHARED, HOME])).size).toBe(0);
}, 60_000);
+
+ const storedAuthority = async (requestId: string) => {
+ const [row] = await engine.executeRaw<{ authority: any }>('SELECT authority FROM persistence_requests WHERE request_id = $1::uuid', [requestId]);
+ return typeof row!.authority === 'string' ? JSON.parse(row!.authority) : row!.authority;
+ };
+ const scopeClient = async (name: string, attest: string[], reads: string[]) => {
+ for (const id of attest) await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [id]);
+ const c = await register(name, HOME);
+ await bindCredential(engine, { kind: 'client', id: c.id }, { attestActor: 'qm', attestOps: MEMORY_OPS, attestSources: attest });
+ await rescopeClientGrant(engine, c.id, { federatedRead: reads }, { actor: 'test' });
+ tokens[name] = (await provider().exchangeClientCredentials(c.id, c.secret)).access_token;
+ return c;
+ };
+ const raceWhile = (matches: (sql: string, params: unknown[]) => boolean, racer: () => Promise<unknown>) => {
+ const original = engine.executeRaw;
+ let race: Promise<Error | null> | null = null;
+ engine.executeRaw = (async function (this: BrainEngine, ...args: Parameters<typeof engine.executeRaw>) {
+ if (!race && matches(String(args[0]), (args[1] ?? []) as unknown[])) {
+ let settled = false;
+ race = refusal(racer()).finally(() => { settled = true; });
+ for (let i = 0; i < 30 && !settled; i++) await new Promise(r => setTimeout(r, 50));
+ }
+ return original.apply(this, args);
+ }) as typeof engine.executeRaw;
+ return { restore: () => { engine.executeRaw = original; }, result: () => race };
+ };
+
+ test('a stored scope write is refused once its OAuth client or legacy token is rescoped to no sources', async () => {
+ const NONE_SCOPE = 'qm-scope-none';
+ const c = await scopeClient('nonescope', [NONE_SCOPE], [HOME, NONE_SCOPE]);
+ const out = await write({ token: 'nonescope', actor: ALICE_ID }, [{ fact: 'No sources canarynonesources', provenance: 'turn n' }], { source_id: NONE_SCOPE });
+ expect(out.structured!.status).toBe('committed');
+ const authority = await storedAuthority(out.structured!.request_id);
+ await authorizeWrite(engine as never, authority, 'remember', 'memory/scope');
+ await rescopeClientGrant(engine, c.id, { sourcesNone: true, sourceId: null, federatedRead: [] }, { actor: 'test' });
+ expect((await refusal(authorizeWrite(engine as never, authority, 'remember', 'memory/scope')))?.message).toContain('revoked or its source changed');
+
+ const TOKEN_SCOPE = 'qm-scope-none-token';
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [TOKEN_SCOPE]);
+ const minted = await mintLegacyToken(engine, { name: 'none-tok-' + randomUUID().slice(0, 8), scopes: ['read', 'write'], takesHolders: ['world'], sourceGrant: [HOME, TOKEN_SCOPE] });
+ await bindCredential(engine, { kind: 'token', id: minted.id }, { attestActor: 'qm', attestOps: MEMORY_OPS, attestSources: [TOKEN_SCOPE] });
+ tokens.nonetoken = minted.token;
+ const viaToken = await write({ token: 'nonetoken', actor: ALICE_ID }, [{ fact: 'No sources token canarynonetoken', provenance: 'turn t' }], { source_id: TOKEN_SCOPE });
+ expect(viaToken.structured!.status).toBe('committed');
+ const tokenAuthority = await storedAuthority(viaToken.structured!.request_id);
+ await authorizeWrite(engine as never, tokenAuthority, 'remember', 'memory/scope');
+ await rescopeLegacyToken(engine, { ...tokenArgs, reset: [], target: { id: minted.id }, sources: [] });
+ expect((await refusal(authorizeWrite(engine as never, tokenAuthority, 'remember', 'memory/scope')))?.message).toContain('no longer permits this source write');
+ }, 60_000);
+
+ test('sources federate racing an --attest-sources mark never leaves a federated or unmarked scope source', async () => {
+ const FED = 'qm-scope-fed-race';
+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [FED]);
+ const racer = await register('fedracer', HOME);
+ await bindCredential(engine, { kind: 'client', id: racer.id }, { attestActor: 'qm', attestOps: MEMORY_OPS });
+ const race = raceWhile((sql, params) => sql.includes('UPDATE sources SET config = $1::text::jsonb WHERE id = $2') && params[1] === FED,
+ () => bindCredential(engine, { kind: 'client', id: racer.id }, { attestSources: [FED] }));
+ try {
+ await runSources(engine, ['federate', FED]);
+ } finally {
+ race.restore();
+ }
+ expect(race.result()).not.toBeNull();
+ const bound = await race.result();
+ const [row] = await engine.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id = $1', [FED]);
+ const config = parseSourceConfig(row!.config);
+ if (bound === null) expect(config).toMatchObject({ qm_scope: true, federated: false });
+ else expect({ marked: config.qm_scope === true, federated: config.federated }).toEqual({ marked: false, federated: true });
+ }, 60_000);
+
+ test('a read grant widened while --attest-sources drops that source never leaves the credential reading an unlisted scope', async () => {
+ const [D1, D2] = ['qm-scope-drop-1', 'qm-scope-drop-2'];
+ const c = await scopeClient('droprace', [D1, D2], [HOME, D1]);
+ const race = raceWhile(sql => sql.includes('UPDATE oauth_clients SET member_id'),
+ () => rescopeClientGrant(engine, c.id, { federatedRead: [HOME, D1, D2] }, { actor: 'test' }));
+ let dropped: Error | null;
+ try {
+ dropped = await refusal(bindCredential(engine, { kind: 'client', id: c.id }, { attestSources: [D1] }));
+ } finally {
+ race.restore();
+ }
+ expect(race.result()).not.toBeNull();
+ const widened = await race.result();
+ expect(dropped === null && widened === null).toBe(false);
+ const [row] = await engine.executeRaw<{ federated_read: string[] | null; attest_sources: string[] | null }>('SELECT federated_read, attest_sources FROM oauth_clients WHERE client_id = $1', [c.id]);
+ const unlisted = (row!.federated_read ?? []).filter(s => [D1, D2].includes(s) && !(row!.attest_sources ?? []).includes(s));
+ expect(unlisted).toEqual([]);
+ }, 60_000);
+
+ test('a read grant widened onto a scope source while a publication holds that source does not deadlock', async () => {
+ const LOCKED = 'qm-scope-share';
+ const c = await scopeClient('sharelock', [LOCKED], [HOME]);
+ const out = await write({ token: 'sharelock', actor: ALICE_ID }, [{ fact: 'Share lock canarysharelock', provenance: 'turn s' }], { source_id: LOCKED });
+ expect(out.structured!.status).toBe('committed');
+ const authority = await storedAuthority(out.structured!.request_id);
+ const ROLLBACK = new Error('rollback');
+ let grant: Promise<Error | null> | null = null;
+ let published: Error | null = new Error('not run');
+ await engine.transaction(async tx => {
+ await tx.executeRaw('SELECT 1 FROM sources WHERE id = $1 FOR SHARE', [LOCKED]);
+ grant = refusal(rescopeClientGrant(engine, c.id, { federatedRead: [HOME, LOCKED] }, { actor: 'test' }));
+ await new Promise(r => setTimeout(r, 300));
+ published = await refusal(authorizeWrite(tx as never, authority, 'remember', 'memory/scope', true));
+ throw ROLLBACK;
+ }).catch(e => { if (e !== ROLLBACK) throw e; });
+ expect(published).toBeNull();
+ expect(await grant).toBeNull();
+ }, 60_000);
});
}
diff --git a/test/sources.test.ts b/test/sources.test.ts
index eaff313ea1..3fd7bd900c 100644
--- a/test/sources.test.ts
+++ b/test/sources.test.ts
@@ -47,6 +47,7 @@ function makeStub(rowsByPattern: Record<string, unknown[]> = {}): {
kind: 'pglite' as const,
executeRaw,
setConfig,
+ transaction: async (fn: (tx: BrainEngine) => Promise<unknown>) => fn(engine),
// Unused methods throw if called accidentally during these tests.
getConfig: async () => null,
} as unknown as BrainEngine;