Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(grants): F3 spec 4.5 tests 2-10 on PGLite, CLI and Postgres

garrytanc31ef93082d7
diff --git a/test/access-token-grants.test.ts b/test/access-token-grants.test.ts
new file mode 100644
index 0000000000..b7b58d612c
--- /dev/null
+++ b/test/access-token-grants.test.ts
@@ -0,0 +1,271 @@
+/**
+ * F3 (O-CEO-8, O-DX-4, O-ENG-7): one grant shape for legacy bearer tokens,
+ * lazily migrated from `access_tokens.permissions` JSONB to the unified
+ * columns, with a JSONB mirror and fail-closed drift.
+ *
+ * Protects (spec 4.5): a pre-F3 token authenticates identically on both HTTP
+ * paths (2); the unified reader equals lane F's parsers for any stored JSONB,
+ * before and after migration (3); `--sources none` after lazy migration denies
+ * reads, writes and publication (4); a rescope writes the columns, bumps the
+ * revision and leaves the JSONB lane F would have written (5); an older
+ * binary's JSONB edit makes that axis deny until an adopt flag resolves it (6);
+ * `--if-version` compare-and-set (8); `--migrate-legacy` previews without
+ * writing and never changes an effective grant (10). Doctor counts both.
+ * The CLI aliases, client path and rotation live in
+ * test/auth-rescope-unified.serial.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine, executeRawJsonb } from '../src/core/sql-query.ts';
+import { coerceLegacyPermissions, parseLegacyOperationGrant, parseLegacyTokenScope, parseTakesHoldersAllowList } from '../src/core/legacy-token-scope.ts';
+import { authSourcesFromGrant, grantFromTokenRow } from '../src/core/grants/model.ts';
+import { migrateLegacyTokens, parseRescopeTokenArgs, rescopeLegacyToken } from '../src/core/grants/legacy-token.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { NO_SOURCES } from '../src/core/source-id.ts';
+import { generateToken, hashToken } from '../src/core/utils.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';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { describeAuthCapabilities } from '../src/core/harness/capabilities.ts';
+import { legacyTokenGrantsEntry } from '../src/commands/doctor/checks/legacy-token-grants.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('other','other') ON CONFLICT DO NOTHING");
+ await engine.putPage('notes/f3', { type: 'note', title: 'F3', compiled_truth: 'f3-marker prose', timeline: '', frontmatter: {} }, { sourceId: 'default' });
+}, 120_000);
+
+afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+});
+
+const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+const rescope = (...args: string[]) => rescopeLegacyToken(engine, parseRescopeTokenArgs(args));
+const rowOf = async (id: string) => (await engine.executeRaw<Record<string, unknown>>('SELECT * FROM access_tokens WHERE id = $1::uuid', [id]))[0];
+
+/** A token exactly as a pre-F3 binary wrote it: JSONB grant, no grant columns. */
+async function legacyToken(permissions: unknown, scopes: string | null = '{read,write}'): Promise<{ id: string; name: string; token: string }> {
+ const name = `f3-${randomUUID().slice(0, 8)}`;
+ const token = generateToken('gbrain_');
+ const [row] = typeof permissions === 'string'
+ ? await engine.executeRaw<{ id: string }>('INSERT INTO access_tokens (name, token_hash, scopes, permissions) VALUES ($1, $2, $3::text[], to_jsonb($4::text)) RETURNING id', [name, hashToken(token), scopes, permissions])
+ : await executeRawJsonb<{ id: string }>(engine, 'INSERT INTO access_tokens (name, token_hash, scopes, permissions) VALUES ($1, $2, $3::text[], $4::jsonb) RETURNING id', [name, hashToken(token), scopes], [permissions]);
+ return { id: row.id, name, token };
+}
+
+async function doctor() {
+ const checks = await legacyTokenGrantsEntry.run({ engine } as unknown as DoctorContext);
+ if (!Array.isArray(checks)) throw new Error('doctor entry stopped');
+ return Object.fromEntries(checks.map(c => [c.name, c]));
+}
+
+/** Lane F's AuthInfo source fields, computed with lane F's parsers only. */
+function laneFSources(raw: unknown) {
+ const permissions = coerceLegacyPermissions(raw);
+ const { sourceId, allowedSources } = parseLegacyTokenScope(permissions?.source_id);
+ return { sourceId, ...(allowedSources ? { allowedSources } : {}), hasSourceGrant: permissions?.source_id != null };
+}
+
+function grantFields(row: Record<string, unknown>) {
+ const g = grantFromTokenRow(row);
+ return { sources: authSourcesFromGrant(g), operations: g.allowedOperations, takes: g.takesHolders };
+}
+
+describe('2. a pre-F3 token authenticates identically on both HTTP paths', () => {
+ test('oauth-provider fallback and the legacy HTTP transport derive the same grant; reads never migrate', async () => {
+ const t = await legacyToken({ takes_holders: ['world', 'brain'], source_id: ['default', 'other'], allowed_operations: ['get_page', 'search', 'query'] });
+ const oauth = await provider().verifyAccessToken(t.token) as unknown as AuthInfo;
+ expect(oauth).toMatchObject({ scopes: ['read', 'write'], sourceId: 'default', allowedSources: ['default', 'other'], hasSourceGrant: true,
+ allowedOperations: ['get_page', 'search', 'query'], takesHoldersAllowList: ['world', 'brain'] });
+ 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 ${t.token}`, 'content-type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'resources/read', params: { uri: 'gbrain://capabilities' } }) });
+ const body = await response.json() as { result: { contents: Array<{ text: string }> } };
+ const http = JSON.parse(body.result.contents[0].text);
+ const pick = (c: Record<string, unknown>) => ({ scopes: c.scopes, source_id: c.source_id, federated_read: c.federated_read, allowed_operations: c.allowed_operations });
+ expect(pick(http)).toEqual(pick(describeAuthCapabilities(oauth)));
+ } finally { server.stop?.(true); }
+ expect((await rowOf(t.id)).source_grant).toBeNull();
+ }, 60_000);
+});
+
+describe('3. equivalence: the unified reader equals lane F for any stored JSONB, before and after migration', () => {
+ const sources: unknown[] = [undefined, null, [], ['default'], ['other', 'default'], ['', 'other'], [5, 'other'], ['__none__'], 'other', '', 5, { x: 1 }, true];
+ const takes: unknown[] = [undefined, [], ['world'], ['world', '', 3], ['a,b', 'q"x', 'back\\slash'], 'world', null];
+ const ops: unknown[] = [undefined, [], ['get_page'], ['search', 'search'], ['Bad-Op'], 'get_page', null];
+ const values: unknown[] = [];
+ for (const s of sources) for (const h of takes) for (const o of ops) {
+ const p: Record<string, unknown> = {};
+ if (s !== undefined) p.source_id = s;
+ if (h !== undefined) p.takes_holders = h;
+ if (o !== undefined) p.allowed_operations = o;
+ values.push(p);
+ }
+ const doubleEncoded = values.filter((_, i) => i % 7 === 0).map(v => JSON.stringify(v));
+ const garbage = ['{not json', '[1,2]', '"world"'];
+
+ test('legacy rows: authSourcesFromGrant(grantFromTokenRow(row)) equals parseLegacyTokenScope for every value', () => {
+ for (const raw of [...values, ...doubleEncoded, ...garbage, [1], 42, null]) {
+ const row = { id: randomUUID(), permissions: raw, scopes: null };
+ const g = grantFromTokenRow(row);
+ expect({ raw, sources: authSourcesFromGrant(g) }).toEqual({ raw, sources: laneFSources(raw) });
+ const permissions = coerceLegacyPermissions(raw);
+ expect({ raw, ops: g.allowedOperations, takes: g.takesHolders }).toEqual({ raw,
+ ops: parseLegacyOperationGrant(permissions?.allowed_operations) ?? null, takes: parseTakesHoldersAllowList(permissions?.takes_holders) ?? null });
+ }
+ });
+
+ test('migrated rows equal both, with no drift; malformed rows are skipped, never guessed', async () => {
+ await engine.executeRaw('UPDATE access_tokens SET revoked_at = now() WHERE revoked_at IS NULL');
+ const inserted: Array<{ id: string; raw: unknown }> = [];
+ for (const raw of [...values, ...doubleEncoded, ...garbage]) inserted.push({ id: (await legacyToken(raw)).id, raw });
+ const before = new Map<string, ReturnType<typeof grantFields>>();
+ for (const t of inserted) before.set(t.id, grantFields(await rowOf(t.id)));
+ const result = await migrateLegacyTokens(engine, { dryRun: false });
+ expect(result.skipped.map(s => s.id).sort()).toEqual(inserted.filter(t => typeof t.raw === 'string' && garbage.includes(t.raw)).map(t => t.id).sort());
+ expect(result.migrated).toHaveLength(inserted.length - garbage.length);
+ for (const t of inserted) {
+ const row = await rowOf(t.id);
+ if (garbage.includes(t.raw as string)) { expect(row.source_grant).toBeNull(); continue; }
+ const g = grantFromTokenRow(row);
+ expect({ raw: t.raw, shape: g.shape, drift: g.drift }).toEqual({ raw: t.raw, shape: 'unified', drift: [] });
+ expect({ raw: t.raw, after: grantFields(row) }).toEqual({ raw: t.raw, after: before.get(t.id)! });
+ expect({ raw: t.raw, sources: authSourcesFromGrant(g) }).toEqual({ raw: t.raw, sources: laneFSources(t.raw) });
+ }
+ }, 120_000);
+});
+
+describe('4. O-ENG-7 after lazy migration: --sources none denies reads, writes and publication', () => {
+ test('a pre-F3 token rescoped to none keeps scopes and operations and is denied everywhere', async () => {
+ const t = await legacyToken({ takes_holders: ['world'], allowed_operations: ['get_page', 'search', 'query', 'put_page'] });
+ const before = await provider().verifyAccessToken(t.token) as unknown as AuthInfo;
+ const ctx = { engine, config: { engine: 'pglite' }, 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/f3');
+ const admitted = await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: 'default',
+ sourceIncarnation: source.incarnation, slug: 'notes/f3', requestId: randomUUID(), callerIntent: {}, intent: {} });
+ await authorizeStoredRequest(engine, admitted);
+
+ const result = await rescope(t.name, '--sources', 'none');
+ expect(result).toMatchObject({ migrated: true, written: true, shape: 'legacy_permissions' });
+ const row = await rowOf(t.id);
+ expect(row).toMatchObject({ source_grant: 'none', source_id: null, federated_read: [], allowed_operations: ['get_page', 'search', 'query', 'put_page'], scopes: ['read', 'write'] });
+ await expect(authorizeStoredRequest(engine, admitted)).rejects.toMatchObject({ code: 'permission_denied' });
+
+ const auth = await provider().verifyAccessToken(t.token) as unknown as AuthInfo;
+ expect(auth).toMatchObject({ sourceId: NO_SOURCES, allowedSources: [], hasSourceGrant: true, scopes: ['read', 'write'] });
+ for (const [op, args] of [['search', { query: 'f3-marker' }], ['get_page', { slug: 'notes/f3' }], ['query', { query: 'f3-marker', source_id: 'other' }],
+ ['put_page', { slug: 'notes/f3-new', content: 'x' }], ['put_page', { slug: 'notes/f3-new', content: 'x', source_id: 'other' }]] as const) {
+ const out = await dispatchToolCall(engine, op, { ...args }, { remote: true, transport: 'http', sourceId: auth.sourceId, auth });
+ expect(JSON.parse(out.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: 'f3-marker' }], ['put_page', { slug: 'notes/f3-http', content: 'x', source_id: 'default' }]] as const) {
+ const response = await fetch(`http://127.0.0.1:${server.port}/mcp`, { method: 'POST',
+ headers: { authorization: `Bearer ${t.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(JSON.parse(body.result.content[0].text).error).toBe('permission_denied');
+ }
+ } finally { server.stop?.(true); }
+ }, 120_000);
+});
+
+describe('5. lazy migration on rescope', () => {
+ test('writes columns, source_grant and revision+1, mirrors JSONB as lane F would, and doctor count drops by one', async () => {
+ const t = await legacyToken({ takes_holders: ['world'], source_id: ['default'], allowed_operations: ['get_page'], note: 'kept' });
+ const countBefore = (await doctor()).legacy_token_grant_shape.details?.legacy_shape_count as number;
+ expect(countBefore).toBeGreaterThan(0);
+ const result = await rescope(t.name, '--takes-holders', 'world,brain');
+ expect(result.revision).toEqual({ before: 0, after: 1 });
+ const row = await rowOf(t.id);
+ expect(row).toMatchObject({ source_grant: 'federated', source_id: 'default', federated_read: ['default'], takes_holders: ['world', 'brain'], allowed_operations: ['get_page'], grant_revision: 1 });
+ expect(row.permissions).toEqual({ takes_holders: ['world', 'brain'], source_id: ['default'], allowed_operations: ['get_page'], note: 'kept' });
+ expect((await doctor()).legacy_token_grant_shape.details?.legacy_shape_count).toBe(countBefore - 1);
+ });
+
+ test('inspection and dry-run never migrate', async () => {
+ const t = await legacyToken({ takes_holders: ['world'] });
+ await rescope(t.name);
+ await rescope(t.name, '--sources', 'other', '--dry-run');
+ expect((await rowOf(t.id)).source_grant).toBeNull();
+ });
+});
+
+describe('6. drift: an older binary edits the JSONB after migration', () => {
+ test('the drifted axis denies, doctor warns, both adopt flags resolve it', async () => {
+ const minted = await mintLegacyToken(engine, { name: `f3-drift-${randomUUID().slice(0, 8)}`, takesHolders: ['world'], scopes: ['read', 'write'], sourceGrant: ['default'], allowedOperations: ['get_page', 'search'] });
+ expect((await rowOf(minted.id)).source_grant).toBe('federated');
+ await engine.executeRaw(`UPDATE access_tokens SET permissions = jsonb_set(permissions, '{source_id}', '["other"]') WHERE id = $1::uuid`, [minted.id]);
+
+ const auth = await provider().verifyAccessToken(minted.token) as unknown as AuthInfo;
+ expect(auth).toMatchObject({ sourceId: NO_SOURCES, allowedSources: [], allowedOperations: ['get_page', 'search'], takesHoldersAllowList: ['world'] });
+ const checks = await doctor();
+ expect(checks.legacy_token_grant_drift.status).toBe('warn');
+ expect(checks.legacy_token_grant_drift.details?.drift).toContainEqual({ name: minted.name, id: minted.id, axes: ['sources'] });
+ expect(checks.legacy_token_grant_drift.message).toContain(`gbrain auth rescope --token ${minted.name} --adopt-permissions`);
+ await expect(rescope(minted.name, '--takes-holders', 'world,brain')).rejects.toMatchObject({ reasons: ['legacy_token_grant_drift'] });
+
+ await rescope(minted.name, '--adopt-permissions');
+ expect(await provider().verifyAccessToken(minted.token)).toMatchObject({ sourceId: 'other', allowedSources: ['other'] });
+ expect((await rowOf(minted.id)).source_id).toBe('other');
+
+ await engine.executeRaw(`UPDATE access_tokens SET permissions = jsonb_set(permissions, '{allowed_operations}', '["get_page","search","put_page"]') WHERE id = $1::uuid`, [minted.id]);
+ expect(await provider().verifyAccessToken(minted.token)).toMatchObject({ allowedOperations: [] });
+ await rescope(minted.name, '--adopt-columns');
+ const healed = await rowOf(minted.id);
+ expect((healed.permissions as Record<string, unknown>).allowed_operations).toEqual(['get_page', 'search']);
+ expect(await provider().verifyAccessToken(minted.token)).toMatchObject({ allowedOperations: ['get_page', 'search'] });
+ expect((await doctor()).legacy_token_grant_drift.details?.drift).not.toContainEqual(expect.objectContaining({ id: minted.id }));
+ });
+});
+
+describe('8. --if-version', () => {
+ test('a stale revision refuses with the current one; the current one succeeds', async () => {
+ const t = await legacyToken({ takes_holders: ['world'] });
+ await rescope(t.name, '--takes-holders', 'world,brain');
+ await expect(rescope(t.name, '--takes-holders', 'world', '--if-version', '0')).rejects.toMatchObject({
+ code: 'grant_conflict', message: expect.stringContaining('--if-version 1') });
+ expect((await rescope(t.name, '--takes-holders', 'world', '--if-version', '1')).revision).toEqual({ before: 1, after: 2 });
+ });
+});
+
+describe('10. --migrate-legacy', () => {
+ test('--dry-run lists without writing; the real run changes no AuthInfo', async () => {
+ const tokens = [
+ await legacyToken({ takes_holders: ['world', 'brain'], source_id: ['other', 'default'] }),
+ await legacyToken({ takes_holders: [], source_id: [], allowed_operations: [] }),
+ await legacyToken({ source_id: 'other' }, null),
+ await legacyToken(JSON.stringify({ takes_holders: ['world'], allowed_operations: ['search'] })),
+ ];
+ const preview = await migrateLegacyTokens(engine, { dryRun: true });
+ expect(preview.migrated.map(m => m.id)).toEqual(expect.arrayContaining(tokens.map(t => t.id)));
+ for (const t of tokens) expect((await rowOf(t.id)).source_grant).toBeNull();
+ const before = await Promise.all(tokens.map(t => provider().verifyAccessToken(t.token)));
+ await migrateLegacyTokens(engine, { dryRun: false });
+ const after = await Promise.all(tokens.map(t => provider().verifyAccessToken(t.token)));
+ const strip = (a: unknown) => ({ ...(a as Record<string, unknown>), expiresAt: 0 });
+ expect(after.map(strip)).toEqual(before.map(strip));
+ for (const t of tokens) expect((await rowOf(t.id)).source_grant).not.toBeNull();
+ const shape = (await doctor()).legacy_token_grant_shape.details as { legacy_shape_count: number; malformed: unknown[] };
+ expect(shape.legacy_shape_count).toBe(shape.malformed.length);
+ });
+});
diff --git a/test/auth-rescope-unified.serial.test.ts b/test/auth-rescope-unified.serial.test.ts
new file mode 100644
index 0000000000..c24e77a34c
--- /dev/null
+++ b/test/auth-rescope-unified.serial.test.ts
@@ -0,0 +1,184 @@
+/**
+ * F3 (O-CEO-8, O-DX-4): `gbrain auth rescope`, one grant editor for legacy
+ * tokens and OAuth clients, run as a real CLI subprocess against a sandboxed
+ * PGLite brain.
+ *
+ * Protects (spec 4.5): `auth create` births a unified token; `rescope-token`
+ * and `permissions set-takes-holders` stay exact aliases of
+ * `rescope --token`; `rescope --client` and `rescope-client` write identical
+ * rows and `--sources none` on a client refuses with
+ * `client_sources_none_unsupported` (9); `--if-version` mismatch refuses with
+ * the current revision on stdout under --json (8); a bare name that matches a
+ * token and a client refuses; `--migrate-legacy --dry-run` writes nothing (10);
+ * harness rotation mints a unified token that keeps explicit empty lists (7).
+ * Serial: each CLI call is a subprocess that takes the PGLite lock, and the
+ * rotation mint opens the brain through GBRAIN_HOME.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+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 { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine, executeRawJsonb } from '../src/core/sql-query.ts';
+import { mintHarnessToken } from '../src/core/bootstrap/harness.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { grantFromTokenRow } from '../src/core/grants/model.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { withEnv } from './helpers/with-env.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(); }
+}
+
+const tokenRow = (name: string) => withBrain(async engine =>
+ (await engine.executeRaw<Record<string, unknown>>('SELECT * FROM access_tokens WHERE name = $1 AND revoked_at IS NULL', [name]))[0]);
+const clientRow = (id: string) => withBrain(async engine =>
+ (await engine.executeRaw<Record<string, unknown>>('SELECT scope, source_id, federated_read, allowed_operations, grant_revision FROM oauth_clients WHERE client_id = $1', [id]))[0]);
+
+async function legacyToken(name: string, permissions: Record<string, unknown>) {
+ await withBrain(engine => executeRawJsonb(engine, 'INSERT INTO access_tokens (name, token_hash, scopes, permissions) VALUES ($1, $2, $3::text[], $4::jsonb)',
+ [name, `hash-${name}`, '{read,write}'], [permissions]));
+}
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'gb-rescope-unified-'));
+ 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");
+ });
+}, 120_000);
+
+afterAll(() => { rmSync(root, { recursive: true, force: true }); });
+
+describe('tokens', () => {
+ test('auth create is born unified; rescope-token and permissions set-takes-holders are aliases of rescope --token', async () => {
+ expect((await cli('auth', 'create', 'tok-a', '--scopes', 'read,write')).exitCode).toBe(0);
+ expect((await cli('auth', 'create', 'tok-b', '--scopes', 'read,write')).exitCode).toBe(0);
+ for (const name of ['tok-a', 'tok-b']) {
+ expect(await tokenRow(name)).toMatchObject({ source_grant: 'default', takes_holders: ['world'], allowed_operations: null, grant_revision: 1, permissions: { takes_holders: ['world'] } });
+ }
+ const flags = ['--sources', 'other,default', '--operations', 'get_page,search', '--takes-holders', 'none'];
+ const unified = await cli('auth', 'rescope', '--token', 'tok-a', ...flags);
+ const alias = await cli('auth', 'rescope-token', 'tok-b', ...flags);
+ expect(unified.exitCode).toBe(0);
+ expect(alias.exitCode).toBe(0);
+ expect(unified.stdout.replaceAll('tok-a', 'X').replace(/\([0-9a-f-]{36}\)/, '')).toBe(alias.stdout.replaceAll('tok-b', 'X').replace(/\([0-9a-f-]{36}\)/, ''));
+ const pick = (r: Record<string, unknown>) => ({ source_grant: r.source_grant, source_id: r.source_id, federated_read: r.federated_read,
+ allowed_operations: r.allowed_operations, takes_holders: r.takes_holders, grant_revision: r.grant_revision, permissions: r.permissions });
+ expect(pick(await tokenRow('tok-a'))).toEqual(pick(await tokenRow('tok-b')));
+ expect(pick(await tokenRow('tok-a'))).toEqual({ source_grant: 'federated', source_id: 'other', federated_read: ['other', 'default'],
+ allowed_operations: ['get_page', 'search'], takes_holders: [], grant_revision: 2,
+ permissions: { source_id: ['other', 'default'], takes_holders: [], allowed_operations: ['get_page', 'search'] } });
+
+ expect((await cli('auth', 'permissions', 'tok-a', 'set-takes-holders', 'world,brain')).exitCode).toBe(0);
+ expect((await cli('auth', 'rescope', 'tok-b', '--takes-holders', 'world,brain')).exitCode).toBe(0);
+ expect(pick(await tokenRow('tok-a'))).toEqual(pick(await tokenRow('tok-b')));
+ expect((await tokenRow('tok-a')).takes_holders).toEqual(['world', 'brain']);
+ }, 180_000);
+
+ test('8. --if-version mismatch refuses with the current revision, as JSON on stdout under --json', async () => {
+ expect((await cli('auth', 'create', 'tok-cas')).exitCode).toBe(0);
+ const stale = await cli('auth', 'rescope', '--token', 'tok-cas', '--sources', 'other', '--if-version', '0', '--json');
+ expect(stale.exitCode).toBe(1);
+ const body = JSON.parse(stale.stdout) as { error: { code: string; message: string } };
+ expect(body.error.code).toBe('grant_conflict');
+ expect(body.error.message).toContain('grant revision 1');
+ expect(body.error.message).toContain('--if-version 1');
+ expect((await tokenRow('tok-cas')).source_grant).toBe('default');
+ expect((await cli('auth', 'rescope', '--token', 'tok-cas', '--sources', 'other', '--if-version', '1')).exitCode).toBe(0);
+ expect((await tokenRow('tok-cas')).grant_revision).toBe(2);
+ }, 120_000);
+
+ test('10. --migrate-legacy --dry-run lists without writing; the real run migrates', async () => {
+ await legacyToken('tok-old', { takes_holders: ['world'], source_id: 'other' });
+ const preview = await cli('auth', 'rescope', '--migrate-legacy', '--dry-run', '--json');
+ expect(preview.exitCode).toBe(0);
+ expect(JSON.parse(preview.stdout).migrated).toContainEqual(expect.objectContaining({ name: 'tok-old', grant: { sources: ['other'], takesHolders: ['world'], operations: 'unrestricted' } }));
+ expect((await tokenRow('tok-old')).source_grant).toBeNull();
+ const run = await cli('auth', 'rescope', '--migrate-legacy');
+ expect(run.exitCode).toBe(0);
+ expect(run.stdout).toContain('no effective grant changes');
+ expect(await tokenRow('tok-old')).toMatchObject({ source_grant: 'scalar', source_id: 'other', permissions: { takes_holders: ['world'], source_id: 'other' } });
+ }, 120_000);
+
+ test('7. rotation mints a unified token that keeps explicit empty lists', async () => {
+ const prior = await withBrain(async engine => {
+ const minted = await mintLegacyToken(engine, { name: 'bootstrap-harness', takesHolders: [], scopes: ['read', 'write'], sourceGrant: [], allowedOperations: [] });
+ expect((await engine.executeRaw<{ source_grant: string }>('SELECT source_grant FROM access_tokens WHERE id = $1::uuid', [minted.id]))[0].source_grant).toBe('none');
+ return minted;
+ });
+ const rotated = await withEnv({ GBRAIN_HOME: home, HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_SOURCE: undefined },
+ () => mintHarnessToken({ name: 'bootstrap-harness', scopes: ['read', 'write'], allowedOperations: ['get_page', 'search'],
+ carry: { fromId: prior.id, explicitSource: false, policyAdded: [] } }));
+ const row = await withBrain(async engine => (await engine.executeRaw<Record<string, unknown>>('SELECT * FROM access_tokens WHERE id = $1::uuid', [rotated.id]))[0]);
+ expect(row).toMatchObject({ source_grant: 'none', source_id: null, federated_read: [], takes_holders: [], allowed_operations: [], grant_revision: 1,
+ permissions: { source_id: [], takes_holders: [], allowed_operations: [] } });
+ expect(grantFromTokenRow(row)).toMatchObject({ shape: 'unified', drift: [], sources: { kind: 'none' }, takesHolders: [], allowedOperations: [] });
+ }, 120_000);
+});
+
+describe('9. OAuth clients', () => {
+ test('rescope --client and rescope-client write identical rows; --sources none refuses', async () => {
+ const [a, b] = await withBrain(async engine => {
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ return [await provider.registerClientManual('client-a-example', ['client_credentials'], 'read write'),
+ await provider.registerClientManual('client-b-example', ['client_credentials'], 'read write')];
+ });
+ const unified = await cli('auth', 'rescope', '--client', a.clientId, '--sources', 'other,default', '--operations', 'get_page,search');
+ const alias = await cli('auth', 'rescope-client', b.clientId, '--source', 'other', '--federated-read', 'other,default', '--allowed-operations', 'get_page,search');
+ expect(unified.exitCode).toBe(0);
+ expect(alias.exitCode).toBe(0);
+ expect(await clientRow(a.clientId)).toEqual(await clientRow(b.clientId));
+ expect(await clientRow(a.clientId)).toMatchObject({ source_id: 'other', federated_read: ['other', 'default'], allowed_operations: ['get_page', 'search'] });
+
+ const none = await cli('auth', 'rescope', '--client', a.clientId, '--sources', 'none', '--json');
+ expect(none.exitCode).toBe(1);
+ const body = JSON.parse(none.stdout) as { error: { reasons: string[]; message: string } };
+ expect(body.error.reasons).toEqual(['client_sources_none_unsupported']);
+ expect(body.error.message).toContain(`gbrain auth revoke-client ${a.clientId}`);
+ expect((await clientRow(a.clientId)).source_id).toBe('other');
+
+ const holders = await cli('auth', 'rescope', '--client', a.clientId, '--takes-holders', 'world');
+ expect(holders.exitCode).toBe(1);
+ expect(holders.stderr).toContain('--takes-holders applies to legacy tokens only');
+ }, 180_000);
+
+ test('a bare name that matches both a token and a client refuses as ambiguous', async () => {
+ const client = await withBrain(async engine => {
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ return provider.registerClientManual('shared-name-example', ['client_credentials'], 'read');
+ });
+ expect((await cli('auth', 'create', 'shared-name-example')).exitCode).toBe(0);
+ const out = await cli('auth', 'rescope', 'shared-name-example', '--operations', 'search', '--json');
+ expect(out.exitCode).toBe(1);
+ const body = JSON.parse(out.stdout) as { error: { reasons: string[]; message: string } };
+ expect(body.error.reasons).toEqual(['rescope_target_ambiguous']);
+ expect(body.error.message).toContain(`--client ${client.clientId}`);
+ expect((await cli('auth', 'rescope', '--token', 'shared-name-example', '--operations', 'search')).exitCode).toBe(0);
+ }, 180_000);
+});
diff --git a/test/e2e/access-token-grants.test.ts b/test/e2e/access-token-grants.test.ts
new file mode 100644
index 0000000000..8d912faab0
--- /dev/null
+++ b/test/e2e/access-token-grants.test.ts
@@ -0,0 +1,70 @@
+/**
+ * F3 on real Postgres: the unified token grant columns (migration
+ * f3_access_token_grants) bind text[] values through postgres.js with quoting
+ * intact, the `permissions` mirror stays a JSONB object (double-encode class),
+ * `--migrate-legacy` preserves every effective grant, and an older binary's
+ * JSONB edit fails closed on the OAuth-provider path. PGLite coverage:
+ * test/access-token-grants.test.ts and test/auth-rescope-unified.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 { migrateLegacyTokens, parseRescopeTokenArgs, rescopeLegacyToken } from '../../src/core/grants/legacy-token.ts';
+import { grantFromTokenRow } from '../../src/core/grants/model.ts';
+import { GBrainOAuthProvider } from '../../src/core/oauth-provider.ts';
+import { executeRawJsonb, sqlQueryForEngine } from '../../src/core/sql-query.ts';
+import { NO_SOURCES } from '../../src/core/source-id.ts';
+import { generateToken, hashToken } from '../../src/core/utils.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-f3','other-f3') ON CONFLICT DO NOTHING");
+});
+afterAll(async () => { if (hasDatabase()) await teardownDB(); });
+
+const provider = () => { const engine = getEngine(); return new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) }); };
+const row = async (id: string) => (await getEngine().executeRaw<Record<string, unknown>>(
+ "SELECT *, jsonb_typeof(permissions) AS kind FROM access_tokens WHERE id = $1::uuid", [id]))[0];
+
+d('F3 token grant columns on Postgres', () => {
+ test('mint and rescope write text[] columns with quoting intact and an object mirror', async () => {
+ const engine = getEngine();
+ const name = `f3-e2e-${randomUUID().slice(0, 8)}`;
+ const minted = await mintLegacyToken(engine, { name, takesHolders: ['world'], scopes: ['read', 'write'], sourceGrant: ['default', 'other-f3'], allowedOperations: ['get_page'] });
+ expect(await row(minted.id)).toMatchObject({ kind: 'object', source_grant: 'federated', source_id: 'default', federated_read: ['default', 'other-f3'], allowed_operations: ['get_page'], grant_revision: 1 });
+ const holders = ['world', 'a,b', 'q"x', 'back\\slash', '{brace}'];
+ const result = await rescopeLegacyToken(engine, parseRescopeTokenArgs([name, '--takes-holders', holders.join(','), '--if-version', '1']));
+ expect(result.revision).toEqual({ before: 1, after: 2 });
+ const after = await row(minted.id);
+ expect(after.takes_holders).toEqual(['world', 'a', 'b', 'q"x', 'back\\slash', '{brace}']);
+ expect(after.permissions).toEqual({ takes_holders: ['world', 'a', 'b', 'q"x', 'back\\slash', '{brace}'], source_id: ['default', 'other-f3'], allowed_operations: ['get_page'] });
+ expect(grantFromTokenRow(after).drift).toEqual([]);
+ });
+
+ test('--migrate-legacy changes no AuthInfo; an older binary JSONB edit then fails closed', async () => {
+ const engine = getEngine();
+ const name = `f3-e2e-legacy-${randomUUID().slice(0, 8)}`;
+ const token = generateToken('gbrain_');
+ const [inserted] = await executeRawJsonb<{ id: string }>(engine, 'INSERT INTO access_tokens (name, token_hash, scopes, permissions) VALUES ($1, $2, $3::text[], $4::jsonb) RETURNING id',
+ [name, hashToken(token), '{read,write}'], [{ takes_holders: ['world', 'brain'], source_id: 'other-f3', allowed_operations: ['search', 'search'], note: 'kept' }]);
+ const before = await provider().verifyAccessToken(token);
+ const preview = await migrateLegacyTokens(engine, { dryRun: true });
+ expect(preview.migrated.map(m => m.id)).toContain(inserted.id);
+ expect((await row(inserted.id)).source_grant).toBeNull();
+ await migrateLegacyTokens(engine, { dryRun: false });
+ const migrated = await row(inserted.id);
+ expect(migrated).toMatchObject({ kind: 'object', source_grant: 'scalar', source_id: 'other-f3', federated_read: null, allowed_operations: ['search'], takes_holders: ['world', 'brain'] });
+ expect(migrated.permissions).toEqual({ takes_holders: ['world', 'brain'], source_id: 'other-f3', allowed_operations: ['search'], note: 'kept' });
+ const strip = (a: unknown) => ({ ...(a as Record<string, unknown>), expiresAt: 0 });
+ expect(strip(await provider().verifyAccessToken(token))).toEqual(strip(before));
+
+ await engine.executeRaw(`UPDATE access_tokens SET permissions = jsonb_set(permissions, '{source_id}', '"default"') WHERE id = $1::uuid`, [inserted.id]);
+ expect(await provider().verifyAccessToken(token)).toMatchObject({ sourceId: NO_SOURCES, allowedSources: [] });
+ await rescopeLegacyToken(engine, parseRescopeTokenArgs([name, '--adopt-columns']));
+ expect(await provider().verifyAccessToken(token)).toMatchObject({ sourceId: 'other-f3', hasSourceGrant: true });
+ });
+});