Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
GBRA-218 A1 identity: tests (members, binding, --as) and access/as refusals
garrytand8f8b0854d98
diff --git a/src/commands/access.ts b/src/commands/access.tsindex 4b6151545a..1a2046417e 100644--- a/src/commands/access.ts+++ b/src/commands/access.ts@@ -17,7 +17,7 @@ import { sqlQueryForEngine } from '../core/sql-query.ts';import { grantFromClient, type PrincipalGrant } from '../core/grants/model.ts';import { readClientGrant } from '../core/grants/service.ts';import { resolveTokenGrant } from '../core/grants/legacy-token.ts';-import { isPrivatePage } from '../core/search/private-visibility.ts';+import { isPrivacyPrivatePage } from '../core/search/private-visibility.ts';import { identityFor, normalizePrincipal, normalizeReaders, readersAllow } from '../core/access/principals.ts';import {addGroup, addMember, assertAccessId, disableMember, enableMember, getMember, legacyTokenByName, listGroups, listMembers,@@ -93,7 +93,7 @@ export async function whoCanRead(engine: BrainEngine, slug: string, sourceId?: sreturn rows.map(row => {const fm = typeof row.frontmatter === 'string' ? JSON.parse(row.frontmatter) : row.frontmatter;const readers = normalizeReaders(fm);- const priv = isPrivatePage({ type: row.type, frontmatter: fm });+ const priv = isPrivacyPrivatePage({ type: row.type, frontmatter: fm });const allowed = readers === null ? 'every_source_reader' as const : members.filter(m => readersAllow(fm, identityFor(m.id, m.groups))).map(m => m.id);const notes = [readers === null ? 'No readable_by: every caller entitled to the source reads it.'@@ -242,6 +242,9 @@ export async function runAccess(engine: BrainEngine, args: string[]): Promise<voconst json = args.includes('--json');const [cmd, ...rest] = args;try {+ if (cmd !== 'check' && rest.some(a => a === '--as' || a.startsWith('--as='))) {+ throw usageError(`--as is not an option of gbrain access ${cmd}.`, 'gbrain access check --token <name> --as a,b evaluates an audience; operations take --as <member> to preview a member view.');+ }switch (cmd) {case 'member': return await memberCmd(engine, rest[0], rest.slice(1), json);case 'group': return await groupCmd(engine, rest[0], rest.slice(1), json);diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex be02e466e2..971728b8a4 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -466,7 +466,7 @@ export function isPrivatePage(page: { type?: string | null; frontmatter?: unknow}/** isPrivatePage without the member-access rule: visibility, aliases and pinned questions only. */-function isPrivacyPrivatePage(page: { type?: string | null; frontmatter?: unknown }): boolean {+export function isPrivacyPrivatePage(page: { type?: string | null; frontmatter?: unknown }): boolean {const frontmatter = typeof page.frontmatter === 'object' && page.frontmatter !== null? page.frontmatter as Record<string, unknown> : {};if (frontmatter.pinned_question != null) return true;diff --git a/test/access-as.serial.test.ts b/test/access-as.serial.test.tsnew file mode 100644index 0000000000..fccbc1237d--- /dev/null+++ b/test/access-as.serial.test.ts@@ -0,0 +1,115 @@+/**+ * GBRA-218 A1 identity: local `--as <member>` as real CLI subprocesses against+ * a repo-less PGLite brain on disk (no git checkout).+ *+ * 1. Protects: `--as` previews an operation's reads as that member (pages+ * naming readers appear only for a listed member); the plain local CLI is+ * unchanged; an unknown, disabled or ill-formed `--as` is refused with+ * access_member_invalid before any work; a command that would ignore+ * `--as` refuses it; writes under `--as` keep local write trust.+ * 2. Fails when: `--as` is silently ignored (shows everything), an unknown+ * member reads as unbound, or `--as` turns local writes into remote ones.+ * 3. Existing coverage: none for the CLI seam (test/access-as.test.ts holds+ * the in-process composition and upload confinement).+ * 4. Real seams: src/cli.ts global flag parsing, runSharedOperation, makeContext.+ */+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 { disposePersistenceConsumer } from '../src/core/persistence/service.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[], stdin?: string) {+ const proc = Bun.spawn(['bun', 'run', CLI, ...args], { cwd: root, env: env(), stdin: stdin === undefined ? 'ignore' : new Blob([stdin]), 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(); }+}++/** A repo-less PGLite brain on disk (no git checkout), the default keyless install. */+async function makeBrain(prefix: string, seed: (engine: BrainEngine) => Promise<void>): Promise<void> {+ root = mkdtempSync(join(tmpdir(), prefix));+ 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 seed(engine); });+}++const ALICE = { slug: 'notes/alice-plan', canary: 'canaryasalice' };++beforeAll(async () => {+ await makeBrain('gb-access-as-', async engine => {+ await engine.putPage(ALICE.slug, { type: 'note', title: 'Alice plan', compiled_truth: `Planning notes ${ALICE.canary}.`, timeline: '', frontmatter: { readable_by: ['alice-example'] } }, { sourceId: 'default' });+ await engine.putPage('notes/open-plan', { type: 'note', title: 'Open plan', compiled_truth: 'Open notes canaryasopen.', timeline: '', frontmatter: {} }, { sourceId: 'default' });+ for (const id of ['alice-example', 'bob-example', 'carol-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);+ await engine.executeRaw("UPDATE access_members SET disabled_at = now() WHERE id = 'carol-example'");+ });+}, 120_000);++afterAll(() => { rmSync(root, { recursive: true, force: true }); });++describe('local --as <member> (repo-less PGLite)', () => {+ test('the plain local CLI reads the restricted page; --as narrows to the member view', async () => {+ const plain = await cli(['get', ALICE.slug]);+ expect(plain.exitCode).toBe(0);+ expect(plain.stdout).toContain(ALICE.canary);+ const asAlice = await cli(['get', ALICE.slug, '--as', 'alice-example']);+ expect(asAlice.exitCode).toBe(0);+ expect(asAlice.stdout).toContain(ALICE.canary);+ const asBob = await cli(['--as', 'bob-example', 'get', ALICE.slug]);+ expect(asBob.stdout + asBob.stderr).not.toContain(ALICE.canary);+ expect(asBob.exitCode).not.toBe(0);+ const listBob = await cli(['list', '--as', 'bob-example', '--json']);+ expect(listBob.exitCode).toBe(0);+ expect(listBob.stdout).toContain('notes/open-plan');+ expect(listBob.stdout).not.toContain(ALICE.slug);+ }, 180_000);++ test('an unknown, disabled or ill-formed --as is refused before any work', async () => {+ for (const [who, reason] of [['nobody-example', 'unknown'], ['carol-example', 'disabled'], ['Not_Valid!', 'ill_formed']] as const) {+ const r = await cli(['get', 'notes/open-plan', '--as', who, '--json']);+ expect({ who, exit: r.exitCode === 0 }).toEqual({ who, exit: false });+ expect(r.stdout).not.toContain('canaryasopen');+ expect(JSON.parse(r.stdout)).toMatchObject({ code: 'access_member_invalid', reason });+ }+ const missing = await cli(['get', 'notes/open-plan', '--as']);+ expect(missing.exitCode).not.toBe(0);+ }, 180_000);++ test('a command that would ignore --as refuses it', async () => {+ const r = await cli(['access', 'member', 'list', '--as', 'alice-example']);+ expect(r.exitCode).not.toBe(0);+ const doctor = await cli(['doctor', '--as', 'alice-example']);+ expect(doctor.exitCode).not.toBe(0);+ expect(doctor.stderr).toContain('--as previews member reads for operation commands only');+ }, 120_000);++ test('whoami --as reports the member; writes under --as keep local trust', async () => {+ const who = await cli(['whoami', '--as', 'bob-example', '--json']);+ expect(who.exitCode).toBe(0);+ expect(JSON.parse(who.stdout)).toMatchObject({ transport: 'local', access: { member: 'bob-example', bound_by: 'as' } });+ const put = await cli(['put', 'notes/bob-draft', '--as', 'bob-example'], '---\ntype: note\ntitle: Bob draft\n---\n# Bob draft\n\nDraft canaryasbob.\n');+ expect({ exit: put.exitCode, err: put.exitCode === 0 ? '' : put.stderr }).toEqual({ exit: 0, err: '' });+ const read = await cli(['get', 'notes/bob-draft']);+ expect(read.stdout).toContain('canaryasbob');+ }, 180_000);+});diff --git a/test/access-as.test.ts b/test/access-as.test.tsnew file mode 100644index 0000000000..0e1a423d28--- /dev/null+++ b/test/access-as.test.ts@@ -0,0 +1,125 @@+/**+ * GBRA-218 A1 identity: the caller-access composition a local `--as <member>`+ * runs under (src/cli/main.ts runSharedOperation), in process on a repo-less+ * brain (in-memory PGLite; Postgres too when DATABASE_URL is set).+ *+ * 1. Protects: a trusted local read under+ * withCallerAccess({ identity, applyRemoteReadPolicy: true, hidePrivate: true })+ * sees exactly the member view (readers applied, visibility: private+ * hidden, escape hatches relax nothing), while ctx.remote stays false, so+ * upload confinement keeps its local meaning.+ * 2. Fails when: --as reads past readers, a hatch widens an --as preview,+ * readers relax visibility: private, or --as flips upload confinement.+ * 3. Existing coverage: test/access-as.serial.test.ts (the CLI seam).+ * 4. Real seams: dispatchToolCall with remote:false, the file_upload handler.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { writeFileSync, mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { withCallerAccess, __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { addMember, memberIdentity } from '../src/core/access/members.ts';+import { operations } from '../src/core/operations.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';++const DIMS = 1536;+const SRC = 'source-a';+const PAGES = {+ alice: { slug: 'notes/alice-plan', canary: 'canaryinasalice', fm: 'readable_by: [alice-example]' },+ quiet: { slug: 'notes/quiet-plan', canary: 'canaryinasquiet', fm: 'readable_by: [alice-example]\nvisibility: private' },+ open: { slug: 'notes/open-plan', canary: 'canaryinasopen', fm: '' },+} as const;++for (const kind of testBackends()) {+ describe(`local --as composition (${kind}, repo-less)`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;++ async function asMember<T>(member: string | null, fn: () => Promise<T>): Promise<T> {+ if (!member) return fn();+ const { identity } = await memberIdentity(engine, member);+ return withCallerAccess({ identity, applyRemoteReadPolicy: true, hidePrivate: true, privateReadableSources: [] }, fn);+ }+ async function seen(member: string | null): Promise<string[]> {+ const out: string[] = [];+ for (const [key, page] of Object.entries(PAGES)) {+ const got = await asMember(member, () => dispatchToolCall(engine, 'get_page', { slug: page.slug }, { remote: false, sourceId: SRC }));+ const found = await asMember(member, () => dispatchToolCall(engine, 'search', { query: page.canary, match: 'keyword', fields: 'full' }, { remote: false, sourceId: SRC }));+ if ([got, found].some(r => r.content.map(c => c.text).join('\n').includes(page.canary))) out.push(key);+ }+ return out.sort();+ }++ beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => new Array<number>(DIMS).fill(0).map((_, i) => (i === 0 ? 1 : 0))) })) as never);+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }+ __resetPrivateVisibilityCacheForTests();+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);+ for (const p of Object.values(PAGES)) {+ await importFromContent(engine, p.slug, `---\ntype: note\ntitle: ${p.slug}\n${p.fm}\n---\n# Plan\n\nPlanning notes ${p.canary}.`, { sourceId: SRC });+ }+ await addMember(engine, 'alice-example');+ await addMember(engine, 'bob-example');+ }, 120_000);++ afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await close?.();+ }, 60_000);++ test('the plain local CLI reads everything; --as alice sees her page; --as bob sees only the open page', async () => {+ expect(await seen(null)).toEqual(['alice', 'open', 'quiet']);+ expect(await seen('alice-example')).toEqual(['alice', 'open']);+ expect(await seen('bob-example')).toEqual(['open']);+ }, 60_000);++ test('escape hatches relax nothing under --as, and readers never relax visibility: private', async () => {+ await withEnv({ GBRAIN_REMOTE_PRIVATE_PAGES: '1' }, async () => {+ expect(await seen('bob-example')).toEqual(['open']);+ expect(await seen('alice-example')).toEqual(['alice', 'open']);+ });+ await engine.setConfig('search.remote_private_pages', 'visible');+ __resetPrivateVisibilityCacheForTests();+ try {+ expect(await seen('bob-example')).toEqual(['open']);+ } finally {+ await engine.setConfig('search.remote_private_pages', 'hidden');+ __resetPrivateVisibilityCacheForTests();+ }+ }, 60_000);++ test('--as keeps ctx.remote false: upload confinement keeps its local meaning', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gb-as-upload-'));+ const file = join(dir, 'outside-cwd.txt');+ writeFileSync(file, 'upload probe');+ const upload = operations.find(o => o.name === 'file_upload')!;+ const ctx = (remote: boolean, identity?: string[]) => ({+ engine, config: {}, remote, dryRun: false, sourceId: SRC, logger: { info() {}, warn() {}, error() {} },+ ...(identity ? { accessIdentity: identity, applyRemoteReadPolicy: true } : {}),+ }) as unknown as OperationContext;+ const failure = async (fn: () => Promise<unknown>) => { try { await fn(); return 'ok'; } catch (e) { return (e as { code?: string }).code ?? (e as Error).message; } };+ try {+ const { identity } = await memberIdentity(engine, 'bob-example');+ const asBob = await asMember('bob-example', () => failure(() => upload.handler(ctx(false, identity), { path: file })));+ const local = await failure(() => upload.handler(ctx(false), { path: file }));+ const remote = await failure(() => upload.handler(ctx(true), { path: file }));+ expect(asBob).toBe(local);+ expect(asBob).toBe('storage_error');+ expect(remote).not.toBe('storage_error');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+ });+}diff --git a/test/access-binding.serial.test.ts b/test/access-binding.serial.test.tsnew file mode 100644index 0000000000..202d0b5961--- /dev/null+++ b/test/access-binding.serial.test.ts@@ -0,0 +1,131 @@+/**+ * GBRA-218 A1 identity: the operator CLI as real subprocesses against a+ * repo-less PGLite brain on disk (no git checkout).+ *+ * 1. Protects: `gbrain auth create|rescope|register-client --member` binds a+ * credential to an enabled member and refuses an unknown one before any+ * credential is minted or changed; `--member none` unbinds; `--dry-run`+ * writes no binding; `--may-act-for` is stored normalized; `gbrain access+ * member rm` previews without `--yes` and a removed id is refused on re-add+ * with access_member_id_retired (the contract envelope under --json).+ * 2. Fails when: a typo mints an unbound token, a rescope preview writes, a+ * removed id is reused, or the refusal loses its code.+ * 3. Existing coverage: test/access-members.test.ts (the service in process).+ * 4. Real seams: src/cli.ts subprocesses, the PGLite file lock, the generated+ * flag registry.+ */+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 { disposePersistenceConsumer } from '../src/core/persistence/service.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[], stdin?: string) {+ const proc = Bun.spawn(['bun', 'run', CLI, ...args], { cwd: root, env: env(), stdin: stdin === undefined ? 'ignore' : new Blob([stdin]), 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(); }+}++/** A repo-less PGLite brain on disk (no git checkout), the default keyless install. */+async function makeBrain(prefix: string, seed: (engine: BrainEngine) => Promise<void>): Promise<void> {+ root = mkdtempSync(join(tmpdir(), prefix));+ 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 seed(engine); });+}++async function binding(table: 'access_tokens' | 'oauth_clients', key: string, value: string) {+ return withBrain(async engine => (await engine.executeRaw<{ member_id: string | null; may_act_for: string[] | null }>(+ `SELECT member_id, may_act_for FROM ${table} WHERE ${key} = $1`, [value]))[0]);+}++beforeAll(async () => {+ await makeBrain('gb-access-binding-', async engine => {+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('source-a', 'source-a') ON CONFLICT DO NOTHING");+ });+}, 120_000);++afterAll(() => { rmSync(root, { recursive: true, force: true }); });++describe('access and auth binding CLI (repo-less PGLite)', () => {+ test('member add, then auth create --member binds the new token', async () => {+ const added = await cli(['access', 'member', 'add', 'alice-example', '--name', 'Alice Example', '--groups', 'team-a']);+ expect(added.exitCode).toBe(0);+ expect(added.stdout).toContain('Member added: alice-example');+ expect((await cli(['access', 'member', 'add', 'bob-example'])).exitCode).toBe(0);+ const created = await cli(['auth', 'create', 'alice-laptop', '--scopes', 'read', '--member', 'alice-example']);+ expect(created.exitCode).toBe(0);+ expect(created.stdout).toContain('Member: alice-example');+ expect(await binding('access_tokens', 'name', 'alice-laptop')).toEqual({ member_id: 'alice-example', may_act_for: null });+ }, 120_000);++ test('an unknown --member is refused before any token is minted', async () => {+ const refused = await cli(['auth', 'create', 'typo-laptop', '--scopes', 'read', '--member', 'alise-example', '--json']);+ expect(refused.exitCode).not.toBe(0);+ expect(JSON.parse(refused.stdout)).toMatchObject({ code: 'access_member_invalid', reason: 'unknown' });+ expect(await binding('access_tokens', 'name', 'typo-laptop')).toBeUndefined();+ }, 120_000);++ test('auth rescope --member rebinds, --dry-run writes nothing, --member none unbinds, --may-act-for is stored normalized', async () => {+ expect((await cli(['auth', 'create', 'shared-bot', '--scopes', 'read'])).exitCode).toBe(0);+ const preview = await cli(['auth', 'rescope', '--token', 'shared-bot', '--member', 'bob-example', '--dry-run']);+ expect(preview.exitCode).toBe(0);+ expect(preview.stdout).toContain('preview, not written');+ expect(await binding('access_tokens', 'name', 'shared-bot')).toEqual({ member_id: null, may_act_for: null });+ const bound = await cli(['auth', 'rescope', '--token', 'shared-bot', '--member', 'bob-example', '--may-act-for', 'Alice-Example,group:team-a', '--json']);+ expect(bound.exitCode).toBe(0);+ expect(JSON.parse(bound.stdout).binding).toEqual({ member: 'bob-example', may_act_for: ['group:team-a', 'member:alice-example'], changed: true });+ expect(await binding('access_tokens', 'name', 'shared-bot')).toEqual({ member_id: 'bob-example', may_act_for: ['group:team-a', 'member:alice-example'] });+ expect((await cli(['auth', 'rescope', '--token', 'shared-bot', '--member', 'none', '--may-act-for', 'none'])).exitCode).toBe(0);+ expect(await binding('access_tokens', 'name', 'shared-bot')).toEqual({ member_id: null, may_act_for: null });+ const bad = await cli(['auth', 'rescope', '--token', 'shared-bot', '--member', 'Not Valid!']);+ expect(bad.exitCode).not.toBe(0);+ expect(bad.stderr).toContain('access_member_invalid');+ }, 180_000);++ test('auth register-client --member binds the new OAuth client', async () => {+ const registered = await cli(['auth', 'register-client', 'client-a-example', '--scopes', 'read', '--member', 'alice-example']);+ expect(registered.exitCode).toBe(0);+ const clientId = (registered.stdout.match(/gbrain_cl_[A-Za-z0-9_-]+/) ?? [''])[0];+ expect(clientId).not.toBe('');+ expect(await binding('oauth_clients', 'client_id', clientId)).toEqual({ member_id: 'alice-example', may_act_for: null });+ const rebound = await cli(['auth', 'rescope', '--client', clientId, '--member', 'bob-example']);+ expect(rebound.exitCode).toBe(0);+ expect(await binding('oauth_clients', 'client_id', clientId)).toEqual({ member_id: 'bob-example', may_act_for: null });+ }, 120_000);++ test('access check reports the binding; member rm previews, --yes removes, and the id is never reused', async () => {+ const check = await cli(['access', 'check', '--token', 'alice-laptop', '--json']);+ expect(check.exitCode).toBe(0);+ expect(JSON.parse(check.stdout)).toMatchObject({ verdict: 'reads_as_member', identity: ['group:team-a', 'member:alice-example'] });+ const preview = await cli(['access', 'member', 'rm', 'alice-example', '--json']);+ expect(preview.exitCode).toBe(0);+ expect(JSON.parse(preview.stdout)).toMatchObject({ applied: false, member: { status: 'enabled' }, bound_credentials: [expect.objectContaining({ kind: 'token', name: 'alice-laptop' })] });+ expect((await cli(['access', 'member', 'rm', 'alice-example', '--yes'])).exitCode).toBe(0);+ expect(JSON.parse((await cli(['access', 'check', '--token', 'alice-laptop', '--json'])).stdout)).toMatchObject({ verdict: 'refused' });+ const readd = await cli(['access', 'member', 'add', 'alice-example', '--json']);+ expect(readd.exitCode).not.toBe(0);+ expect(JSON.parse(readd.stdout)).toMatchObject({ code: 'access_member_id_retired', docs: expect.stringContaining('docs/guides/write-refusals.md#access_member_id_retired') });+ }, 180_000);+});diff --git a/test/access-binding.test.ts b/test/access-binding.test.tsnew file mode 100644index 0000000000..272a401eaa--- /dev/null+++ b/test/access-binding.test.ts@@ -0,0 +1,192 @@+/**+ * GBRA-218 A1 identity: credential bindings at verification, in dispatch and+ * on a local stdio server, on a repo-less brain (in-memory PGLite; Postgres+ * too when DATABASE_URL is set).+ *+ * 1. Protects: a token or OAuth client bound to a disabled, removed or missing+ * member is refused by the verifier (access_member_disabled) on both the+ * OAuth provider and the legacy bearer transport; the verifier carries the+ * live member on AuthInfo so dispatch needs no lookup; an unbound credential+ * keeps an empty identity; a stdio server reads as config mcp.stdio_member+ * and, unbound, sees no page that names readers; whoami and grant_diagnosis+ * report member, groups and may_act_for.+ * 2. Fails when: a disabled member's credential still verifies (or verifies+ * as unbound and keeps reading open pages), dispatch trusts a stale+ * identity source, an unbound stdio server reads a restricted page, or a+ * stdio server bound to a disabled member keeps reading.+ * 3. Existing coverage: test/member-read-access.test.ts checks reads with the+ * principal lookup only.+ * 4. Real seams: GBrainOAuthProvider.verifyAccessToken, startHttpTransport's+ * bearer verifier over a real socket, dispatchToolCall with transport stdio.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { mintLegacyToken } from '../src/core/token-mint.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 { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { memberIdentityFor, STDIO_MEMBER_KEY } from '../src/core/access/caller.ts';+import { addGroup, addMember, bindCredential, disableMember, enableMember, removeMember } from '../src/core/access/members.ts';+import type { AuthInfo } from '../src/core/ops/contract.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const DIMS = 1536;+const SRC = 'source-a';+const ALICE_SLUG = 'notes/alice-plan';+const CANARY = 'canarybindalice';++for (const kind of testBackends()) {+ describe(`access binding (${kind}, repo-less)`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const tokens: Record<string, { id: string; token: string }> = {};+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ const verify = async (token: string) => await provider().verifyAccessToken(token) as unknown as AuthInfo;+ const verifyError = async (token: string) => { try { await verify(token); return 'verified'; } catch (e) { return (e as Error).message; } };++ async function stdioGet(slug: string): Promise<string> {+ const out = await dispatchToolCall(engine, 'get_page', { slug }, { remote: true, transport: 'stdio', sourceId: SRC, takesHoldersAllowList: ['world'] });+ return out.content.map(c => c.text).join('\n');+ }++ beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => new Array<number>(DIMS).fill(0).map((_, i) => (i === 0 ? 1 : 0))) })) as never);+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }+ __resetPrivateVisibilityCacheForTests();+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);+ await importFromContent(engine, ALICE_SLUG, `---\ntype: note\ntitle: Alice plan\nreadable_by: [alice-example]\n---\n# Alice plan\n\nPlanning notes ${CANARY}.`, { sourceId: SRC });+ await addMember(engine, 'alice-example', { groups: ['team-a'] });+ await addMember(engine, 'bob-example');+ for (const name of ['alice', 'bob', 'unbound', 'ghost']) {+ tokens[name] = await mintLegacyToken(engine, { name, scopes: ['read'], takesHolders: ['world'], sourceGrant: [SRC] });+ }+ await bindCredential(engine, { kind: 'token', id: tokens.alice!.id }, { member: 'alice-example', mayActFor: ['member:bob-example'] });+ await bindCredential(engine, { kind: 'token', id: tokens.bob!.id }, { member: 'bob-example' });+ await engine.executeRaw("UPDATE access_tokens SET member_id = 'nobody-example' WHERE id = $1::uuid", [tokens.ghost!.id]);+ }, 120_000);++ afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await close?.();+ }, 60_000);++ test('the legacy-token verifier joins the live member and carries it on AuthInfo; an unbound token carries null', async () => {+ const alice = await verify(tokens.alice!.token);+ expect(alice.member).toEqual({ id: 'alice-example', groups: ['team-a'] });+ expect(alice.mayActFor).toEqual(['member:bob-example']);+ expect((await verify(tokens.unbound!.token)).member).toBeNull();+ });++ test('a token bound to a disabled, removed or missing member is refused at verification', async () => {+ expect(await verifyError(tokens.ghost!.token)).toContain('access_member_disabled');+ await disableMember(engine, 'bob-example');+ expect(await verifyError(tokens.bob!.token)).toContain('access_member_disabled');+ await enableMember(engine, 'bob-example');+ expect((await verify(tokens.bob!.token)).member).toEqual({ id: 'bob-example', groups: [] });+ await addMember(engine, 'frank-example');+ const frank = await mintLegacyToken(engine, { name: 'frank', scopes: ['read'], takesHolders: ['world'], sourceGrant: [SRC] });+ await bindCredential(engine, { kind: 'token', id: frank.id }, { member: 'frank-example' });+ await removeMember(engine, 'frank-example');+ expect(await verifyError(frank.token)).toContain('access_member_disabled');+ });++ test('an OAuth client bound to a member verifies as that member and is refused once the member is disabled', async () => {+ const registered = await provider().registerClientManual('client-a-example', ['client_credentials'], 'read', [], SRC);+ await bindCredential(engine, { kind: 'client', id: registered.clientId }, { member: 'alice-example' });+ const issued = await provider().exchangeClientCredentials(registered.clientId, registered.clientSecret!);+ expect((await verify(issued.access_token)).member).toEqual({ id: 'alice-example', groups: ['team-a'] });+ await disableMember(engine, 'alice-example');+ try {+ expect(await verifyError(issued.access_token)).toContain('access_member_disabled');+ } finally {+ await enableMember(engine, 'alice-example');+ }+ await bindCredential(engine, { kind: 'client', id: registered.clientId }, { member: null });+ expect((await verify(issued.access_token)).member).toBeNull();+ });++ test('the legacy bearer transport refuses a token bound to a disabled member with access_member_disabled', async () => {+ 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 callAs = (token: string) => 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: 'get_page', arguments: { slug: ALICE_SLUG } } }),+ });+ const ok = await callAs(tokens.alice!.token);+ expect(ok.status).toBe(200);+ expect(await ok.text()).toContain(CANARY);+ await disableMember(engine, 'alice-example');+ try {+ const refused = await callAs(tokens.alice!.token);+ expect(refused.status).toBe(401);+ expect(await refused.json()).toMatchObject({ error: 'invalid_token', code: 'access_member_disabled' });+ } finally {+ await enableMember(engine, 'alice-example');+ }+ } finally {+ server.stop(true);+ }+ }, 60_000);++ test('dispatch reads the identity the verifier joined without a query; only an AuthInfo no verifier built is looked up', async () => {+ const noQueries = { executeRaw: async () => { throw new Error('dispatch must not query when the verifier joined the member'); } } as unknown as BrainEngine;+ const joined = { token: '', clientId: 'x', scopes: ['read'], principal: { kind: 'legacy_token' as const, id: tokens.alice!.id } };+ expect(await memberIdentityFor(noQueries, { ...joined, member: { id: 'alice-example', groups: ['team-a'] } })).toEqual(['group:team-a', 'member:alice-example']);+ expect(await memberIdentityFor(noQueries, { ...joined, member: null })).toEqual([]);+ expect(await memberIdentityFor(engine, joined)).toEqual(['group:team-a', 'member:alice-example']);+ expect(await memberIdentityFor(noQueries, joined)).toEqual([]);+ });++ test('stdio: unbound sees no restricted page; mcp.stdio_member binds it; a disabled bound member sees none again', async () => {+ expect(await stdioGet(ALICE_SLUG)).not.toContain(CANARY);+ await engine.setConfig(STDIO_MEMBER_KEY, 'bob-example');+ expect(await stdioGet(ALICE_SLUG)).not.toContain(CANARY);+ await engine.setConfig(STDIO_MEMBER_KEY, 'alice-example');+ expect(await stdioGet(ALICE_SLUG)).toContain(CANARY);+ const whoami = JSON.parse((await dispatchToolCall(engine, 'whoami', {}, { remote: true, transport: 'stdio', sourceId: SRC })).content[0]!.text);+ expect(whoami.access).toMatchObject({ member: 'alice-example', groups: ['team-a'], bound_by: 'stdio_config' });+ await disableMember(engine, 'alice-example');+ try {+ expect(await stdioGet(ALICE_SLUG)).not.toContain(CANARY);+ const after = JSON.parse((await dispatchToolCall(engine, 'whoami', {}, { remote: true, transport: 'stdio', sourceId: SRC })).content[0]!.text);+ expect(after.access).toMatchObject({ member: null, bound_by: 'none' });+ expect(after.access.note).toContain('not an enabled member');+ } finally {+ await enableMember(engine, 'alice-example');+ await engine.setConfig(STDIO_MEMBER_KEY, '');+ }+ expect(await stdioGet(ALICE_SLUG)).not.toContain(CANARY);+ });++ test('whoami and grant_diagnosis over a legacy token report member, groups and may_act_for', async () => {+ const auth = await verify(tokens.alice!.token);+ const out = await dispatchToolCall(engine, 'whoami', {}, { remote: true, transport: 'http', auth, sourceId: SRC });+ const body = JSON.parse(out.content[0]!.text);+ expect(body.access).toEqual({ member: 'alice-example', groups: ['team-a'], may_act_for: ['member:bob-example'], bound_by: 'credential' });+ expect(body.grant_diagnosis).toMatchObject({ member: 'alice-example', groups: ['team-a'], may_act_for: ['member:bob-example'] });+ const unbound = JSON.parse((await dispatchToolCall(engine, 'whoami', {}, { remote: true, transport: 'http', auth: await verify(tokens.unbound!.token), sourceId: SRC })).content[0]!.text);+ expect(unbound.access).toMatchObject({ member: null, groups: [], bound_by: 'none' });+ expect(unbound.grant_diagnosis).toMatchObject({ member: null, may_act_for: null });+ const local = JSON.parse((await dispatchToolCall(engine, 'whoami', {}, { remote: false, sourceId: SRC })).content[0]!.text);+ expect(local.access).toMatchObject({ member: null, bound_by: 'none' });+ });++ test('a group binding follows membership on the next request', async () => {+ await addGroup(engine, 'team-c', ['bob-example']);+ expect((await verify(tokens.bob!.token)).member).toEqual({ id: 'bob-example', groups: ['team-c'] });+ });+ });+}diff --git a/test/access-members.test.ts b/test/access-members.test.tsnew file mode 100644index 0000000000..5c771175b6--- /dev/null+++ b/test/access-members.test.ts@@ -0,0 +1,179 @@+/**+ * GBRA-218 A1 identity: the members and groups service and the read-only+ * `gbrain access` checks, on a repo-less brain (in-memory PGLite, no git+ * checkout; Postgres too when DATABASE_URL is set).+ *+ * 1. Protects: member ids are never reused (rm tombstones, add and enable+ * refuse a removed id), rm is preview-first and names bound credentials and+ * pages, group membership drives who-can-read, and access check reports one+ * credential's own grant axes next to its member identity.+ * 2. Fails when: a removed id can be added or enabled again, a preview writes,+ * an ill-formed or unknown id is accepted, who-can-read admits a member the+ * readers do not name, or two credentials of one member report the same+ * grant when their grants differ.+ * 3. Existing coverage: test/member-read-access.test.ts (the read matrix, with+ * members inserted by SQL).+ * 4. Real seams: the members service over the real schema; tokens minted by+ * the token service; who-can-read reads live frontmatter.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import {+ addGroup, addMember, bindCredential, disableMember, enableMember, getMember, listGroups, listMembers, memberIdentity,+ parseMayActFor, previewRemoveGroup, previewRemoveMember, removeGroup, removeGroupMembers, removeMember,+} from '../src/core/access/members.ts';+import { accessCheck, whoCanRead } from '../src/commands/access.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const DIMS = 1536;+const SRC = 'source-a';++async function refusal(p: Promise<unknown>): Promise<{ code: string; reason?: string }> {+ try { await p; } catch (e) {+ if (e instanceof OperationError) return { code: e.code, ...(e.reason ? { reason: e.reason } : {}) };+ throw e;+ }+ throw new Error('expected a refusal');+}++for (const kind of testBackends()) {+ describe(`access members (${kind}, repo-less)`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;++ beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => new Array<number>(DIMS).fill(0).map((_, i) => (i === 0 ? 1 : 0))) })) as never);+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);+ await importFromContent(engine, 'notes/alice-plan', '---\ntype: note\ntitle: Alice plan\nreadable_by: [alice-example, group:team-a]\n---\n# Alice plan\n\nPlanning notes.', { sourceId: SRC });+ await importFromContent(engine, 'notes/quiet-plan', '---\ntype: note\ntitle: Quiet plan\nreadable_by: alice-example\nvisibility: private\n---\n# Quiet plan\n\nQuiet notes.', { sourceId: SRC });+ await importFromContent(engine, 'notes/open-plan', '---\ntype: note\ntitle: Open plan\n---\n# Open plan\n\nOpen notes.', { sourceId: SRC });+ }, 120_000);++ afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await close?.();+ }, 60_000);++ test('add creates a member and its groups; ids are validated; an existing id is not edited', async () => {+ const added = await addMember(engine, 'alice-example', { name: 'Alice Example', groups: ['team-b'] });+ expect(added.member).toMatchObject({ id: 'alice-example', display_name: 'Alice Example', status: 'enabled', groups: ['team-b'] });+ expect(added.groups_created).toEqual(['team-b']);+ await addMember(engine, 'bob-example');+ await addMember(engine, 'carol-example');+ expect(await refusal(addMember(engine, 'Not Valid!'))).toEqual({ code: 'access_member_invalid', reason: 'ill_formed' });+ expect(await refusal(addMember(engine, 'dan-example', { groups: ['bad group'] }))).toEqual({ code: 'access_member_invalid', reason: 'ill_formed' });+ expect(await getMember(engine, 'dan-example')).toBeNull();+ expect(await refusal(addMember(engine, 'alice-example'))).toEqual({ code: 'access_member_invalid', reason: 'exists' });+ const [row] = await engine.executeRaw<{ value: string }>("SELECT value FROM config WHERE key = 'access.restrictions_present'");+ expect(row?.value).toBe('1');+ });++ test('groups: add with members, remove members, and a preview-first group removal', async () => {+ const team = await addGroup(engine, 'team-a', ['bob-example', 'carol-example']);+ expect(team).toEqual({ group: { id: 'team-a', members: ['bob-example', 'carol-example'] }, created: true });+ expect(await removeGroupMembers(engine, 'team-a', ['carol-example'])).toEqual({ id: 'team-a', members: ['bob-example'] });+ expect(await refusal(addGroup(engine, 'team-a', ['nobody-example']))).toEqual({ code: 'access_member_invalid', reason: 'unknown' });+ expect(await refusal(removeGroupMembers(engine, 'team-z', ['bob-example']))).toEqual({ code: 'access_member_invalid', reason: 'unknown_group' });+ const preview = await previewRemoveGroup(engine, 'team-b');+ expect(preview.group).toEqual({ id: 'team-b', members: ['alice-example'] });+ expect((await listGroups(engine)).map(g => g.id)).toContain('team-b');+ await removeGroup(engine, 'team-b');+ expect((await listGroups(engine)).map(g => g.id)).not.toContain('team-b');+ expect((await getMember(engine, 'alice-example'))!.groups).toEqual([]);+ expect((await previewRemoveGroup(engine, 'team-a')).pages).toEqual([{ slug: 'notes/alice-plan', source_id: SRC }]);+ });++ test('who-can-read names the readers, the privacy layer and the enabled members they admit', async () => {+ const [alice] = await whoCanRead(engine, 'notes/alice-plan');+ expect(alice).toMatchObject({ source_id: SRC, readers: ['group:team-a', 'member:alice-example'], private: false, members: ['alice-example', 'bob-example'] });+ const [quiet] = await whoCanRead(engine, 'notes/quiet-plan', SRC);+ expect(quiet).toMatchObject({ readers: ['member:alice-example'], private: true, members: ['alice-example'] });+ expect((await whoCanRead(engine, 'notes/open-plan'))[0]).toMatchObject({ readers: null, members: 'every_source_reader' });+ expect(await refusal(whoCanRead(engine, 'notes/missing-plan'))).toEqual({ code: 'not_found' });+ });++ test('disable and enable are reversible; a disabled member gives no identity and no longer counts as a reader', async () => {+ expect((await disableMember(engine, 'bob-example')).status).toBe('disabled');+ expect(await refusal(memberIdentity(engine, 'bob-example'))).toEqual({ code: 'access_member_invalid', reason: 'disabled' });+ expect((await whoCanRead(engine, 'notes/alice-plan'))[0]!.members).toEqual(['alice-example']);+ expect((await enableMember(engine, 'bob-example')).status).toBe('enabled');+ expect(await memberIdentity(engine, 'bob-example')).toEqual({ member: 'bob-example', groups: ['team-a'], identity: ['group:team-a', 'member:bob-example'] });+ expect(await refusal(memberIdentity(engine, 'nobody-example'))).toEqual({ code: 'access_member_invalid', reason: 'unknown' });+ });++ test('rm previews bound credentials and pages without writing, then tombstones; the id is never reused', async () => {+ await addMember(engine, 'erin-example', { groups: ['team-a'] });+ await importFromContent(engine, 'notes/erin-plan', '---\ntype: note\ntitle: Erin plan\nreadable_by: [erin-example]\n---\n# Erin plan\n\nErin notes.', { sourceId: SRC });+ const minted = await mintLegacyToken(engine, { name: 'erin-laptop', scopes: ['read'], takesHolders: ['world'], sourceGrant: [SRC] });+ await bindCredential(engine, { kind: 'token', id: minted.id }, { member: 'erin-example' });+ const preview = await previewRemoveMember(engine, 'erin-example');+ expect(preview.member.status).toBe('enabled');+ expect(preview.bound_credentials).toEqual([{ kind: 'token', id: minted.id, name: 'erin-laptop' }]);+ expect(preview.pages).toEqual([{ slug: 'notes/erin-plan', source_id: SRC }]);+ expect(preview.note).toContain('can never be reused');+ expect((await getMember(engine, 'erin-example'))!.status).toBe('enabled');+ const removed = await removeMember(engine, 'erin-example');+ expect(removed.member).toMatchObject({ status: 'removed', groups: [] });+ expect((await listMembers(engine)).map(m => m.id)).not.toContain('erin-example');+ expect((await listMembers(engine, { includeRemoved: true })).find(m => m.id === 'erin-example')?.status).toBe('removed');+ expect(await refusal(addMember(engine, 'erin-example'))).toEqual({ code: 'access_member_id_retired' });+ expect(await refusal(enableMember(engine, 'erin-example'))).toEqual({ code: 'access_member_id_retired' });+ expect(await refusal(addGroup(engine, 'team-a', ['erin-example']))).toEqual({ code: 'access_member_id_retired' });+ expect(await refusal(memberIdentity(engine, 'erin-example'))).toEqual({ code: 'access_member_invalid', reason: 'removed' });+ });++ test('bindings: an unknown or disabled member is refused, none unbinds, may_act_for normalizes', async () => {+ const minted = await mintLegacyToken(engine, { name: 'bind-probe', scopes: ['read'], takesHolders: ['world'], sourceGrant: [SRC] });+ expect(await refusal(bindCredential(engine, { kind: 'token', id: minted.id }, { member: 'nobody-example' }))).toEqual({ code: 'access_member_invalid', reason: 'unknown' });+ await disableMember(engine, 'carol-example');+ expect(await refusal(bindCredential(engine, { kind: 'token', id: minted.id }, { member: 'carol-example' }))).toEqual({ code: 'access_member_invalid', reason: 'disabled' });+ await enableMember(engine, 'carol-example');+ const mayActFor = parseMayActFor('Bob-Example, group:team-a, guest');+ expect(mayActFor).toEqual(['group:team-a', 'guest', 'member:bob-example']);+ expect(await bindCredential(engine, { kind: 'token', id: minted.id }, { member: 'carol-example', mayActFor })).toEqual({ member: 'carol-example', may_act_for: mayActFor, changed: true });+ expect(await bindCredential(engine, { kind: 'token', id: minted.id }, { member: 'carol-example' }, { dryRun: true })).toMatchObject({ changed: false });+ expect(await bindCredential(engine, { kind: 'token', id: minted.id }, { member: null, mayActFor: null }, { dryRun: true })).toEqual({ member: null, may_act_for: null, changed: true });+ const [still] = await engine.executeRaw<{ member_id: string | null }>('SELECT member_id FROM access_tokens WHERE id = $1::uuid', [minted.id]);+ expect(still?.member_id).toBe('carol-example');+ await bindCredential(engine, { kind: 'token', id: minted.id }, { member: null, mayActFor: null });+ const [cleared] = await engine.executeRaw<{ member_id: string | null; may_act_for: string[] | null }>('SELECT member_id, may_act_for FROM access_tokens WHERE id = $1::uuid', [minted.id]);+ expect(cleared).toEqual({ member_id: null, may_act_for: null });+ expect(() => parseMayActFor('alice-example, not valid')).toThrow(OperationError);+ });++ test('access check: two credentials of one member read as the same identity but keep their own grants', async () => {+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('source-b', 'source-b') ON CONFLICT (id) DO NOTHING");+ const laptop = await mintLegacyToken(engine, { name: 'alice-laptop', scopes: ['read', 'write'], takesHolders: ['world'], sourceGrant: [SRC] });+ const phone = await mintLegacyToken(engine, { name: 'alice-phone', scopes: ['read'], takesHolders: ['world'], sourceGrant: ['source-b'] });+ for (const t of [laptop, phone]) await bindCredential(engine, { kind: 'token', id: t.id }, { member: 'alice-example' });+ const a = await accessCheck(engine, { token: 'alice-laptop' });+ const b = await accessCheck(engine, { token: 'alice-phone' });+ expect(a.identity).toEqual(['member:alice-example']);+ expect(b.identity).toEqual(a.identity);+ expect(a.verdict).toBe('reads_as_member');+ expect(a.grant.scopes).not.toEqual(b.grant.scopes);+ expect(a.grant.sources).not.toEqual(b.grant.sources);+ await disableMember(engine, 'alice-example');+ try {+ expect(await accessCheck(engine, { token: 'alice-laptop' })).toMatchObject({ verdict: 'refused', identity: [], member: { id: 'alice-example', status: 'disabled' } });+ } finally {+ await enableMember(engine, 'alice-example');+ }+ const unbound = await accessCheck(engine, { token: 'bind-probe' });+ expect(unbound).toMatchObject({ verdict: 'unbound', member: null, identity: [] });+ expect(await refusal(accessCheck(engine, { token: 'alice-laptop', as: 'nobody-example' }))).toEqual({ code: 'access_member_invalid', reason: 'unknown' });+ expect((await accessCheck(engine, { token: 'alice-laptop', as: 'bob-example,group:team-a' })).audience).toEqual([+ { principal: 'member:bob-example', covered_by_may_act_for: false }, { principal: 'group:team-a', covered_by_may_act_for: false }]);+ });+ });+}