Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

auth: rescope-token for legacy bearer tokens with an explicit no-source grant (#5231 #5893)

garrytan32621e1835b0
diff --git a/scripts/check-operations-filter-bypass.sh b/scripts/check-operations-filter-bypass.sh
index 9ff37b35df..4d2734d2f8 100755
--- a/scripts/check-operations-filter-bypass.sh
+++ b/scripts/check-operations-filter-bypass.sh
@@ -44,6 +44,7 @@ ALLOWED=(
"src/core/grants/profiles.ts" # snapshots eligible remote ops with !op.localOnly; grant validation never exposes local-only operations
"src/core/bootstrap/harness.ts" # trusted owner provisioning; filters localOnly and scopes before minting explicit follow operation snapshots
"src/core/token-mint.ts" # trusted token creation validates explicit snapshots against public scope-compatible operations
+ "src/core/grants/legacy-token.ts" # trusted local rescope-token; validates and refreshes snapshots against !op.localOnly scope-compatible operations
"src/core/shared-skills/tool-access.ts" # skill usability intersects locality, scopes, snapshots, source fences, surface and publication gates
"src/mcp/skill-resources.ts" # resources map only catalog reads through equivalent scope/snapshot/surface/gate checks and shared dispatch
"src/core/harness/capabilities.ts" # introspection applies !op.localOnly plus effective surface, scope, fence, snapshot and publish-gate filters
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 7d376a30e5..707d7aeec6 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -83,6 +83,9 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/mcp/skill-resources.ts": ["test/e2e/shared-skills-transports.test.ts"],
"src/core/scope.ts": ["test/e2e/client-grants.test.ts", "test/e2e/shared-skills-transports.test.ts"],
"src/core/grants/**": ["test/e2e/client-grants.test.ts", "test/e2e/harness-access.test.ts", "test/e2e/delegated-grants-withdrawal.test.ts", "test/e2e/delegated-http-worker.test.ts"],
+ // #5231/#5893 (O-ENG-7): legacy-token rescope and the explicit no-source grant on Postgres.
+ "src/core/grants/legacy-token.ts": ["test/e2e/auth-rescope-token.test.ts"],
+ "src/core/legacy-token-scope.ts": ["test/e2e/auth-rescope-token.test.ts", "test/e2e/auth-permissions.test.ts"],
"src/core/facts/withdrawal*.ts": ["test/e2e/delegated-grants-withdrawal.test.ts", "test/e2e/withdrawal-bounded-safety-postgres.test.ts", "test/e2e/withdrawal-crash-postgres.test.ts", "test/e2e/memory-safety-wave-postgres.test.ts", "test/e2e/fact-withdrawal-scope-postgres.test.ts"],
"src/commands/mcp*.ts": ["test/e2e/harness-access.test.ts"],
// OpenRouter subagent-loop families: the family allowlist + recipe feed the
diff --git a/src/commands/auth.ts b/src/commands/auth.ts
index ecff6b0e64..6477c0b015 100644
--- a/src/commands/auth.ts
+++ b/src/commands/auth.ts
@@ -30,6 +30,7 @@ import { normalizeTokenScopes } from '../core/legacy-token-scope.ts';
import { sqlQueryForEngine, executeRawJsonb, type SqlQuery } from '../core/sql-query.ts';
import { readClientGrant, rescopeClientGrant, resolveGrantProfile, type GrantPatch } from '../core/grants/service.ts';
import { parseRescopeGrantArgs } from '../core/grants/cli.ts';
+import { parseRescopeTokenArgs, renderLegacyGrantAxis, rescopeLegacyToken } from '../core/grants/legacy-token.ts';
function hashToken(token: string): string {
return createHash('sha256').update(token).digest('hex');
@@ -863,6 +864,39 @@ async function rescopeClient(clientId: string, args: string[]) {
}
}
+/** `gbrain auth rescope-token`: the legacy-token twin of rescope-client (src/core/grants/legacy-token.ts). */
+async function rescopeToken(args: string[]) {
+ try {
+ const parsed = parseRescopeTokenArgs(args);
+ await withConfiguredSql(async (_sql, engine) => {
+ const result = await rescopeLegacyToken(engine, parsed);
+ if (parsed.json) { console.log(JSON.stringify(result, null, 2)); return; }
+ const verb = !result.changed ? 'grants' : result.dryRun ? 'grant preview' : 'rescoped';
+ console.log(`Legacy token ${verb}: ${result.name} (${result.id})`);
+ const rows: Array<[string, keyof typeof result.before]> = [['Sources', 'sources'], ['Takes holders', 'takesHolders'], ['Operations', 'operations']];
+ for (const [label, key] of rows) {
+ const before = renderLegacyGrantAxis(result.before[key]);
+ const after = renderLegacyGrantAxis(result.after[key]);
+ console.log(` ${label}: ${before === after ? after : `${before} -> ${after}`}`);
+ }
+ if (result.refresh) {
+ const { available, added, unregistered } = result.refresh;
+ console.log(` New operations available: ${available.length ? available.join(', ') : 'none'}`);
+ if (unregistered.length) console.log(` Granted but no longer registered: ${unregistered.join(', ')}`);
+ if (added.length) console.log(` Added: ${added.join(', ')}`);
+ else if (available.length) {
+ const add = available.length <= 8 ? `--add ${available.join(',')}` : '--add <op,...>';
+ console.log(` Nothing widened. Grant them with: gbrain auth rescope-token ${result.name} --refresh-operations ${add} (or --all-new)`);
+ }
+ }
+ if (result.changed && !result.dryRun) console.log('Grants apply on the next request; the token secret is unchanged.');
+ });
+ } catch (error) {
+ console.error('Error:', error instanceof Error ? error.message : String(error));
+ process.exit(1);
+ }
+}
+
/**
* E4 (WP4 expansion): `gbrain auth clients [--usage] [--days N] [--json]`.
*
@@ -1093,7 +1127,19 @@ Usage:
gbrain auth revoke <name> Revoke a legacy token (ALL active rows with that name)
gbrain auth revoke --id <uuid> Revoke exactly one token by id (names are not unique)
gbrain auth permissions <name> set-takes-holders <h1,h2,h3>
- Update visibility for an existing token
+ Update visibility for an existing token (alias of
+ rescope-token --takes-holders)
+ gbrain auth rescope-token <name>|--id <uuid> [options] Change a legacy token's grants in place (the token
+ twin of rescope-client). Only the flags you pass
+ change; the token secret is unchanged. With no
+ grant flag it prints the stored grants.
+ --sources <id1,id2,...|none> Source grant (first = write source; 'none' = deny-all)
+ --takes-holders <h1,h2,...|none> Takes-holder allow-list ('none' = deny-all)
+ --operations <op1,op2,...|none> Operation snapshot ('none' = deny-all)
+ --reset-default <sources,takes-holders,operations> Restore the auth create default for those axes
+ --refresh-operations [--add <op,...>|--all-new] Preview operations added since the snapshot; widen only
+ by the ones --add names (or all with --all-new)
+ --dry-run / --json Preview without writing / machine-readable output
gbrain auth register-client <name> [options] Register an OAuth 2.1 client (v0.26+)
--grant-types <client_credentials,authorization_code> (default: client_credentials;
auto-set to authorization_code,refresh_token
@@ -1181,6 +1227,7 @@ export async function runAuth(args: string[]): Promise<void> {
}
case 'register-client': await registerClient(rest[0], rest.slice(1)); return;
case 'rescope-client': await rescopeClient(rest[0], rest.slice(1)); return;
+ case 'rescope-token': await rescopeToken(rest); return;
case 'revoke-client': await revokeClient(rest[0]); return;
case 'clients': await clientsCmd(rest); return;
case 'test': {
diff --git a/src/commands/serve-http-webhooks.ts b/src/commands/serve-http-webhooks.ts
index 907d5f6da2..058743c5ca 100644
--- a/src/commands/serve-http-webhooks.ts
+++ b/src/commands/serve-http-webhooks.ts
@@ -24,6 +24,8 @@ import {
type IngestionEvent,
} from '../core/ingestion/types.ts';
import type { ServeHttpContext } from './serve-http.ts';
+import { NO_SOURCES } from '../core/source-id.ts';
+import { noSourceGrantError } from '../core/ops/context.ts';
/**
* v0.46: normalize the per-event GitHub webhook payload shape into
@@ -320,6 +322,11 @@ async function handleIngest(
// The webhook queue bypasses MCP dispatch and does not carry an original
// operation grant through execution. A snapshot-bound client must use the
// shared MCP write path until ingestion has that same policy contract.
+ if (authInfo.sourceId === NO_SOURCES) {
+ const refusal = noSourceGrantError('POST /ingest');
+ res.status(403).json({ error: refusal.code, message: refusal.message, detail: refusal.detail, hint: refusal.suggestion, docs_url: refusal.docs });
+ return;
+ }
if (authInfo.allowedOperations != null || authInfo.grantProjectionDegraded) {
res.status(403).json({
error: 'permission_denied',
diff --git a/src/core/grants/legacy-token.ts b/src/core/grants/legacy-token.ts
new file mode 100644
index 0000000000..c465060db1
--- /dev/null
+++ b/src/core/grants/legacy-token.ts
@@ -0,0 +1,195 @@
+/**
+ * Legacy bearer-token grants (`gbrain auth rescope-token`), the token twin of
+ * `auth rescope-client`. Three axes live in `access_tokens.permissions`:
+ *
+ * - `source_id` (`--sources a,b|none`): array, element 0 = write source
+ * - `takes_holders` (`--takes-holders a,b|none`)
+ * - `allowed_operations` (`--operations a,b|none`, `--refresh-operations`)
+ *
+ * `none` stores the explicit empty list (deny-all). An omitted flag preserves
+ * the stored value. `--reset-default <axes>` restores the `auth create`
+ * default for the named axes (no source grant → the historical `default`
+ * floor; takes holders `['world']`; no operation snapshot). Every other key in
+ * `permissions` is preserved. `--refresh-operations` only previews unless
+ * `--add <op,...>` or `--all-new` names the operations to widen by. With no
+ * grant flag the command only prints the stored grants.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { coerceLegacyPermissions, normalizeTokenScopes, parseLegacyOperationGrant, parseLegacyTokenScope, parseTakesHoldersAllowList } from '../legacy-token-scope.ts';
+import { NO_SOURCES, isValidSourceId } from '../source-id.ts';
+import { operationScopesAllowed } from '../scope.ts';
+import { executeRawJsonb } from '../sql-query.ts';
+import { TOKEN_ID_RE } from '../token-mint.ts';
+import { GrantError } from './model.ts';
+
+export type LegacyGrantAxis = 'sources' | 'takes-holders' | 'operations';
+const AXES: readonly LegacyGrantAxis[] = ['sources', 'takes-holders', 'operations'];
+
+export interface RescopeTokenArgs {
+ target: { name: string } | { id: string };
+ sources?: string[];
+ takesHolders?: string[];
+ operations?: string[];
+ reset: LegacyGrantAxis[];
+ refreshOperations: boolean;
+ add?: string[];
+ allNew: boolean;
+ dryRun: boolean;
+ json: boolean;
+}
+
+export interface LegacyTokenGrantView {
+ sources: string[] | 'default';
+ takesHolders: string[];
+ operations: string[] | 'unrestricted';
+}
+
+export interface RescopeTokenResult {
+ id: string;
+ name: string;
+ dryRun: boolean;
+ changed: boolean;
+ before: LegacyTokenGrantView;
+ after: LegacyTokenGrantView;
+ refresh?: { available: string[]; added: string[]; unregistered: string[] };
+}
+
+const csvOrNone = (value: string): string[] =>
+ value === 'none' ? [] : [...new Set(value.split(',').map(s => s.trim()).filter(Boolean))];
+
+export function parseRescopeTokenArgs(args: string[]): RescopeTokenArgs {
+ let target: RescopeTokenArgs['target'] | undefined;
+ const out: Omit<RescopeTokenArgs, 'target'> = { reset: [], refreshOperations: false, allNew: false, dryRun: false, json: false };
+ for (let i = 0; i < args.length; i++) {
+ const flag = args[i];
+ if (flag === '--dry-run') { out.dryRun = true; continue; }
+ if (flag === '--json') { out.json = true; continue; }
+ if (flag === '--refresh-operations') { out.refreshOperations = true; continue; }
+ if (flag === '--all-new') { out.allNew = true; continue; }
+ if (!flag.startsWith('--')) {
+ if (target) throw new GrantError('invalid_grant', `Unexpected argument: ${flag}`);
+ target = { name: flag };
+ continue;
+ }
+ const value = args[++i];
+ if (value === undefined || value.startsWith('--')) throw new GrantError('invalid_grant', `${flag} requires a value`);
+ switch (flag) {
+ case '--id':
+ if (target) throw new GrantError('invalid_grant', 'Pass either a token name or --id, not both');
+ if (!TOKEN_ID_RE.test(value)) throw new GrantError('invalid_grant', '--id must be a token id from `gbrain auth list`');
+ target = { id: value };
+ break;
+ case '--sources': out.sources = csvOrNone(value); break;
+ case '--takes-holders': out.takesHolders = csvOrNone(value); break;
+ case '--operations': out.operations = csvOrNone(value); break;
+ case '--add': out.add = csvOrNone(value); break;
+ case '--reset-default':
+ for (const axis of csvOrNone(value)) {
+ if (!(AXES as readonly string[]).includes(axis)) throw new GrantError('invalid_grant', `--reset-default takes ${AXES.join(', ')}`);
+ out.reset.push(axis as LegacyGrantAxis);
+ }
+ break;
+ default: throw new GrantError('invalid_grant', `Unknown flag: ${flag}`);
+ }
+ }
+ if (!target) throw new GrantError('invalid_grant', 'Name the token to rescope (or pass --id <uuid>)');
+ const set = { sources: out.sources, 'takes-holders': out.takesHolders, operations: out.operations };
+ for (const axis of out.reset) {
+ if (set[axis] !== undefined) throw new GrantError('invalid_grant', `--reset-default ${axis} conflicts with --${axis}`);
+ }
+ if ((out.add || out.allNew) && !out.refreshOperations) throw new GrantError('invalid_grant', '--add and --all-new require --refresh-operations');
+ if (out.add && out.allNew) throw new GrantError('invalid_grant', 'Pass either --add or --all-new, not both');
+ if (out.refreshOperations && (out.operations !== undefined || out.reset.includes('operations'))) {
+ throw new GrantError('invalid_grant', '--refresh-operations cannot be combined with --operations or --reset-default operations');
+ }
+ return { target, ...out };
+}
+
+function view(permissions: Record<string, unknown>): LegacyTokenGrantView {
+ const scope = parseLegacyTokenScope(permissions.source_id);
+ const operations = parseLegacyOperationGrant(permissions.allowed_operations);
+ return {
+ sources: permissions.source_id == null ? 'default'
+ : scope.sourceId === NO_SOURCES ? [] : scope.allowedSources ?? [scope.sourceId],
+ takesHolders: parseTakesHoldersAllowList(permissions.takes_holders) ?? ['world'],
+ operations: operations ?? 'unrestricted',
+ };
+}
+
+/** Remote operations a token with these scopes could call: the refresh candidate set. */
+async function grantableOperations(scopes: string[]): Promise<{ all: Set<string>; grantable: string[] }> {
+ const { operations } = await import('../operations.ts');
+ const remote = operations.filter(op => !op.localOnly);
+ return {
+ all: new Set(remote.map(op => op.name)),
+ grantable: remote.filter(op => operationScopesAllowed(scopes, op)).map(op => op.name).sort(),
+ };
+}
+
+async function assertActiveSources(engine: BrainEngine, ids: string[]): Promise<void> {
+ for (const id of ids) {
+ if (!isValidSourceId(id)) throw new GrantError('invalid_grant', `Invalid source id: ${id}`);
+ }
+ if (ids.length === 0) return;
+ const rows = await engine.executeRaw<{ id: string }>(
+ 'SELECT id FROM sources WHERE id = ANY($1::text[]) AND archived IS NOT TRUE', [ids]);
+ const active = new Set(rows.map(r => r.id));
+ const missing = ids.filter(id => !active.has(id));
+ if (missing.length) throw new GrantError('invalid_grant', `Unknown or archived source: ${missing.join(', ')} (see gbrain sources list)`);
+}
+
+export async function rescopeLegacyToken(engine: BrainEngine, args: RescopeTokenArgs): Promise<RescopeTokenResult> {
+ return engine.transaction(async tx => {
+ const rows = 'id' in args.target
+ ? await tx.executeRaw<Record<string, unknown>>('SELECT id, name, scopes, permissions FROM access_tokens WHERE id = $1::uuid AND revoked_at IS NULL FOR UPDATE', [args.target.id])
+ : await tx.executeRaw<Record<string, unknown>>('SELECT id, name, scopes, permissions FROM access_tokens WHERE name = $1 AND revoked_at IS NULL FOR UPDATE', [args.target.name]);
+ const label = 'id' in args.target ? `id ${args.target.id}` : `"${args.target.name}"`;
+ if (rows.length === 0) throw new GrantError('invalid_grant', `No active token ${label} (see gbrain auth list)`);
+ if (rows.length > 1) throw new GrantError('invalid_grant', `${rows.length} active tokens are named ${label}; pass --id <uuid> from gbrain auth list`);
+ const row = rows[0];
+ const current = coerceLegacyPermissions(row.permissions) ?? {};
+ const next: Record<string, unknown> = { ...current };
+
+ if (args.sources !== undefined) {
+ await assertActiveSources(tx, args.sources);
+ next.source_id = args.sources;
+ }
+ if (args.takesHolders !== undefined) next.takes_holders = args.takesHolders;
+ let refresh: RescopeTokenResult['refresh'];
+ const { all, grantable } = await grantableOperations(normalizeTokenScopes(row.scopes) ?? ['read', 'write', 'admin']);
+ if (args.operations !== undefined) {
+ const unknown = args.operations.filter(op => !all.has(op));
+ if (unknown.length) throw new GrantError('invalid_grant', `Unknown remote operation: ${unknown.join(', ')}`);
+ next.allowed_operations = args.operations;
+ }
+ for (const axis of args.reset) {
+ if (axis === 'sources') delete next.source_id;
+ if (axis === 'takes-holders') next.takes_holders = ['world'];
+ if (axis === 'operations') delete next.allowed_operations;
+ }
+ if (args.refreshOperations) {
+ const granted = parseLegacyOperationGrant(current.allowed_operations);
+ if (granted === undefined) {
+ throw new GrantError('invalid_grant', `Token ${label} has no operation snapshot, so it already reaches every operation its scopes allow; nothing to refresh`);
+ }
+ const available = grantable.filter(op => !granted.includes(op));
+ const added = args.allNew ? available : args.add ?? [];
+ const notAvailable = added.filter(op => !available.includes(op));
+ if (notAvailable.length) throw new GrantError('invalid_grant', `Not a new operation for this token: ${notAvailable.join(', ')} (run --refresh-operations alone to preview)`);
+ if (added.length) next.allowed_operations = [...granted, ...added];
+ refresh = { available, added, unregistered: granted.filter(op => !all.has(op)) };
+ }
+
+ const changed = JSON.stringify(next) !== JSON.stringify(current);
+ if (changed && !args.dryRun) {
+ await executeRawJsonb(tx, 'UPDATE access_tokens SET permissions = $2::jsonb WHERE id = $1::uuid', [String(row.id)], [next]);
+ }
+ return { id: String(row.id), name: String(row.name), dryRun: args.dryRun, changed, before: view(current), after: view(next), ...(refresh ? { refresh } : {}) };
+ });
+}
+
+export function renderLegacyGrantAxis(value: string[] | 'default' | 'unrestricted'): string {
+ if (value === 'default') return 'default (no source grant)';
+ if (value === 'unrestricted') return 'unrestricted (every operation the scopes allow)';
+ return value.length === 0 ? 'none (deny-all)' : value.join(', ');
+}
diff --git a/src/core/legacy-token-scope.ts b/src/core/legacy-token-scope.ts
index 88a020acc7..ac93cd22ff 100644
--- a/src/core/legacy-token-scope.ts
+++ b/src/core/legacy-token-scope.ts
@@ -1,4 +1,5 @@
import { ALLOWED_SCOPES } from './scope.ts';
+import { NO_SOURCES } from './source-id.ts';
/**
* Derive a legacy bearer token's source scope from its stored
@@ -6,8 +7,11 @@ import { ALLOWED_SCOPES } from './scope.ts';
*
* ARRAY = federated read grant, exposed through `allowedSources` with the
* first granted source as the scalar write floor. STRING = scalar source.
- * Missing, empty, or garbage values fail closed to the historical `default`
- * floor and NEVER widen to all sources.
+ * An array with no usable source id is the explicit no-source grant
+ * (`auth rescope-token --sources none`): the `NO_SOURCES` sentinel with an
+ * empty `allowedSources`, which reads, writes and publication all refuse.
+ * Missing or non-array garbage values keep the historical `default` floor.
+ * Nothing here ever widens to all sources.
*/
export function parseLegacyTokenScope(rawSource: unknown): { sourceId: string; allowedSources?: string[] } {
if (Array.isArray(rawSource)) {
@@ -15,7 +19,7 @@ export function parseLegacyTokenScope(rawSource: unknown): { sourceId: string; a
if (allowedSources.length > 0) {
return { sourceId: allowedSources[0], allowedSources };
}
- return { sourceId: 'default' };
+ return { sourceId: NO_SOURCES, allowedSources: [] };
}
if (typeof rawSource === 'string' && rawSource.length > 0) {
return { sourceId: rawSource };
diff --git a/src/core/ops/context.ts b/src/core/ops/context.ts
index 6852bb3060..cc0630f049 100644
--- a/src/core/ops/context.ts
+++ b/src/core/ops/context.ts
@@ -15,7 +15,7 @@ import { resolve, relative, sep } from 'path';
import { OperationError } from './contract.ts';
import type { AuthInfo, Operation, OperationContext } from './contract.ts';
import { CJK_SLUG_CHARS, SLUG_WORD_CHARS } from '../cjk.ts';
-import { ALL_SOURCES, isValidSourceId } from '../source-id.ts';
+import { ALL_SOURCES, NO_SOURCES, isValidSourceId } from '../source-id.ts';
import { encodeDeepResearchId } from '../deep-research-id.ts';
import { isSearchMode } from '../search/mode.ts';
import { stampEvidence } from '../search/evidence.ts';
@@ -374,6 +374,20 @@ export function opAllowedForBoundClient(
return CLIENT_FENCED_WRITE_OPS.has(op.name);
}
+/**
+ * The explicit no-source grant (`permissions.source_id: []`, written by
+ * `gbrain auth rescope-token <name> --sources none`) refuses every operation:
+ * it never falls back to the `default` floor for reads or writes.
+ */
+export function noSourceGrantError(operation?: string): OperationError {
+ const err = new OperationError('permission_denied',
+ `${operation ? `${operation}: ` : ''}this token is granted no sources (its source grant is an explicit empty list).`,
+ 'On the brain host, grant sources with: gbrain auth rescope-token <name> --sources <id,...>',
+ 'docs/mcp/ADMIN.md#legacy-token-grants');
+ err.detail = 'fence=no_source_grant';
+ return err;
+}
+
/**
* Fail-closed gate for slug-bound clients, applied at dispatch (the single
* choke point both MCP transports share) so it cannot be forgotten per op.
@@ -385,6 +399,7 @@ export function enforceBoundClientOpAllowList(
auth: AuthInfo | undefined,
op: Pick<Operation, 'name' | 'scope' | 'mutating'>,
): void {
+ if (auth?.sourceId === NO_SOURCES) throw noSourceGrantError(op.name);
if (opAllowedForBoundClient(auth, op)) return;
if (auth?.grantProjectionDegraded || (Array.isArray(auth?.allowedOperations) && !auth.allowedOperations.includes(op.name))) {
const err = new OperationError('permission_denied', `${op.name} is outside this client's approved operation snapshot.`,
@@ -461,6 +476,7 @@ export function validateFilename(name: string): void {
* same precedence ladder — drift between sites is the bug class.
*/
export function sourceScopeOpts(ctx: OperationContext): { sourceId?: string; sourceIds?: string[] } {
+ if (ctx.sourceId === NO_SOURCES || ctx.auth?.sourceId === NO_SOURCES) throw noSourceGrantError();
const allowed = ctx.auth?.allowedSources;
// Treat an empty `allowedSources: []` as "no federated read scope" — the
// op-handler defers to scalar `ctx.sourceId` below. An attacker-controlled
diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.ts
index 1f42af20b3..69d8b0244a 100644
--- a/src/core/persistence/authority.ts
+++ b/src/core/persistence/authority.ts
@@ -1,7 +1,8 @@
import type { BrainEngine } from '../engine.ts';
import type { OperationContext } from '../ops/contract.ts';
import { OperationError } from '../ops/contract.ts';
-import { slugUnderBoundPrefixes, matchesSlugAllowList } from '../ops/context.ts';
+import { slugUnderBoundPrefixes, matchesSlugAllowList, noSourceGrantError } from '../ops/context.ts';
+import { NO_SOURCES } from '../source-id.ts';
import { hasScope } from '../scope.ts';
import { coerceLegacyPermissions, normalizeTokenScopes, parseLegacyTokenScope, parseTakesHoldersAllowList, parseLegacyOperationGrant } from '../legacy-token-scope.ts';
import { readLocalWriter, currentVerifiedLocalWriter, verifyLocalWriter, type LocalGrant } from './identity.ts';
@@ -23,6 +24,7 @@ function assertSkillWriteScopes(scopes: readonly string[], operation: string, re
}
}
export async function submissionAuthority(ctx: OperationContext, operation: string, sourceId: string, sourceIncarnation: string, slug: string): Promise<WriteAuthority> {
+ if (ctx.auth?.sourceId === NO_SOURCES || sourceId === NO_SOURCES) throw noSourceGrantError(operation);
if (ctx.auth?.fenceProjectionDegraded || ctx.auth?.grantProjectionDegraded) deny('The grant projection is incomplete.');
let principal: Principal;
let localGrant: LocalGrant | undefined;
diff --git a/src/core/source-id.ts b/src/core/source-id.ts
index f270e19f4f..dac3bb1eb0 100644
--- a/src/core/source-id.ts
+++ b/src/core/source-id.ts
@@ -44,6 +44,15 @@ export const SOURCE_ID_RE = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;
*/
export const ALL_SOURCES = '__all__';
+/**
+ * Sentinel for a legacy token whose stored source grant is an explicit empty
+ * list (`gbrain auth rescope-token <name> --sources none`). Like
+ * `ALL_SOURCES` it can never name a real source; `sourceScopeOpts`, the
+ * dispatch fence and write submission refuse it instead of falling back to
+ * the `default` floor.
+ */
+export const NO_SOURCES = '__none__';
+
/** Returns true if the string matches the canonical source_id regex. */
export function isValidSourceId(s: unknown): s is string {
return typeof s === 'string' && SOURCE_ID_RE.test(s);
diff --git a/test/auth-rescope-token.serial.test.ts b/test/auth-rescope-token.serial.test.ts
new file mode 100644
index 0000000000..f0fbab7fc8
--- /dev/null
+++ b/test/auth-rescope-token.serial.test.ts
@@ -0,0 +1,223 @@
+/**
+ * #5231 / #5893 (O-DX-4, O-ENG-7): `gbrain auth rescope-token` run as a real
+ * CLI subprocess against a sandboxed PGLite brain, then enforced in process.
+ *
+ * Protects: `none` stores an explicit empty list that both HTTP auth paths
+ * (the legacy bearer transport and the OAuth provider behind `serve --http`)
+ * enforce as deny-all for reads and writes, never the `default` floor; an
+ * omitted flag preserves the stored value; `--refresh-operations` without
+ * `--add`/`--all-new` widens nothing; a write accepted before the rescope is
+ * refused at publication. Regression it catches: `parseLegacyTokenScope([])`
+ * mapping the explicit empty grant back to `default` (the pre-fix contract),
+ * or a CLI that whole-replaces `permissions` and drops other grant keys.
+ * Serial: each CLI call is a subprocess that takes the PGLite lock.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { createEngine } from '../src/core/engine-factory.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { AuthInfo, OperationContext } from '../src/core/ops/contract.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { startHttpTransport } from '../src/mcp/http-transport.ts';
+import { RateLimiter } from '../src/mcp/rate-limit.ts';
+import { NO_SOURCES } from '../src/core/source-id.ts';
+import { submissionAuthority, authorizeStoredRequest } from '../src/core/persistence/authority.ts';
+import { admitWrite } from '../src/core/persistence/journal.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import express from 'express';
+import type { Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import { mountWebhooks } from '../src/commands/serve-http-webhooks.ts';
+import type { ServeHttpContext } from '../src/commands/serve-http.ts';
+
+const CLI = join(resolve(import.meta.dir, '..'), 'src', 'cli.ts');
+let root: string, home: string, db: string;
+
+function env(): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const [key, value] of Object.entries(process.env)) if (value !== undefined) out[key] = value;
+ for (const key of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_BRAIN_ID', 'GBRAIN_SOURCE', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY']) delete out[key];
+ return { ...out, HOME: home, GBRAIN_HOME: home, GBRAIN_SELF_UPGRADE_MODE: 'off', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SWEEP: '0' };
+}
+
+async function cli(...args: string[]) {
+ const proc = Bun.spawn(['bun', 'run', CLI, ...args], { cwd: root, env: env(), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { stdout, stderr, exitCode };
+}
+
+async function withBrain<T>(run: (engine: BrainEngine) => Promise<T>): Promise<T> {
+ const config = { engine: 'pglite' as const, database_path: db };
+ const engine = await createEngine(config);
+ await engine.connect(config);
+ try { return await run(engine); } finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+}
+
+async function permissions(name: string): Promise<Record<string, unknown>> {
+ return withBrain(async engine => {
+ const [row] = await engine.executeRaw<{ permissions: Record<string, unknown> }>(
+ 'SELECT permissions FROM access_tokens WHERE name = $1 AND revoked_at IS NULL', [name]);
+ return row.permissions;
+ });
+}
+
+async function mint(name: string): Promise<string> {
+ const created = await cli('auth', 'create', name, '--scopes', 'read,write');
+ expect(created.exitCode).toBe(0);
+ return (created.stdout.match(/gbrain_[a-f0-9]{64}/) ?? [''])[0];
+}
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'gb-rescope-token-'));
+ home = join(root, 'home');
+ db = join(root, 'db');
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: db }));
+ await withBrain(async engine => {
+ await engine.initSchema();
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('other','other') ON CONFLICT DO NOTHING");
+ await engine.putPage('notes/shared', { type: 'note', title: 'Shared', compiled_truth: 'rescope-marker prose', timeline: '', frontmatter: {} }, { sourceId: 'default' });
+ });
+}, 120_000);
+
+afterAll(() => { rmSync(root, { recursive: true, force: true }); });
+
+describe('auth rescope-token CLI', () => {
+ test('none stores deny-all, omission preserves, other keys survive', async () => {
+ await mint('tok-none');
+ const set = await cli('auth', 'rescope-token', 'tok-none', '--sources', 'none', '--takes-holders', 'none', '--operations', 'get_page,search');
+ expect(set.exitCode).toBe(0);
+ expect(set.stdout).toContain('Sources: default (no source grant) -> none (deny-all)');
+ expect(await permissions('tok-none')).toEqual({ source_id: [], takes_holders: [], allowed_operations: ['get_page', 'search'] });
+
+ const partial = await cli('auth', 'rescope-token', 'tok-none', '--takes-holders', 'world,brain');
+ expect(partial.exitCode).toBe(0);
+ expect(await permissions('tok-none')).toEqual({ source_id: [], takes_holders: ['world', 'brain'], allowed_operations: ['get_page', 'search'] });
+
+ const inspect = await cli('auth', 'rescope-token', 'tok-none');
+ expect(inspect.exitCode).toBe(0);
+ expect(inspect.stdout).toContain('Sources: none (deny-all)');
+ expect(inspect.stdout).toContain('Operations: get_page, search');
+
+ const alias = await cli('auth', 'permissions', 'tok-none', 'set-takes-holders', 'world');
+ expect(alias.exitCode).toBe(0);
+ expect(await permissions('tok-none')).toEqual({ source_id: [], takes_holders: ['world'], allowed_operations: ['get_page', 'search'] });
+ }, 120_000);
+
+ test('refresh-operations previews without widening; --add widens by exactly the named operation', async () => {
+ await mint('tok-refresh');
+ expect((await cli('auth', 'rescope-token', 'tok-refresh', '--operations', 'get_page')).exitCode).toBe(0);
+ const preview = await cli('auth', 'rescope-token', 'tok-refresh', '--refresh-operations');
+ expect(preview.exitCode).toBe(0);
+ expect(preview.stdout).toContain('Legacy token grants: tok-refresh');
+ expect(preview.stdout).toMatch(/New operations available: .*\bsearch\b/);
+ expect((await permissions('tok-refresh')).allowed_operations).toEqual(['get_page']);
+
+ const added = await cli('auth', 'rescope-token', 'tok-refresh', '--refresh-operations', '--add', 'search');
+ expect(added.exitCode).toBe(0);
+ expect((await permissions('tok-refresh')).allowed_operations).toEqual(['get_page', 'search']);
+
+ const refused = await cli('auth', 'rescope-token', 'tok-refresh', '--refresh-operations', '--add', 'get_page');
+ expect(refused.exitCode).toBe(1);
+ expect(refused.stderr).toContain('Not a new operation for this token: get_page');
+ }, 120_000);
+
+ test('reset-default restores the auth create defaults; unknown sources refuse', async () => {
+ await mint('tok-reset');
+ expect((await cli('auth', 'rescope-token', 'tok-reset', '--sources', 'other,default', '--takes-holders', 'none')).exitCode).toBe(0);
+ expect(await permissions('tok-reset')).toEqual({ source_id: ['other', 'default'], takes_holders: [] });
+ expect((await cli('auth', 'rescope-token', 'tok-reset', '--reset-default', 'sources,takes-holders')).exitCode).toBe(0);
+ expect(await permissions('tok-reset')).toEqual({ takes_holders: ['world'] });
+ const unknown = await cli('auth', 'rescope-token', 'tok-reset', '--sources', 'missing-source');
+ expect(unknown.exitCode).toBe(1);
+ expect(unknown.stderr).toContain('Unknown or archived source: missing-source');
+ }, 120_000);
+});
+
+describe('explicit no-source grant is enforced (O-ENG-7)', () => {
+ test('both HTTP auth paths deny reads and writes to default and another source', async () => {
+ const token = await mint('tok-deny');
+ expect((await cli('auth', 'rescope-token', 'tok-deny', '--sources', 'none')).exitCode).toBe(0);
+ await withBrain(async engine => {
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const auth = await provider.verifyAccessToken(token) as unknown as AuthInfo;
+ expect(auth.sourceId).toBe(NO_SOURCES);
+ expect(auth.allowedSources).toEqual([]);
+ for (const [name, args] of [
+ ['search', { query: 'rescope-marker' }],
+ ['get_page', { slug: 'notes/shared' }],
+ ['query', { query: 'rescope-marker', source_id: 'default' }],
+ ['put_page', { slug: 'notes/new', content: 'new prose' }],
+ ['put_page', { slug: 'notes/new', content: 'new prose', source_id: 'other' }],
+ ] as const) {
+ const result = await dispatchToolCall(engine, name, { ...args }, { remote: true, transport: 'http', sourceId: auth.sourceId, auth });
+ expect(result.isError).toBe(true);
+ expect(JSON.parse(result.content[0].text).error).toBe('permission_denied');
+ }
+
+ const server = await startHttpTransport({ port: 0, engine, surface: 'full', limiters: {
+ ip: new RateLimiter({ limit: 10_000, windowMs: 60_000, lruCap: 100 }),
+ token: new RateLimiter({ limit: 10_000, windowMs: 60_000, lruCap: 100 }),
+ } });
+ try {
+ for (const [name, args] of [['search', { query: 'rescope-marker' }], ['put_page', { slug: 'notes/legacy', content: 'x', source_id: 'default' }]] as const) {
+ const response = await fetch(`http://127.0.0.1:${server.port}/mcp`, {
+ method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }),
+ });
+ const body = await response.json() as { result: { isError?: boolean; content: Array<{ text: string }> } };
+ expect(body.result.isError).toBe(true);
+ expect(JSON.parse(body.result.content[0].text).error).toBe('permission_denied');
+ }
+ } finally { server.stop?.(); }
+ expect(await engine.getPage('notes/new', { sourceId: 'default' })).toBeNull();
+ });
+ }, 120_000);
+
+ test('POST /ingest refuses a no-source token before queueing', async () => {
+ const token = await mint('tok-ingest');
+ expect((await cli('auth', 'rescope-token', 'tok-ingest', '--sources', 'none')).exitCode).toBe(0);
+ await withBrain(async engine => {
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const app = express();
+ const pass: express.RequestHandler = (_req, _res, next) => next();
+ mountWebhooks(app, { engine, resourceVerifier: provider, resourceMetadataUrl: 'http://127.0.0.1/.well-known/oauth-protected-resource',
+ ingestRateLimiter: pass, githubWebhookLimiter: pass, broadcastEvent: () => {} } as unknown as ServeHttpContext);
+ const server = await new Promise<Server>(resolve => { const s = app.listen(0, '127.0.0.1', () => resolve(s)); });
+ try {
+ const response = await fetch(`http://127.0.0.1:${(server.address() as AddressInfo).port}/ingest`, { method: 'POST',
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'text/markdown' }, body: '# Capture\n\nno-source prose' });
+ expect(response.status).toBe(403);
+ expect(await response.json()).toMatchObject({ error: 'permission_denied', detail: 'fence=no_source_grant', docs_url: 'docs/mcp/ADMIN.md#legacy-token-grants' });
+ const [jobs] = await engine.executeRaw<{ n: number }>("SELECT COUNT(*)::int AS n FROM minion_jobs WHERE name = 'ingest_capture'");
+ expect(jobs.n).toBe(0);
+ } finally { await new Promise<void>(resolve => server.close(() => resolve())); }
+ });
+ }, 120_000);
+
+ test('a write accepted before the rescope is refused at publication', async () => {
+ const token = await mint('tok-publish');
+ expect((await cli('auth', 'rescope-token', 'tok-publish', '--sources', 'default')).exitCode).toBe(0);
+ const row = await withBrain(async engine => {
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const auth = await provider.verifyAccessToken(token) as unknown as AuthInfo;
+ const ctx = { engine, config: { engine: 'pglite' }, sourceId: 'default', auth, remote: true, dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;
+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'");
+ const authority = await submissionAuthority(ctx, 'put_page', 'default', source.incarnation, 'notes/shared');
+ const admitted = await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: 'default',
+ sourceIncarnation: source.incarnation, slug: 'notes/shared', requestId: randomUUID(), callerIntent: {}, intent: {} });
+ await authorizeStoredRequest(engine, admitted);
+ return admitted;
+ });
+ expect((await cli('auth', 'rescope-token', 'tok-publish', '--sources', 'none')).exitCode).toBe(0);
+ await withBrain(async engine => {
+ await expect(authorizeStoredRequest(engine, row)).rejects.toMatchObject({ code: 'permission_denied' });
+ });
+ }, 120_000);
+});
diff --git a/test/e2e/auth-rescope-token.test.ts b/test/e2e/auth-rescope-token.test.ts
new file mode 100644
index 0000000000..fdbe9d84e2
--- /dev/null
+++ b/test/e2e/auth-rescope-token.test.ts
@@ -0,0 +1,83 @@
+/**
+ * #5231 / #5893 (O-ENG-7) on real Postgres: `rescopeLegacyToken` (the
+ * `gbrain auth rescope-token` core) stores real JSONB objects and arrays
+ * (postgres.js double-encode class), binds its source list as text[], and the
+ * explicit no-source grant is enforced by both HTTP auth paths and by
+ * publication reauthorization. PGLite and the real CLI subprocess are covered
+ * by test/auth-rescope-token.serial.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import { mintLegacyToken } from '../../src/core/token-mint.ts';
+import { parseRescopeTokenArgs, rescopeLegacyToken } from '../../src/core/grants/legacy-token.ts';
+import { GBrainOAuthProvider } from '../../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../../src/core/sql-query.ts';
+import { NO_SOURCES } from '../../src/core/source-id.ts';
+import type { AuthInfo, OperationContext } from '../../src/core/ops/contract.ts';
+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';
+import { startHttpTransport } from '../../src/mcp/http-transport.ts';
+import { RateLimiter } from '../../src/mcp/rate-limit.ts';
+import { authorizeStoredRequest, submissionAuthority } from '../../src/core/persistence/authority.ts';
+import { admitWrite } from '../../src/core/persistence/journal.ts';
+
+const d = hasDatabase() ? describe : describe.skip;
+
+beforeAll(async () => {
+ if (!hasDatabase()) return;
+ const engine = await setupDB();
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('other-e2e','other-e2e') ON CONFLICT DO NOTHING");
+ await engine.putPage('notes/rescope-e2e', { type: 'note', title: 'Rescope', compiled_truth: 'rescope-e2e-marker prose', timeline: '', frontmatter: {} }, { sourceId: 'default' });
+});
+afterAll(async () => { if (hasDatabase()) await teardownDB(); });
+
+const rescope = (...args: string[]) => rescopeLegacyToken(getEngine(), parseRescopeTokenArgs(args));
+const provider = () => { const engine = getEngine(); return new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) }); };
+
+d('auth rescope-token on Postgres', () => {
+ test('stores JSONB objects and arrays, preserving untouched keys', async () => {
+ const engine = getEngine();
+ const name = `rescope-e2e-${randomUUID().slice(0, 8)}`;
+ const minted = await mintLegacyToken(engine, { name, takesHolders: ['world'], scopes: ['read', 'write'], allowedOperations: ['get_page', 'search'] });
+ await rescope(name, '--sources', 'other-e2e,default', '--takes-holders', 'none');
+ const [row] = await engine.executeRaw<{ permissions: Record<string, unknown>; kind: string; sources: string; holders: string }>(
+ `SELECT permissions, jsonb_typeof(permissions) AS kind, jsonb_typeof(permissions->'source_id') AS sources,
+ jsonb_typeof(permissions->'takes_holders') AS holders FROM access_tokens WHERE id = $1::uuid`, [minted.id]);
+ expect(row).toMatchObject({ kind: 'object', sources: 'array', holders: 'array' });
+ expect(row.permissions).toEqual({ source_id: ['other-e2e', 'default'], takes_holders: [], allowed_operations: ['get_page', 'search'] });
+ await expect(rescope(name, '--sources', 'missing-e2e')).rejects.toThrow('Unknown or archived source: missing-e2e');
+ });
+
+ test('none is enforced on both HTTP auth paths and at publication', async () => {
+ const engine = getEngine();
+ const name = `rescope-e2e-${randomUUID().slice(0, 8)}`;
+ const minted = await mintLegacyToken(engine, { name, takesHolders: ['world'], scopes: ['read', 'write'], sourceGrant: ['default'] });
+ const before = await provider().verifyAccessToken(minted.token) as unknown as AuthInfo;
+ const ctx = { engine, config: { engine: 'postgres' }, sourceId: 'default', auth: before, remote: true, dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;
+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'");
+ const authority = await submissionAuthority(ctx, 'put_page', 'default', source.incarnation, 'notes/rescope-e2e');
+ const admitted = await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: 'default',
+ sourceIncarnation: source.incarnation, slug: 'notes/rescope-e2e', requestId: randomUUID(), callerIntent: {}, intent: {} });
+
+ await rescope(name, '--sources', 'none');
+ await expect(authorizeStoredRequest(engine, admitted)).rejects.toMatchObject({ code: 'permission_denied' });
+
+ const auth = await provider().verifyAccessToken(minted.token) as unknown as AuthInfo;
+ expect(auth.sourceId).toBe(NO_SOURCES);
+ for (const [op, args] of [['search', { query: 'rescope-e2e-marker' }], ['put_page', { slug: 'notes/rescope-e2e-new', content: 'x', source_id: 'other-e2e' }]] as const) {
+ const result = await dispatchToolCall(engine, op, { ...args }, { remote: true, transport: 'http', sourceId: auth.sourceId, auth });
+ expect(JSON.parse(result.content[0].text).error).toBe('permission_denied');
+ }
+ const server = await startHttpTransport({ port: 0, engine, surface: 'full', limiters: {
+ ip: new RateLimiter({ limit: 10_000, windowMs: 60_000, lruCap: 100 }), token: new RateLimiter({ limit: 10_000, windowMs: 60_000, lruCap: 100 }) } });
+ try {
+ const response = await fetch(`http://127.0.0.1:${server.port}/mcp`, { method: 'POST',
+ headers: { authorization: `Bearer ${minted.token}`, 'content-type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'get_page', arguments: { slug: 'notes/rescope-e2e' } } }) });
+ const body = await response.json() as { result: { isError?: boolean; content: Array<{ text: string }> } };
+ expect(body.result.isError).toBe(true);
+ expect(JSON.parse(body.result.content[0].text).error).toBe('permission_denied');
+ } finally { server.stop?.(true); }
+ });
+});
diff --git a/test/fixtures/e2e-unmapped-baseline.txt b/test/fixtures/e2e-unmapped-baseline.txt
index 077e7ac517..5921d1ed1b 100644
--- a/test/fixtures/e2e-unmapped-baseline.txt
+++ b/test/fixtures/e2e-unmapped-baseline.txt
@@ -5,7 +5,6 @@
# added here in a reviewer-visible diff. Removing lines (by mapping the
# file) is always safe. Enforced by test/scripts/e2e-wiring.test.ts.
test/e2e/anomalies-pglite.test.ts
-test/e2e/auth-permissions.test.ts
test/e2e/auth-takes-holders-pglite.test.ts
test/e2e/autopilot-cooldown-parity.test.ts
test/e2e/autopilot-fanout-postgres.test.ts
diff --git a/test/legacy-token-federated-scope.test.ts b/test/legacy-token-federated-scope.test.ts
index 0b75be09ae..7c7628d00e 100644
--- a/test/legacy-token-federated-scope.test.ts
+++ b/test/legacy-token-federated-scope.test.ts
@@ -12,6 +12,7 @@
import { describe, test, expect } from 'bun:test';
import { parseLegacyTokenScope } from '../src/mcp/http-transport.ts';
import { parseTakesHoldersAllowList, coerceLegacyPermissions } from '../src/core/legacy-token-scope.ts';
+import { NO_SOURCES } from '../src/core/source-id.ts';
describe('parseLegacyTokenScope', () => {
test('array grant → allowedSources (federated read) with first as scalar floor', () => {
@@ -31,8 +32,9 @@ describe('parseLegacyTokenScope', () => {
expect(parseLegacyTokenScope(null)).toEqual({ sourceId: 'default' });
});
- test('empty array → default floor, no grant (NOT "all")', () => {
- expect(parseLegacyTokenScope([])).toEqual({ sourceId: 'default' });
+ test('empty array → explicit no-source grant (NEVER the default floor, NOT "all")', () => {
+ expect(parseLegacyTokenScope([])).toEqual({ sourceId: NO_SOURCES, allowedSources: [] });
+ expect(parseLegacyTokenScope(['', 5])).toEqual({ sourceId: NO_SOURCES, allowedSources: [] });
});
test('garbage (number / empty string) → default floor', () => {