Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(loops): enforce the bound write source and hide foreign loop existence (#5697)

garrytan195de5b320ff
diff --git a/src/commands/loops.ts b/src/commands/loops.ts
index f2d99a92d3..e2761467b0 100644
--- a/src/commands/loops.ts
+++ b/src/commands/loops.ts
@@ -146,8 +146,8 @@ export async function runLoops(engine: BrainEngine, args: string[]): Promise<voi
'gbrain loops — inspect and manage open loops',
' list [--status open|done|dropped|stale] [--type <loop_type>] [--source <id>] [--json]',
' show <id> [--json]',
- ' done <id> mark handled',
- ' drop <id> not going to do it',
+ ' done <id> [--note <text>] mark handled',
+ ' drop <id> [--note <text>] not going to do it',
' mute sender <email> | thread <thread-id> [--source <id>]',
' unmute sender <email> | thread <thread-id> [--source <id>] undo a mute',
'',
@@ -212,10 +212,16 @@ export async function runLoops(engine: BrainEngine, args: string[]): Promise<voi
console.error(`Usage: gbrain loops ${sub} <id>`);
process.exit(2);
}
+ const noteIdx = rest.indexOf('--note');
+ const note = noteIdx !== -1 ? rest[noteIdx + 1] : undefined;
const result = (await handleToolCall(
engine,
'loops_close',
- { id, status: sub === 'done' ? 'done' : 'dropped' },
+ {
+ id,
+ status: sub === 'done' ? 'done' : 'dropped',
+ ...(note !== undefined ? { note } : {}),
+ },
{ sourceId: ALL_SOURCES },
)) as { closed: boolean; reason?: string; status?: string };
if (json) {
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 6b9da0a73d..1a7b4cdce1 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -72,7 +72,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'integrity': ['--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url'],
'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--images', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--prune-orphans', '--queue', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--abort', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all'],
- 'loops': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],
+ 'loops': ['--all', '--brain', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
'maintain': ['--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
@@ -123,7 +123,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout'],
'upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
- 'waiting': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],
+ 'waiting': ['--all', '--brain', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--top', '--type'],
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
'whoknows': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--explain', '--federated-read', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--url', '--yes'],
};
diff --git a/src/core/ops/loops.ts b/src/core/ops/loops.ts
index af47558418..1b8d368371 100644
--- a/src/core/ops/loops.ts
+++ b/src/core/ops/loops.ts
@@ -34,6 +34,26 @@ import {
const STALE_AFTER_MS = 24 * 3_600_000;
+/** Does this source carry Google content? A loops suppression row is only
+ * ever consulted by the detector inside a google source — a mute written
+ * anywhere else can never match. */
+async function sourceHasGoogleContent(ctx: OperationContext, sourceId: string): Promise<boolean> {
+ try {
+ const rows = await ctx.engine.executeRaw<{ config: unknown }>(
+ `SELECT config FROM sources WHERE id = $1`,
+ [sourceId],
+ );
+ const c = rows[0]?.config;
+ const cfg =
+ typeof c === 'string'
+ ? (JSON.parse(c) as Record<string, unknown>)
+ : ((c ?? {}) as Record<string, unknown>);
+ return cfg.kind === 'google';
+ } catch {
+ return false;
+ }
+}
+
interface GoogleSourceFreshness {
id: string;
last_sync_at: string | null;
@@ -461,24 +481,49 @@ const loops_close: Operation = {
id: { type: 'number', required: true, description: 'Loop id (from open_loops).' },
status: { type: 'string', required: true, enum: ['done', 'dropped'], description: 'Terminal state.' },
note: { type: 'string', description: 'Optional closed_by note (default: manual).' },
+ source_id: {
+ type: 'string',
+ description:
+ "The loop's home source (e.g. the google source, when the caller's transport is bound " +
+ 'elsewhere). Remote callers must be write-bound to it — a federated read grant does not ' +
+ 'authorize the close. When omitted, the caller\'s bound write source is used.',
+ },
},
mutating: true,
scope: 'write',
handler: async (ctx, p) => {
- const scope = sourceScopeOpts(ctx);
- // Remote callers stay inside their granted source scope; trusted local
+ const requested = p.source_id as string | undefined;
+ if (requested) validateSourceId(requested);
+ // Remote callers stay inside their bound write source; trusted local
// closes across sources (null = unscoped).
let sourceId: string | null = null;
if (ctx.remote !== false) {
- sourceId = scope.sourceId ?? (scope.sourceIds && scope.sourceIds.length === 1 ? scope.sourceIds[0] : null);
- if (!sourceId) {
+ // Write authority is the caller's bound write source
+ // (auth.sourceId, dual-written to ctx.sourceId) ONLY — the federated
+ // allowedSources array is a READ grant and must never authorize a
+ // close+fact-expiry write in a sibling source (contract.ts).
+ const writeSource = (ctx.auth?.sourceId ?? ctx.sourceId) as string | undefined;
+ if (!writeSource) {
// Enumerated error envelope (dispatch classifies + request-logs it),
// never a success-shaped { closed:false } payload.
throw new OperationError(
'permission_denied',
- 'loops_close: remote callers need a single-source scope',
+ 'loops_close: remote callers need a bound write source',
+ );
+ }
+ if (requested && requested !== writeSource) {
+ throw new OperationError(
+ 'permission_denied',
+ `loops_close: source "${requested}" is outside the caller's write scope`,
);
}
+ // No cross-source SELECT: the close runs scoped to the write source,
+ // so a loop living in a grant-adjacent source is indistinguishable
+ // from a missing id — both answer closed:false, and neither the row's
+ // existence nor its home source name ever leaves the boundary.
+ sourceId = writeSource;
+ } else {
+ sourceId = requested ?? null;
}
if (ctx.dryRun) return { dry_run: true, action: 'loops_close', id: p.id, status: p.status };
const row = await closeOpenLoop(
@@ -519,23 +564,30 @@ const loops_mute: Operation = {
handler: async (ctx, p) => {
const sourceId = (p.source_id as string | undefined) ?? ctx.sourceId ?? 'default';
validateSourceId(sourceId);
- // Remote callers stay strictly inside their grant (mirrors loops_close):
- // a scalar-scoped caller may only mute within its own source; federated
- // grants must include the target. Trusting p.source_id for a remote
- // WRITE would let any remote client plant suppression rows into
+ // Remote callers stay strictly inside their bound write source (mirrors
+ // loops_close): the federated allowedSources array is a READ grant and
+ // never authorizes the write. Trusting it (or p.source_id alone) for a
+ // remote WRITE would let any remote client plant suppression rows into
// arbitrary sources (targeted denial-of-loop-detection).
if (ctx.remote !== false) {
- const scope = sourceScopeOpts(ctx);
- const granted =
- (scope.sourceId && scope.sourceId === sourceId) ||
- (scope.sourceIds?.includes(sourceId) ?? false);
- if (!granted) {
+ const writeSource = (ctx.auth?.sourceId ?? ctx.sourceId) as string | undefined;
+ if (!writeSource || sourceId !== writeSource) {
throw new OperationError(
'permission_denied',
- `loops_mute: source "${sourceId}" is outside the caller's scope`,
+ `loops_mute: source "${sourceId}" is outside the caller's write scope`,
);
}
}
+ // A suppression is only consulted inside a google source — when the
+ // caller omits source_id and the resolved target holds no Google
+ // content, the row can never match. Refuse instead of planting a dead
+ // mute (remote callers bound to a non-google source hit exactly this).
+ if (p.source_id === undefined && !(await sourceHasGoogleContent(ctx, sourceId))) {
+ throw new OperationError(
+ 'invalid_params',
+ `loops_mute: source "${sourceId}" holds no Google content — a suppression there can never match; pass source_id naming the google source`,
+ );
+ }
if (ctx.dryRun) return { dry_run: true, action: 'loops_mute', kind: p.kind, value: p.value };
await addSuppression(ctx.engine, sourceId, p.kind as 'sender' | 'thread', p.value as string);
return { muted: true, kind: p.kind, value: (p.value as string).toLowerCase(), source_id: sourceId };
@@ -558,21 +610,28 @@ const loops_unmute: Operation = {
handler: async (ctx, p) => {
const sourceId = (p.source_id as string | undefined) ?? ctx.sourceId ?? 'default';
validateSourceId(sourceId);
- // Same grant check as loops_mute — an unmute is equally a targeted write:
- // letting a remote caller lift another source's suppression would re-open
- // the very noise channel its owner silenced.
+ // Same write-source check as loops_mute — an unmute is equally a targeted
+ // write, and a federated read grant does not confer it: letting a remote
+ // caller lift another source's suppression would re-open the very noise
+ // channel its owner silenced.
if (ctx.remote !== false) {
- const scope = sourceScopeOpts(ctx);
- const granted =
- (scope.sourceId && scope.sourceId === sourceId) ||
- (scope.sourceIds?.includes(sourceId) ?? false);
- if (!granted) {
+ const writeSource = (ctx.auth?.sourceId ?? ctx.sourceId) as string | undefined;
+ if (!writeSource || sourceId !== writeSource) {
throw new OperationError(
'permission_denied',
- `loops_unmute: source "${sourceId}" is outside the caller's scope`,
+ `loops_unmute: source "${sourceId}" is outside the caller's write scope`,
);
}
}
+ // Mirrors loops_mute: an omitted source_id resolving to a source with no
+ // Google content can never hold a live suppression — refuse rather than
+ // answer removed:false on a row that should never have existed.
+ if (p.source_id === undefined && !(await sourceHasGoogleContent(ctx, sourceId))) {
+ throw new OperationError(
+ 'invalid_params',
+ `loops_unmute: source "${sourceId}" holds no Google content — pass source_id naming the google source`,
+ );
+ }
if (ctx.dryRun) return { dry_run: true, action: 'loops_unmute', kind: p.kind, value: p.value };
const removed = await removeSuppression(
ctx.engine,
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 76a2907a26..4101d592b2 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 202985,
- "stdoutSha256": "bd0de8ec965e91bfc419afeccf1983ff9bc1d2590e38ec76d3b751dd53e3fe47",
+ "stdoutBytes": 203354,
+ "stdoutSha256": "c8950fdaf4565dfc46c9f17fd7707b39c7bdbdd3776d416b50f25f4d61ca79f8",
"toolNames": [
"remember",
"entity",
@@ -5186,6 +5186,7 @@
"parameters": {
"id": "number",
"note": "string?",
+ "source_id": "string?",
"status": "string"
},
"schema": {
@@ -5198,6 +5199,10 @@
"description": "Optional closed_by note (default: manual).",
"type": "string"
},
+ "source_id": {
+ "description": "The loop's home source (e.g. the google source, when the caller's transport is bound elsewhere). Remote callers must be write-bound to it — a federated read grant does not authorize the close. When omitted, the caller's bound write source is used.",
+ "type": "string"
+ },
"status": {
"description": "Terminal state.",
"enum": [
diff --git a/test/loops-cli.test.ts b/test/loops-cli.test.ts
index 5c6fe3d607..58b4824479 100644
--- a/test/loops-cli.test.ts
+++ b/test/loops-cli.test.ts
@@ -342,6 +342,16 @@ describe('runLoops', () => {
expect(rows[0].status).toBe('dropped');
});
+ test('--note records a closed_by note instead of "manual" (#5446)', async () => {
+ await upsertOpenLoop(engine, loop());
+ const r = await captured(() => runLoops(engine, ['done', '1', '--note', 'handled in person']));
+ expect(r.out).toContain('Loop 1 done.');
+ const rows = await engine.executeRaw<{ closed_by: string }>(
+ `SELECT closed_by FROM open_loops WHERE id = 1`,
+ );
+ expect(rows[0].closed_by).toBe('handled in person');
+ });
+
test('done without a numeric id hard-exits with usage code 2', async () => {
const r = await captured(() => runLoops(engine, ['done']));
expect(r.exitCalled).toBe(2);
diff --git a/test/ops-loops.test.ts b/test/ops-loops.test.ts
index 2d57b6dd09..3f441f3055 100644
--- a/test/ops-loops.test.ts
+++ b/test/ops-loops.test.ts
@@ -645,7 +645,80 @@ describe('loops_close', () => {
expect(expired[0].expired_at).not.toBeNull();
});
- test('remote ctx without a single-source scope → throws permission_denied, loop untouched', async () => {
+ test('remote write-bound caller closes a loop in its write source even under a multi-source read grant (#5446)', async () => {
+ const { id } = await upsertOpenLoop(engine, loop()); // lives in g1 = ctx.sourceId
+ const res = (await loopsCloseOp.handler(
+ ctx({
+ remote: true,
+ auth: {
+ token: 't',
+ clientId: 'c',
+ scopes: ['write'],
+ allowedSources: ['g1', 'g2'], // read federation — write stays g1
+ },
+ }),
+ { id, status: 'done' },
+ )) as { closed: boolean; status: string };
+ expect(res.closed).toBe(true);
+ expect(res.status).toBe('done');
+ });
+
+ test('remote caller cannot close a loop in a read-granted sibling source — identical answer to a missing id (#5446)', async () => {
+ // Write source g1, read grant covers g1+g2, loop lives in g2: the
+ // federated READ grant must never authorize the close+fact-expiry write.
+ // The op does NOT cross-source SELECT — the close runs scoped to the
+ // write source, so a foreign-source loop is indistinguishable from a
+ // missing id and neither its existence nor its source name leaks.
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, config) VALUES ('g2', 'g2', '{}'::jsonb) ON CONFLICT (id) DO NOTHING`,
+ );
+ const { id } = await upsertOpenLoop(engine, loop({ sourceId: 'g2' }));
+ const boundCtx = ctx({
+ remote: true,
+ auth: {
+ token: 't',
+ clientId: 'c',
+ scopes: ['write'],
+ allowedSources: ['g1', 'g2'], // read covers g2 — write does not
+ },
+ });
+ const foreign = (await loopsCloseOp.handler(boundCtx, { id, status: 'done' })) as {
+ closed: boolean; reason?: string;
+ };
+ const missing = (await loopsCloseOp.handler(boundCtx, { id: 999999, status: 'done' })) as {
+ closed: boolean; reason?: string;
+ };
+ expect(foreign).toEqual(missing); // identical envelope — no existence/source disclosure
+ expect(foreign.closed).toBe(false);
+ expect(JSON.stringify(foreign)).not.toContain('g2');
+ const rows = await listOpenLoops(engine, { sourceIds: ['g2'], status: 'open' });
+ expect(rows).toHaveLength(1); // untouched
+ });
+
+ test('remote source_id param: equal to the write source → closes; anything else → permission_denied (#5446)', async () => {
+ const { id } = await upsertOpenLoop(engine, loop());
+ const boundCtx = ctx({
+ remote: true,
+ auth: { token: 't', clientId: 'c', scopes: ['write'], allowedSources: ['g1', 'g2'] },
+ });
+ const res = (await loopsCloseOp.handler(boundCtx, {
+ id,
+ status: 'done',
+ source_id: 'g1',
+ })) as { closed: boolean };
+ expect(res.closed).toBe(true);
+
+ const { id: id2 } = await upsertOpenLoop(
+ engine,
+ loop({ threadId: '18c2f4a9b3d21e99', dedupKey: 'thread:18c2f4a9b3d21e99:unanswered_inbound' }),
+ );
+ // 'g2' is inside the READ grant — still not the write source.
+ await expect(
+ loopsCloseOp.handler(boundCtx, { id: id2, status: 'done', source_id: 'g2' }),
+ ).rejects.toThrow(/permission_denied|outside the caller's write scope/);
+ });
+
+ test('remote ctx without any scope still throws permission_denied, loop untouched', async () => {
const { id } = await upsertOpenLoop(engine, loop());
// Denials are thrown OperationErrors (enumerated error envelope via
// dispatch), never success-shaped { closed: false } payloads.
@@ -653,16 +726,11 @@ describe('loops_close', () => {
loopsCloseOp.handler(
ctx({
remote: true,
- auth: {
- token: 't',
- clientId: 'c',
- scopes: ['write'],
- allowedSources: ['g1', 'g2'], // multi-source grant → no single scope
- },
+ sourceId: undefined,
}),
{ id, status: 'done' },
),
- ).rejects.toThrow(/permission_denied|single-source scope/);
+ ).rejects.toThrow(/permission_denied|bound write source/);
const rows = await listOpenLoops(engine, { sourceIds: ['g1'], status: 'open' });
expect(rows).toHaveLength(1);
});
@@ -720,18 +788,23 @@ describe('loops_mute', () => {
expect(set.senders.size).toBe(0);
});
- test('remote caller cannot mute outside its granted scope (throws)', async () => {
+ test('federated read grant does not confer write authority: write source mutes, read-only source refuses (#5446)', async () => {
+ // Write-bound to g1, read-federated over other-src: the other-source
+ // mute is a write the read grant cannot authorize, even though the
+ // caller can read that source.
+ const boundCtx = ctx({
+ remote: true,
+ auth: { token: 't', clientId: 'c', scopes: ['write'], allowedSources: ['other-src'] },
+ });
await expect(
- loopsMuteOp.handler(
- ctx({
- remote: true,
- auth: { token: 't', clientId: 'c', scopes: ['write'], allowedSources: ['other-src'] },
- }),
- { kind: 'sender', value: '[email protected]' },
- ),
- ).rejects.toThrow(/permission_denied|outside the caller's scope/);
- const set = await loadSuppressions(engine, 'g1');
- expect(set.senders.size).toBe(0);
+ loopsMuteOp.handler(boundCtx, { kind: 'sender', value: '[email protected]', source_id: 'other-src' }),
+ ).rejects.toThrow(/permission_denied|outside the caller's write scope/);
+ const own = (await loopsMuteOp.handler(boundCtx, {
+ kind: 'sender',
+ value: '[email protected]',
+ })) as { muted: boolean };
+ expect(own.muted).toBe(true);
+ expect((await loadSuppressions(engine, 'g1')).senders.has('[email protected]')).toBe(true);
});
test('REGRESSION: scalar-scoped remote caller cannot mute a DIFFERENT source via p.source_id', async () => {
@@ -744,7 +817,7 @@ describe('loops_mute', () => {
ctx({ remote: true, sourceId: 'g1' }),
{ kind: 'sender', value: '[email protected]', source_id: 'g2' },
),
- ).rejects.toThrow(/permission_denied|outside the caller's scope/);
+ ).rejects.toThrow(/permission_denied|outside the caller's write scope/);
const set = await loadSuppressions(engine, 'g2');
expect(set.senders.size).toBe(0);
// Within its own scalar scope, the mute still works.
@@ -754,6 +827,36 @@ describe('loops_mute', () => {
)) as { muted: boolean };
expect(ok.muted).toBe(true);
});
+
+ test('omitted source_id on a non-google source → invalid_params, no dead suppression (#5446)', async () => {
+ // The reporter's 4 dead mutes: a remote caller bound to 'workspace'
+ // (no Google content) planted suppression rows the detector could
+ // never consult.
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, config) VALUES ('workspace', 'workspace', '{"kind":"files"}'::jsonb)
+ ON CONFLICT (id) DO NOTHING`,
+ );
+ await expect(
+ loopsMuteOp.handler(
+ ctx({ remote: true, sourceId: 'workspace' }),
+ { kind: 'sender', value: '[email protected]' },
+ ),
+ ).rejects.toThrow(/no Google content|invalid_params/);
+ expect((await loadSuppressions(engine, 'workspace')).senders.size).toBe(0);
+ });
+
+ test('explicit source_id naming a non-google source is honored (deliberate scope)', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, config) VALUES ('workspace', 'workspace', '{"kind":"files"}'::jsonb)
+ ON CONFLICT (id) DO NOTHING`,
+ );
+ const res = (await loopsMuteOp.handler(
+ ctx({ remote: true, sourceId: 'workspace' }),
+ { kind: 'sender', value: '[email protected]', source_id: 'workspace' },
+ )) as { muted: boolean };
+ expect(res.muted).toBe(true);
+ expect((await loadSuppressions(engine, 'workspace')).senders.has('[email protected]')).toBe(true);
+ });
});
describe('loops_unmute', () => {
@@ -800,18 +903,23 @@ describe('loops_unmute', () => {
expect(set.threads.has('shared-value')).toBe(true);
});
- test('remote caller cannot unmute outside its granted scope (throws)', async () => {
+ test('federated read grant does not confer write authority on unmute either (#5446)', async () => {
+ // Write-bound to g1, read-federated over other-src: lifting g1's mute is
+ // the caller's own write domain; lifting a read-only source's is not.
await loopsMuteOp.handler(ctx(), { kind: 'sender', value: '[email protected]' });
+ const boundCtx = ctx({
+ remote: true,
+ auth: { token: 't', clientId: 'c', scopes: ['write'], allowedSources: ['other-src'] },
+ });
await expect(
- loopsUnmuteOp.handler(
- ctx({
- remote: true,
- auth: { token: 't', clientId: 'c', scopes: ['write'], allowedSources: ['other-src'] },
- }),
- { kind: 'sender', value: '[email protected]' },
- ),
- ).rejects.toThrow(/permission_denied|outside the caller's scope/);
- expect((await loadSuppressions(engine, 'g1')).senders.has('[email protected]')).toBe(true);
+ loopsUnmuteOp.handler(boundCtx, { kind: 'sender', value: '[email protected]', source_id: 'other-src' }),
+ ).rejects.toThrow(/permission_denied|outside the caller's write scope/);
+ const res = (await loopsUnmuteOp.handler(boundCtx, {
+ kind: 'sender',
+ value: '[email protected]',
+ })) as { removed: boolean };
+ expect(res.removed).toBe(true);
+ expect((await loadSuppressions(engine, 'g1')).senders.has('[email protected]')).toBe(false);
});
test('REGRESSION: scalar-scoped remote caller cannot unmute a DIFFERENT source via p.source_id', async () => {
@@ -829,7 +937,20 @@ describe('loops_unmute', () => {
ctx({ remote: true, sourceId: 'g1' }),
{ kind: 'sender', value: '[email protected]', source_id: 'g2' },
),
- ).rejects.toThrow(/permission_denied|outside the caller's scope/);
+ ).rejects.toThrow(/permission_denied|outside the caller's write scope/);
expect((await loadSuppressions(engine, 'g2')).senders.has('[email protected]')).toBe(true);
});
+
+ test('omitted source_id on a non-google source → invalid_params (#5446)', async () => {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, config) VALUES ('workspace', 'workspace', '{"kind":"files"}'::jsonb)
+ ON CONFLICT (id) DO NOTHING`,
+ );
+ await expect(
+ loopsUnmuteOp.handler(
+ ctx({ remote: true, sourceId: 'workspace' }),
+ { kind: 'sender', value: '[email protected]' },
+ ),
+ ).rejects.toThrow(/no Google content|invalid_params/);
+ });
});