Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Say which pages a disabled member or new folder rule leaves readable by no one (#9583)

Garry Tan4706715eebea
diff --git a/behavior-changes.d/auth_list_member_status_gbra593.md b/behavior-changes.d/auth_list_member_status_gbra593.md
new file mode 100644
index 0000000000..23c4023f35
--- /dev/null
+++ b/behavior-changes.d/auth_list_member_status_gbra593.md
@@ -0,0 +1,4 @@
+---
+kind: add
+---
+gbrain auth list --json adds a member_status field to each token: enabled, disabled or removed for the member the token is bound to, missing when that member row is gone, and null for an unbound token. The status field keeps its meaning (active or revoked). The text table prints refused for an active token whose member is disabled or removed, because the brain refuses that token at verification (access_member_disabled).
diff --git a/changelog.d/gbra593-read-by-nobody-messages.md b/changelog.d/gbra593-read-by-nobody-messages.md
new file mode 100644
index 0000000000..b16768b70c
--- /dev/null
+++ b/changelog.d/gbra593-read-by-nobody-messages.md
@@ -0,0 +1,10 @@
+**The access commands now say when a page is left readable by no member, and what to run.**
+
+### Fixed
+- `gbrain access member disable` lists the pages naming the member that no enabled member reads remotely any more, with the `gbrain repair visibility --slug <slug> --readers <member>,<owner>` write that gives one back.
+- `gbrain access who-can-read` explains a page no enabled member reads remotely, whether because its readers name only disabled or removed members or because its `readable_by` and the folder rules covering it admit nobody in common.
+- `gbrain access rule add` (and the other rule edits) warns in its preview about pages the change leaves readable by no member, such as a page written into a person's folder before that folder's rule named them.
+- `gbrain auth list` shows a token bound to a disabled or removed member as `refused`; `--json` keeps `status` and adds `member_status`.
+- A thin client whose credential is bound to a disabled member now says so (`access_member_disabled`) instead of "credentials may have been revoked".
+
+<!-- behavior-change: auth_list_member_status_gbra593 -->
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index da27bcfabc..5be12dce61 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -1074,7 +1074,7 @@ same on a repo-less brain and on a git-backed one.
|---|---|---|
| <a id="access_member_invalid"></a>`access_member_invalid` | A member or group id given to `gbrain access`, to `--member` on `gbrain auth create`, `rescope` or `register-client`, or to a local `--as <member>` is ill-formed (`ill_formed`) or names no usable member (`unknown`, `disabled`, `removed`, `unknown_group`), or `member add` named an existing member (`exists`). A member's declared email (`--email` on `member add` or `member set`) is not an address (`invalid_email`), another member already declares it (`email_taken`), or `member link --email` found several members declaring it (`email_ambiguous`; the email is unique, so this means a damaged table). Nothing was read or changed: an unknown `--as` is refused before the command runs instead of reading as unbound. | Check the id with `gbrain access member list --all`; add the member with `gbrain access member add <id>` or enable it with `gbrain access member enable <id>`. Ids are 1-64 characters: lower-case letters, digits, `.`, `_` or `-`. An email has one `@`, no spaces and at most 254 characters; clear a taken one with `gbrain access member set <id> --email none`, and link by member id when an email is ambiguous. `member link --email` naming an email no member declares is `not_found`; it never creates a member. |
| <a id="access_member_id_retired"></a>`access_member_id_retired` | `gbrain access member add` or `enable` named an id that `gbrain access member rm --yes` removed. Member ids are never reused, because pages and audit history may still name the removed id. Nothing was created. | Choose a new member id. `gbrain access member disable` is the reversible way to pause a member. |
-| <a id="access_member_disabled"></a>`access_member_disabled` | The access token or OAuth client is bound to a member who is disabled, removed or missing, so it was refused at verification (HTTP 401, `invalid_token` with this code in the description). A credential bound to a member reads as that member, so it is refused rather than silently treated as unbound. | Ask the brain operator to run `gbrain access member enable <id>`, or to rebind the credential with `gbrain auth rescope --token <name> --member <id>` (`--member none` unbinds it; an unbound credential sees no page that names readers). |
+| <a id="access_member_disabled"></a>`access_member_disabled` | The access token or OAuth client is bound to a member who is disabled, removed or missing, so it was refused at verification (HTTP 401, `invalid_token` with this code in the description). A credential bound to a member reads as that member, so it is refused rather than silently treated as unbound. | Ask the brain operator to run `gbrain access member enable <id>`, or to rebind the credential with `gbrain auth rescope --token <name> --member <id>` (`--member none` unbinds it; an unbound credential sees no page that names readers). On the host, `gbrain auth list` shows such a token as `refused` (`member_status` in `--json`), and a thin client prints this code instead of "credentials may have been revoked". Disabling a member lists the pages it leaves readable by no member, and `gbrain access who-can-read <slug>` names the `gbrain repair visibility --slug <slug> --readers <member>,<owner>` write that gives one back. |
| <a id="access_identity_unavailable"></a>`access_identity_unavailable` | The member a credential (access token, OAuth client or stdio binding) is bound to could not be looked up: the database failed the statement, or timed out or dropped the connection while the request was submitted. The request was refused and nothing was read or written. Reading the credential as unbound instead would open every unlabelled page to a labelled-only member. | Retry the same request in a few seconds; a write keeps the same `request_id`. `whoami` shows the member the connection reads as once the lookup works again. If it keeps failing, the brain operator runs `gbrain doctor --json` on the brain host. |
| <a id="access_rule_invalid"></a>`access_rule_invalid` | `gbrain access rule add` was given a rule whose prefix is not a literal lower-case slug folder ending in `/` (or holds `..` or `*`), whose readers are not member ids or `group:<id>`, or whose prefix another rule already covers; nothing was written. Prefixes match slugs literally, so a pattern or typo would restrict the wrong pages. | Write the prefix as a folder such as `partners/alice-example/` and the readers as `alice-example,group:team-a`; to change who reads a folder that already has a rule, pass that rule's `--id`. |
| <a id="access_policy_invalid"></a>`access_policy_invalid` | A source's committed `.gbrain/access.yml` (or a file given to `gbrain access rule import`) does not validate. The last applied rules stay in force and every prefix the file names reads as nobody for remote callers (the whole source when the file does not parse), so a typo never opens a folder. In a partial clone (`git clone --filter`), a policy file or an earlier version of it that the clone never fetched makes the whole source read as nobody the same way, because sync fetches nothing. | `gbrain access rule list --source <id>` shows each problem with its line. Fix the file, commit it with `gbrain git commit-push`, and run `gbrain sync --source <id> --no-pull`. In a partial clone, run the `git cat-file -p` or `git log -p` the problem names in the checkout, which fetches what is missing, then sync the same way. |
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 59842be0d7..03c3ed2070 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -890,8 +890,8 @@ async function runThinClientRouted(
console.error(' gbrain auth register-client <name> --grant-types client_credentials --scopes read,write,admin');
break;
case 'auth_after_refresh':
- console.error('OAuth auth failed after token refresh. Credentials may have been revoked.');
- console.error('Run `gbrain remote doctor` to confirm.');
+ console.error(e.detail?.code === 'access_member_disabled' ? e.message : 'OAuth auth failed after token refresh. Credentials may have been revoked.');
+ if (e.detail?.code !== 'access_member_disabled') console.error('Run `gbrain remote doctor` to confirm.');
break;
case 'rate_limited':
console.error(`OAuth /token is rate-limited by the server (HTTP 429)${e.detail?.retry_after_s !== undefined ? `; retry in ${e.detail.retry_after_s}s` : ''}.`);
diff --git a/src/commands/access-read-by-nobody.ts b/src/commands/access-read-by-nobody.ts
new file mode 100644
index 0000000000..fcfe83447e
--- /dev/null
+++ b/src/commands/access-read-by-nobody.ts
@@ -0,0 +1,98 @@
+/**
+ * GBRA-582 item 9 (leaver handover, PR 1): name the pages no enabled member reads remotely after a member is disabled
+ * or a folder rule changes, and the label write that gives one back. Messages only: nothing here writes.
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import { appliedRules } from '../core/access/policy.ts';
+import { folderRulesAllow, ruleCovers, ruleCoversSql, type FolderRule } from '../core/access/folder-rules.ts';
+import { identityFor, MEMBER_PAGE_PREFIX, normalizeReaders, readersAllow, NOBODY } from '../core/access/principals.ts';
+import { listMembers, type MemberRecord } from '../core/access/members.ts';
+import { ownerMemberId, ownerReadsRestrictedOn } from '../core/access/owner.ts';
+import { whoCanRead } from './access.ts';
+
+const SAMPLES = 5;
+/** Pages naming a disabled member that member disable checks one by one with who-can-read. */
+const DISABLE_CHECK_LIMIT = 200;
+
+interface PageRef { source_id: string; slug: string }
+
+const plain = (p: string) => (p.startsWith('member:') ? p.slice(7) : p);
+const sample = (refs: PageRef[], withSource: boolean) =>
+ refs.slice(0, SAMPLES).map(r => (withSource ? `${r.source_id}:${r.slug}` : r.slug)).join(', ') + (refs.length > SAMPLES ? ', ...' : '');
+const labelFix = (slug: string, readers: string) => `gbrain repair visibility --slug ${slug} --readers ${readers}`;
+const withOwner = (readers: string[], owner: string | null) => (owner && !readers.includes(owner) ? [...readers, owner] : readers);
+
+/** The who-can-read note for a page no enabled member reads remotely; null when someone does or the page is open. */
+export function readByNobodyNote(entry: { slug: string; source_id: string; readers: string[] | null }, ruled: boolean, admitted: number,
+ members: MemberRecord[], owner: string | null): string | null {
+ if (admitted > 0 || (entry.readers === null && !ruled) || entry.readers?.includes(NOBODY)) return null;
+ const down = (entry.readers ?? []).filter(r => r.startsWith('member:')).map(plain)
+ .filter(id => members.find(m => m.id === id)?.status !== 'enabled');
+ const named = (entry.readers ?? []).some(r => !down.includes(plain(r)));
+ const why = down.length && !named ? `its readable_by names ${down.join(', ')}, which ${down.length === 1 ? 'is' : 'are'} disabled, removed or unknown`
+ : entry.readers === null ? 'the folder rules covering it admit no enabled member'
+ : ruled ? 'no enabled member meets both its readable_by and the folder rules covering it'
+ : 'its readable_by names no enabled member';
+ const fix = entry.readers === null
+ ? `change the rule's readers (gbrain access rule list --source ${entry.source_id})`
+ : labelFix(entry.slug, withOwner(['<member>'], owner).join(','));
+ return `No enabled member reads it remotely: ${why}. The owner still reads it on the brain host. To give it to a member: ${fix}.`;
+}
+
+/** Pages whose readable_by names `memberId` that no enabled member reads remotely now (checked with who-can-read). */
+export async function pagesReadByNobodyNaming(engine: BrainEngine, memberId: string): Promise<{ pages: PageRef[]; truncated: boolean }> {
+ const rows = await engine.executeRaw<PageRef>(
+ `SELECT source_id, slug FROM pages WHERE deleted_at IS NULL AND frontmatter ? 'readable_by' AND gbrain_access_readers(frontmatter) @> ARRAY[$1]::text[]
+ ORDER BY source_id, slug LIMIT ${DISABLE_CHECK_LIMIT + 1}`, [`member:${memberId}`]);
+ const pages: PageRef[] = [];
+ for (const row of rows.slice(0, DISABLE_CHECK_LIMIT)) {
+ const [entry] = await whoCanRead(engine, row.slug, row.source_id);
+ if (Array.isArray(entry?.members) && entry.members.length === 0) pages.push(row);
+ }
+ return { pages, truncated: rows.length > DISABLE_CHECK_LIMIT };
+}
+
+/** The member disable lines for the pages it leaves readable by no member. */
+export async function disableReadByNobodyLines(engine: BrainEngine, memberId: string): Promise<string[]> {
+ const { pages, truncated } = await pagesReadByNobodyNaming(engine, memberId);
+ if (!pages.length) return [];
+ const owner = await ownerMemberId(engine);
+ return [
+ `Pages naming it that no enabled member reads remotely now (${pages.length}${truncated ? ` among the first ${DISABLE_CHECK_LIMIT} checked` : ''}): ${sample(pages, true)}.`,
+ ` The owner still reads them on the brain host. To give one to a member: ${labelFix(pages[0]!.slug, withOwner(['<member>'], owner).join(','))} (gbrain access who-can-read <slug> shows who reads a page).`,
+ ];
+}
+
+/**
+ * The rule-preview lines for pages under the changed prefixes that some enabled member reads under the applied rules
+ * and no enabled member reads under `desired` (audit case 9c: a page written before its folder's rule named readers).
+ */
+export async function ruleReadByNobodyLines(engine: BrainEngine, sourceId: string, desired: FolderRule[], prefixes: string[]): Promise<string[]> {
+ if (!prefixes.length) return [];
+ const current = await appliedRules(engine, sourceId);
+ const owner = await ownerMemberId(engine);
+ const enabled = (await listMembers(engine)).filter(m => m.status === 'enabled');
+ const ownerOptIn = !!owner && enabled.some(m => m.id === owner) && await ownerReadsRestrictedOn(engine);
+ const identities = enabled.map(m => identityFor(m.id, m.groups));
+ const rows = await engine.executeRaw<{ slug: string; frontmatter: unknown }>(
+ `SELECT slug, frontmatter FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND EXISTS (SELECT 1 FROM unnest($2::text[]) AS pfx WHERE ${ruleCoversSql('slug', 'pfx')}) ORDER BY slug`,
+ [sourceId, prefixes]);
+ const someoneReads = (slug: string, fm: unknown, rules: FolderRule[]) => {
+ const restricted = normalizeReaders(fm) !== null || rules.some(r => ruleCovers(slug, r.prefix));
+ if (!restricted) return true;
+ if (ownerOptIn && !slug.startsWith(MEMBER_PAGE_PREFIX)) return true;
+ return identities.some(identity => folderRulesAllow(slug, rules, identity) && readersAllow(fm, identity));
+ };
+ const stranded: PageRef[] = [];
+ for (const row of rows) {
+ const fm = typeof row.frontmatter === 'string' ? JSON.parse(row.frontmatter) : row.frontmatter;
+ if (someoneReads(row.slug, fm, current) && !someoneReads(row.slug, fm, desired)) stranded.push({ source_id: sourceId, slug: row.slug });
+ }
+ if (!stranded.length) return [];
+ const rule = desired.find(r => ruleCovers(stranded[0]!.slug, r.prefix));
+ const readers = withOwner((rule?.readable_by ?? ['member:<member>']).map(plain), owner).join(',');
+ return [
+ ` Pages this change leaves readable by no member remotely (${stranded.length}): ${sample(stranded, false)}. Their readable_by names no member the rules admit; the owner still reads them on the brain host.`,
+ ` To give one to the members the rule lists: ${labelFix(stranded[0]!.slug, readers)}`,
+ ];
+}
diff --git a/src/commands/access-rules.ts b/src/commands/access-rules.ts
index bd2560928c..a042ba04e8 100644
--- a/src/commands/access-rules.ts
+++ b/src/commands/access-rules.ts
@@ -26,6 +26,7 @@ import { classifyRulebook, coversDerived, folderRulesAllow, normalizeRule, ruleC
import { folderHoldingSlug, UNATTRIBUTED_MEMORY_SLUG } from '../core/facts-fence.ts';
import { heldRowsInVersions } from '../core/facts/fence-fact-append.ts';
import { identityFor } from '../core/access/principals.ts';
+import { ruleReadByNobodyLines } from './access-read-by-nobody.ts';
import { openTwins, openTwinsLines, OPEN_TWINS_PAGES, type OpenTwins } from '../core/access/open-twins.ts';
import { boundCredentials, listGroups, listMembers } from '../core/access/members.ts';
import { ownerReadsRestrictedOn, ownerView, readersOmitOwnerError, readersOwner } from '../core/access/owner.ts';
@@ -393,7 +394,8 @@ async function ruleCmd(engine: BrainEngine, sub: string | undefined, args: strin
}
const preview = await previewRules(engine, sourceId, store, persisted, desired);
if (!yes) {
- return print(json, { ...preview, applied: false }, () => previewLines(preview, `gbrain access rule ${[sub, ...args.filter(a => a !== '--json')].join(' ')} --yes`));
+ const stranded = json ? [] : await ruleReadByNobodyLines(engine, sourceId, desired, Object.keys(preview.matched_pages));
+ return print(json, { ...preview, applied: false }, () => previewLines(preview, `gbrain access rule ${[sub, ...args.filter(a => a !== '--json')].join(' ')} --yes`).toSpliced(-2, 0, ...stranded));
}
const r = await writeRules(engine, sourceId, desired, { expect, operation, message, json });
if (r.state === 'invalid') setCliExitVerdict(1);
diff --git a/src/commands/access.ts b/src/commands/access.ts
index fe116e1a11..7364e1b06e 100644
--- a/src/commands/access.ts
+++ b/src/commands/access.ts
@@ -17,6 +17,7 @@ import type { BrainEngine } from '../core/engine.ts';
import { exitCliError, usageError } from '../cli/cli-error.ts';
import { runAccessRules } from './access-rules.ts';
import { runAccessServes } from './access-serves.ts';
+import { disableReadByNobodyLines, readByNobodyNote } from './access-read-by-nobody.ts';
import { rescopeArchiveAfter, rescopeArchiveBefore } from './archive-rescope.ts';
import { opError } from '../core/ops/contract.ts';
import { sqlQueryForEngine } from '../core/sql-query.ts';
@@ -171,7 +172,8 @@ export async function whoCanRead(engine: BrainEngine, slug: string, sourceId?: s
const ownerId = await ownerMemberId(engine);
const optIn = await ownerReadsRestrictedOn(engine) ? ownerId : null;
const memberLineage = await membersReadLineageOn(engine);
- const enabled = (await listMembers(engine)).filter(m => m.status === 'enabled');
+ const known = await listMembers(engine);
+ const enabled = known.filter(m => m.status === 'enabled');
const audienceIds = enabled.filter(m => m.kind === 'audience').map(m => m.id);
const members = await Promise.all(enabled.map(async m => {
const identity = identityFor(m.id, m.groups);
@@ -205,7 +207,9 @@ export async function whoCanRead(engine: BrainEngine, slug: string, sourceId?: s
`SELECT count(*)::int AS n FROM unnest($1::text[]) AS x WHERE NOT EXISTS (SELECT 1 FROM access_rules r WHERE r.source_id = $2 AND x = $2 || ':' || r.rule_id AND NOT r.covers_derived)`,
[row.folder_rule_ids, row.source_id]) : [{ n: 0 }];
const closesLineage = readers !== null || Number(lineageRules[0]?.n ?? 0) > 0;
+ const nobody = readByNobodyNote({ slug: row.slug, source_id: row.source_id, readers }, ruled, allowed.length, known, ownerId);
const notes = [
+ ...(nobody ? [nobody] : []),
readers === null ? (ruled ? 'No readable_by, but folder rules cover it: only members who meet every rule read it remotely.' : 'No readable_by: every caller entitled to the source reads it.')
: readers.includes('!nobody') ? 'readable_by is malformed, so no remote caller reads it; fix the frontmatter.'
: 'Only credentials bound to these members (directly or through a group) read it remotely; unbound credentials and stdio do not.',
@@ -351,8 +355,10 @@ async function memberCmd(engine: BrainEngine, sub: string | undefined, args: str
if (sub === 'enable') await rescopeArchiveBefore(engine, id, 'enable');
const m = await (sub === 'disable' ? disableMember : enableMember)(engine, id);
if (sub === 'enable') await rescopeArchiveAfter(engine);
+ const stranded = sub === 'disable' && !json ? await disableReadByNobodyLines(engine, m.id).catch((e: unknown) =>
+ [`Could not check which pages naming it no enabled member reads (${e instanceof Error ? e.message : String(e)}); the disable stands. gbrain access who-can-read <slug> shows who reads a page.`]) : [];
return print(json, { member: m }, () => [`Member ${sub}d: ${m.id}`, memberLine(m),
- sub === 'disable' ? 'Its credentials are refused on their next request; gbrain access member enable undoes this.' : 'Its credentials read again on their next request.']);
+ sub === 'disable' ? 'Its credentials are refused on their next request; gbrain access member enable undoes this.' : 'Its credentials read again on their next request.', ...stranded]);
}
case 'set': {
const email = flagValue(args, '--email');
diff --git a/src/commands/auth.ts b/src/commands/auth.ts
index 04081c021c..28814658c9 100644
--- a/src/commands/auth.ts
+++ b/src/commands/auth.ts
@@ -173,10 +173,11 @@ async function list(json: boolean) {
SELECT * FROM access_tokens
ORDER BY created_at DESC
`;
+ const memberStatus = await (await import('../core/access/token-member-status.ts')).tokenMemberStatuses(sql, rows);
if (json) {
console.log(JSON.stringify(rows.map(r => ({
id: String(r.id), name: r.name, scopes: renderTokenScopes(r.scopes), created_at: r.created_at, last_used_at: r.last_used_at ?? null,
- status: r.revoked_at ? 'revoked' : 'active', private_pages: privatePagesFromColumn(r.private_pages), private_facts: privatePagesFromColumn(r.private_facts),
+ status: r.revoked_at ? 'revoked' : 'active', private_pages: privatePagesFromColumn(r.private_pages), private_facts: privatePagesFromColumn(r.private_facts), member_status: memberStatus(r),
})), null, 2));
return;
}
@@ -192,7 +193,7 @@ async function list(json: boolean) {
const scopes = renderTokenScopes(r.scopes).padEnd(21);
const created = new Date(r.created_at as string).toISOString().slice(0, 19);
const lastUsed = r.last_used_at ? new Date(r.last_used_at as string).toISOString().slice(0, 19) : 'never'.padEnd(19);
- const status = (r.revoked_at ? 'REVOKED' : 'active').padEnd(7);
+ const status = (r.revoked_at ? 'REVOKED' : (memberStatus(r) ?? 'enabled') !== 'enabled' ? 'refused' : 'active').padEnd(7);
const facts = privatePagesFromColumn(r.private_facts) === 'granted_sources' ? 'granted-sources' : 'none';
console.log(`${id} ${name} ${scopes} ${created} ${lastUsed} ${status} ${facts.padEnd(15)} ${renderPrivatePages(privatePagesFromColumn(r.private_pages))}`);
}
diff --git a/src/core/access/token-member-status.ts b/src/core/access/token-member-status.ts
new file mode 100644
index 0000000000..628eb76d04
--- /dev/null
+++ b/src/core/access/token-member-status.ts
@@ -0,0 +1,17 @@
+/**
+ * GBRA-582 item 9d: the state of the member each credential row is bound to, for `gbrain auth list`. A credential bound
+ * to a member that is not enabled is refused at verification (access_member_disabled), whatever its own status says.
+ */
+import type { SqlQuery } from '../sql-query.ts';
+
+export type TokenMemberStatus = 'enabled' | 'disabled' | 'removed' | 'missing' | null;
+
+/** A lookup from a credential row to its bound member's status: null when unbound, `missing` when no member row exists. */
+export async function tokenMemberStatuses(sql: SqlQuery, rows: ReadonlyArray<Record<string, unknown>>): Promise<(row: Record<string, unknown>) => TokenMemberStatus> {
+ const members = rows.some(r => r.member_id) ? await sql`SELECT id, disabled_at, tombstoned_at FROM access_members` : [];
+ return row => {
+ if (!row.member_id) return null;
+ const m = members.find(x => x.id === row.member_id);
+ return !m ? 'missing' : m.tombstoned_at ? 'removed' : m.disabled_at ? 'disabled' : 'enabled';
+ };
+}
diff --git a/src/core/mcp-client.ts b/src/core/mcp-client.ts
index f2ad929892..3f65f9cb1d 100644
--- a/src/core/mcp-client.ts
+++ b/src/core/mcp-client.ts
@@ -95,6 +95,18 @@ async function loadHttpClientSdk(): Promise<HttpClientSdk> {
return httpClientSdk;
}
+/**
+ * A second HTTP 401 after a fresh token. GBRA-582 item 9d: when the host's refusal body names access_member_disabled
+ * (GBRA-218), the client is fine and its bound member cannot read, so the error says that instead of "revoked". The OAuth
+ * host's SDK bearer check puts the code at the start of error_description; the bearer-token transport sends a code key.
+ */
+function authAfterRefresh(e: StreamableHTTPError, mcpUrl: string, fallback: string): RemoteMcpError {
+ return /"(?:code|error_description)"\s*:\s*"access_member_disabled\b/.test(e.message)
+ ? new RemoteMcpError('auth_after_refresh', 'The brain host refused this client: its credential is bound to a member who is disabled, removed or missing (access_member_disabled). Ask the brain host\'s operator to enable the member or bind this client to an enabled one.',
+ { mcp_url: mcpUrl, status: 401, code: 'access_member_disabled' })
+ : new RemoteMcpError('auth_after_refresh', fallback, { mcp_url: mcpUrl, status: 401 });
+}
+
/** A transport error: only possible once loadHttpClientSdk has loaded the transport that throws it. */
function isStreamableHttpError(e: unknown): e is StreamableHTTPError {
return httpClientSdk !== undefined && e instanceof httpClientSdk.StreamableHTTPError;
@@ -503,11 +515,8 @@ export async function callRemoteTool(
if (isStreamableHttpError(e2) && e2.code === 401) {
submitted = false;
dropAccessToken(config);
- throw new RemoteMcpError(
- 'auth_after_refresh',
- `Auth failed after token refresh. Verify oauth_client_id and secret are still valid; the host operator may need to re-run \`gbrain auth register-client\`.`,
- { mcp_url: remote.mcp_url, status: 401 },
- );
+ throw authAfterRefresh(e2, remote.mcp_url,
+ `Auth failed after token refresh. Verify oauth_client_id and secret are still valid; the host operator may need to re-run \`gbrain auth register-client\`.`);
}
throw e2;
}
@@ -655,7 +664,7 @@ export async function forwardRemoteToolCall(
if (!isStreamableHttpError(e2) || e2.code !== 401) throw e2;
submitted = false;
dropAccessToken(config);
- throw new RemoteMcpError('auth_after_refresh', 'Auth failed after token refresh.', { mcp_url: remote.mcp_url, status: 401 });
+ throw authAfterRefresh(e2, remote.mcp_url, 'Auth failed after token refresh.');
}
}
} catch (e) {
diff --git a/src/mcp/remote-bridge-errors.ts b/src/mcp/remote-bridge-errors.ts
index d30e20b060..8c9db70080 100644
--- a/src/mcp/remote-bridge-errors.ts
+++ b/src/mcp/remote-bridge-errors.ts
@@ -69,6 +69,13 @@ function reasonFix(e: RemoteMcpError, opts: { clientId?: string; timeoutMs: numb
}
case 'auth':
case 'auth_after_refresh': {
+ if (e.detail?.code === 'access_member_disabled') {
+ return { code: 'access_member_disabled', retryable: false, recovery: 'Retrying will not help until the host operator acts.',
+ why: 'The brain host refused this client because the member its credential is bound to is disabled, removed or missing; the client itself is still valid.',
+ suggestion: 'Ask the brain host\'s operator to enable the member, or to bind this client to an enabled member.',
+ fix: action({ argv: ['gbrain', 'access', 'member', 'list', '--all'], actor: 'host_admin', why: 'Read-only, on the brain host: shows each member and whether it is disabled or removed.',
+ user_message: 'The gbrain brain host refuses this client because the member it is bound to is disabled or removed. Can you ask the host\'s owner to enable that member, or bind this client to an enabled one?' }) };
+ }
const client = opts.clientId ? `OAuth client ${opts.clientId}` : "this thin client's OAuth client";
return { code: 'invalid_client', retryable: false, recovery: 'Retrying will not help until the host owner acts.',
why: `The brain host rejected ${client}: it was revoked, its secret changed, or it expired.`,
diff --git a/test/access-read-by-nobody-gbra593.test.ts b/test/access-read-by-nobody-gbra593.test.ts
new file mode 100644
index 0000000000..17aeff8091
--- /dev/null
+++ b/test/access-read-by-nobody-gbra593.test.ts
@@ -0,0 +1,190 @@
+/**
+ * GBRA-582 item 9 (leaver handover, PR 1): the access commands say when a page is left readable by no member.
+ *
+ * 1. Protects: `gbrain access who-can-read` explains a page no enabled member reads remotely (its readers name only a
+ * disabled member, or its readable_by and a folder rule admit nobody in common) and names the label write that gives
+ * it back; `gbrain access member disable` counts and samples the pages it leaves readable by no member;
+ * `gbrain access rule add` previews the pages a new rule leaves readable by no member. Every one is a message: no
+ * page, rule or label changes, and the owner's reads are the same before and after.
+ * 2. Fails when: who-can-read prints "none" with no reason, member disable says nothing about the pages it strands, or
+ * a rule preview over a pre-written page (audit case 9c) shows no warning.
+ * 3. Existing coverage: access-who-can-read-folder-rules pins the member list; access-members pins disable itself.
+ * 4. Real seams: the access CLI module on PGLite and Postgres, repo-less (database store) and on a managed git source.
+ */
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { existsSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runAccess, whoCanRead } from '../src/commands/access.ts';
+import { readByNobodyNote } from '../src/commands/access-read-by-nobody.ts';
+import type { MemberRecord } from '../src/core/access/members.ts';
+import { addMember } from '../src/core/access/members.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { durableGitRepo } from './helpers/git-publication.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+async function access(engine: BrainEngine, args: string[]): Promise<string> {
+ const lines: string[] = [];
+ const spy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { lines.push(a.map(String).join(' ')); });
+ try { await runAccess(engine, args); } finally { spy.mockRestore(); }
+ return lines.join('\n');
+}
+
+/** Every page's slug, readers and folder rules: what the owner's reads depend on. */
+const pageState = (engine: BrainEngine, src: string) => engine.executeRaw<{ slug: string; readers: unknown; rules: unknown }>(
+ `SELECT slug, frontmatter->'readable_by' AS readers, folder_rule_ids AS rules FROM pages WHERE source_id = $1 ORDER BY slug`, [src]);
+
+/** Pages whose who-can-read list names the owner (or every source reader). */
+async function ownerReads(engine: BrainEngine, src: string): Promise<string[]> {
+ const out: string[] = [];
+ for (const { slug } of await pageState(engine, src)) {
+ const [entry] = await whoCanRead(engine, slug, src);
+ if (entry!.members === 'every_source_reader' || entry!.members.includes('owner-example')) out.push(slug);
+ }
+ return out;
+}
+
+type Write = (slug: string, content: string) => Promise<unknown>;
+
+async function fixture(engine: BrainEngine, src: string, write: Write = (slug, content) => importFromContent(engine, slug, content, { sourceId: src })): Promise<void> {
+ if (src !== 'default') await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT DO NOTHING', [src]);
+ for (const id of ['owner-example', 'alice-example', 'bob-example', 'carol-example', 'dave-example']) await addMember(engine, id);
+ await engine.setConfig('access.owner_member', 'owner-example');
+ const page = (slug: string, readable_by?: string[]) => write(slug,
+ `---\ntype: note\ntitle: ${slug}\n${readable_by ? `readable_by: [${readable_by.join(', ')}]\n` : ''}---\nSynthetic notes.\n`);
+ await page('companies/acme-example', ['bob-example']);
+ await page('notes/bob-billing-example', ['bob-example']);
+ await page('notes/alice-pricing-example', ['bob-example', 'alice-example']);
+ await page('notes/owner-plan-example', ['bob-example', 'owner-example']);
+ await page('people/dave-example/onboarding', ['carol-example']);
+ await page('open/handbook-example');
+}
+
+async function cases(engine: BrainEngine, src: string): Promise<void> {
+ const ownerBefore = await ownerReads(engine, src);
+ const stateBefore = await pageState(engine, src);
+ expect(ownerBefore).toEqual(['notes/owner-plan-example', 'open/handbook-example']);
+
+ const [before] = await whoCanRead(engine, 'companies/acme-example', src);
+ expect(before!.members).toEqual(['bob-example']);
+ expect(before!.note).not.toContain('No enabled member reads it');
+
+ const disabled = await access(engine, ['member', 'disable', 'bob-example']);
+ expect(disabled).toContain('Member disabled: bob-example');
+ expect(disabled).toContain('Pages naming it that no enabled member reads remotely now (2): ' + src + ':companies/acme-example, ' + src + ':notes/bob-billing-example.');
+ expect(disabled).not.toContain('alice-pricing-example');
+ expect(disabled).not.toContain('owner-plan-example');
+ expect(disabled).toContain('gbrain repair visibility --slug companies/acme-example --readers <member>,owner-example');
+ const disabledJson = JSON.parse(await access(engine, ['member', 'disable', 'bob-example', '--json']));
+ expect(Object.keys(disabledJson)).toEqual(['member']);
+
+ const [after] = await whoCanRead(engine, 'companies/acme-example', src);
+ expect(after!.members).toEqual([]);
+ expect(after!.note).toContain('No enabled member reads it remotely: its readable_by names bob-example, which is disabled, removed or unknown.');
+ expect(after!.note).toContain('gbrain repair visibility --slug companies/acme-example --readers <member>,owner-example');
+ const text = await access(engine, ['who-can-read', 'companies/acme-example', '--source', src]);
+ expect(text).toContain('Members who may read it: none');
+ expect(text).toContain('No enabled member reads it remotely');
+ const [shared] = await whoCanRead(engine, 'notes/alice-pricing-example', src);
+ expect(shared!.members).toEqual(['alice-example']);
+ expect(shared!.note).not.toContain('No enabled member reads it');
+
+ const preview = await access(engine, ['rule', 'add', '--prefix', 'people/dave-example/', '--readers', 'dave-example,owner-example', '--source', src]);
+ expect(preview).toContain('Pages this change leaves readable by no member remotely (1): people/dave-example/onboarding.');
+ expect(preview).toContain('gbrain repair visibility --slug people/dave-example/onboarding --readers dave-example,owner-example');
+ expect(preview.trimEnd().split('\n').at(-1)).toStartWith('Nothing written. To approve');
+ const open = await access(engine, ['rule', 'add', '--prefix', 'open/', '--readers', 'alice-example,owner-example', '--source', src]);
+ expect(open).not.toContain('readable by no member');
+
+ expect(await pageState(engine, src)).toEqual(stateBefore);
+ expect(await ownerReads(engine, src)).toEqual(ownerBefore);
+}
+
+describe('readByNobodyNote reasons', () => {
+ const member = (id: string, status: MemberRecord['status']): MemberRecord =>
+ ({ id, display_name: null, email: null, status, kind: 'person', labelled_only: false, groups: [], created_at: null });
+ const members = [member('owner-example', 'enabled'), member('alice-example', 'enabled'), member('bob-example', 'disabled'), member('carol-example', 'removed')];
+ const note = (readers: string[] | null, ruled: boolean) => readByNobodyNote({ slug: 'notes/x-example', source_id: 'source-a', readers }, ruled, 0, members, 'owner-example');
+
+ test('a page only folder rules close points at the rule, not a label write', () => {
+ expect(note(null, true)).toBe('No enabled member reads it remotely: the folder rules covering it admit no enabled member. The owner still reads it on the brain host. To give it to a member: change the rule\'s readers (gbrain access rule list --source source-a).');
+ });
+
+ test('readable_by and folder rules with no enabled member in common', () => {
+ expect(note(['member:alice-example'], true)).toContain('no enabled member meets both its readable_by and the folder rules covering it');
+ expect(note(['member:alice-example'], true)).toContain('gbrain repair visibility --slug notes/x-example --readers <member>,owner-example');
+ });
+
+ test('a removed reader is named like a disabled one, and a group-only label names no enabled member', () => {
+ expect(note(['member:carol-example'], false)).toContain('its readable_by names carol-example, which is disabled, removed or unknown');
+ expect(note(['group:team-example'], false)).toContain('its readable_by names no enabled member');
+ });
+
+ test('a page someone reads, an open page and a malformed label get no note', () => {
+ expect(readByNobodyNote({ slug: 'a', source_id: 's', readers: ['member:alice-example'] }, false, 1, members, null)).toBeNull();
+ expect(note(null, false)).toBeNull();
+ expect(note(['!nobody'], false)).toBeNull();
+ });
+});
+
+describe('member disable when the stranded-page check fails', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite' } as never);
+ await engine.initSchema();
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await fixture(engine, 'source-a');
+ }, 120_000);
+ afterAll(async () => { await engine?.disconnect(); });
+
+ test('the disable still succeeds and says how to check the pages by hand', async () => {
+ const original = engine.executeRaw.bind(engine);
+ const spy = spyOn(engine, 'executeRaw').mockImplementation(((sql: string, params?: unknown[]) => {
+ if (sql.includes('gbrain_access_readers(frontmatter) @>')) return Promise.reject(new Error('connection dropped'));
+ return original(sql, params as never);
+ }) as never);
+ let out: string;
+ try { out = await access(engine, ['member', 'disable', 'bob-example']); } finally { spy.mockRestore(); }
+ expect(out).toContain('Member disabled: bob-example');
+ expect(out).toContain('Could not check which pages naming it no enabled member reads (connection dropped)');
+ expect(out).toContain('gbrain access who-can-read <slug>');
+ const [row] = await engine.executeRaw<{ disabled: boolean }>("SELECT disabled_at IS NOT NULL AS disabled FROM access_members WHERE id = 'bob-example'");
+ expect(row!.disabled).toBe(true);
+ }, 120_000);
+});
+
+for (const backend of testBackends()) {
+ describe(`read-by-nobody messages on a repo-less brain (${backend})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => {
+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { const pglite = new PGLiteEngine(); await pglite.connect({ engine: 'pglite' } as never); await pglite.initSchema(); engine = pglite; close = () => pglite.disconnect(); }
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await fixture(engine, 'source-a');
+ }, 180_000);
+ afterAll(async () => { await close?.(); });
+
+ test('who-can-read, member disable and rule add name the pages no member reads, and change nothing', () => cases(engine, 'source-a'), 120_000);
+ });
+
+ describe(`read-by-nobody rule preview on a git source (${backend})`, () => {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), 'archive/\n'); durableGitRepo(root, ['.gitignore']); };
+
+ test('the rule preview warns about the pre-written page and writes no access.yml', () => managedBrain(async ({ engine, ctx, root }) => {
+ await fixture(engine, 'default', async (slug, content) => {
+ expect(await operationsByName.put_page!.handler(ctx, { slug, content, request_id: randomUUID(), wait_ms: 30_000 })).toMatchObject({ state: 'committed' });
+ });
+ const preview = await access(engine, ['rule', 'add', '--prefix', 'people/dave-example/', '--readers', 'dave-example,owner-example']);
+ expect(preview).toContain('Pages this change leaves readable by no member remotely (1): people/dave-example/onboarding.');
+ expect(existsSync(join(root, '.gbrain', 'access.yml'))).toBe(false);
+ }, { databaseUrl, setup }), 240_000);
+ });
+}
diff --git a/test/auth-list-member-status-gbra593.test.ts b/test/auth-list-member-status-gbra593.test.ts
new file mode 100644
index 0000000000..4a0ef0d5ea
--- /dev/null
+++ b/test/auth-list-member-status-gbra593.test.ts
@@ -0,0 +1,103 @@
+/**
+ * GBRA-582 item 9d (leaver handover, PR 1): `gbrain auth list` shows a token bound to a disabled member as refused.
+ *
+ * 1. Protects: `auth list --json` keeps `status` (active or revoked, from revoked_at alone) and adds `member_status`
+ * (the bound member's enabled, disabled or removed, `missing` for a binding to no member row, null when unbound);
+ * the text table prints `refused` for an active token whose member cannot read.
+ * 2. Fails when: a disabled member's token lists as plain `active` with nothing beside it, or `status` changes meaning.
+ * 3. Existing coverage: auth-private-pages-output pins the field set; access-binding pins the refusal at verification.
+ * 4. Real seams: the auth CLI handler on PGLite under a sandboxed GBRAIN_HOME, real members and bindings (console.log captured).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createEngine } from '../src/core/engine-factory.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { runAuth } from '../src/commands/auth.ts';
+import { addMember, disableMember, removeMember } from '../src/core/access/members.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { tokenMemberStatuses } from '../src/core/access/token-member-status.ts';
+import type { SqlQuery } from '../src/core/sql-query.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let root: string, home: string, db: string;
+
+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 engine.disconnect(); }
+}
+
+async function auth(args: string[]): Promise<string> {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.join(' ')); };
+ try { await withEnv({ GBRAIN_HOME: home, HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_SOURCE: undefined }, () => runAuth(args)); }
+ finally { console.log = original; }
+ return lines.join('\n');
+}
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'gb-auth-member-status-'));
+ 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();
+ for (const id of ['owner-example', 'alice-example', 'bob-example', 'carol-example']) await addMember(engine, id);
+ const bind = async (name: string, member: string | null) => {
+ const t = await mintLegacyToken(engine, { name, scopes: ['read'], takesHolders: ['world'] });
+ if (member) await engine.executeRaw('UPDATE access_tokens SET member_id = $1 WHERE id = $2::uuid', [member, t.id]);
+ return t;
+ };
+ await bind('owner-key', 'owner-example');
+ await bind('alice-key', 'alice-example');
+ await bind('bob-key', 'bob-example');
+ await bind('carol-key', 'carol-example');
+ await bind('unbound-key', null);
+ const old = await bind('bob-old-key', 'bob-example');
+ await engine.executeRaw('UPDATE access_tokens SET revoked_at = now() WHERE id = $1::uuid', [old.id]);
+ await disableMember(engine, 'bob-example');
+ await removeMember(engine, 'carol-example');
+ });
+}, 120_000);
+
+afterAll(() => { rmSync(root, { recursive: true, force: true }); });
+
+describe('auth list member status (GBRA-582 item 9d)', () => {
+ test('--json keeps status and adds member_status; the owner and enabled members read as before', async () => {
+ const tokens = JSON.parse(await auth(['list', '--json'])) as Array<Record<string, unknown>>;
+ const byName = Object.fromEntries(tokens.map(t => [t.name as string, [t.status, t.member_status]]));
+ expect(byName).toEqual({
+ 'owner-key': ['active', 'enabled'], 'alice-key': ['active', 'enabled'], 'bob-key': ['active', 'disabled'],
+ 'carol-key': ['active', 'removed'], 'unbound-key': ['active', null], 'bob-old-key': ['revoked', 'disabled'],
+ });
+ });
+
+ test('the text table prints refused for an active token whose member cannot read', async () => {
+ const rows = (await auth(['list'])).split('\n');
+ const at = rows.find(r => r.startsWith('ID '))!.indexOf('Status');
+ const status = (name: string) => rows.find(r => r.includes(` ${name} `))!.slice(at, at + 7).trim();
+ expect(status('owner-key')).toBe('active');
+ expect(status('alice-key')).toBe('active');
+ expect(status('unbound-key')).toBe('active');
+ expect(status('bob-key')).toBe('refused');
+ expect(status('carol-key')).toBe('refused');
+ expect(status('bob-old-key')).toBe('REVOKED');
+ });
+
+ test('tokenMemberStatuses skips the member read when no row is bound and names a dangling binding missing', async () => {
+ let reads = 0;
+ const sql = ((..._args: unknown[]) => { reads++; return Promise.resolve([{ id: 'alice-example', disabled_at: null, tombstoned_at: null }]); }) as unknown as SqlQuery;
+ const unbound = await tokenMemberStatuses(sql, [{ member_id: null }]);
+ expect(unbound({ member_id: null })).toBeNull();
+ expect(reads).toBe(0);
+ const bound = await tokenMemberStatuses(sql, [{ member_id: 'alice-example' }, { member_id: 'ghost-example' }]);
+ expect(reads).toBe(1);
+ expect(bound({ member_id: 'alice-example' })).toBe('enabled');
+ expect(bound({ member_id: 'ghost-example' })).toBe('missing');
+ });
+});
diff --git a/test/auth-private-pages-output.test.ts b/test/auth-private-pages-output.test.ts
index 3925a86437..6f33e0896f 100644
--- a/test/auth-private-pages-output.test.ts
+++ b/test/auth-private-pages-output.test.ts
@@ -70,10 +70,10 @@ describe('private-pages grant output (#8104)', () => {
expect(privatePagesFromColumn(null)).toBe('none');
});
- test('auth list --json prints exactly id, name, scopes, created_at, last_used_at, status, private_pages and private_facts: never token_hash', async () => {
+ test('auth list --json prints exactly id, name, scopes, created_at, last_used_at, status, private_pages, private_facts and member_status: never token_hash', async () => {
const tokens = JSON.parse(await auth(['list', '--json'])) as Array<Record<string, unknown>>;
for (const t of tokens) {
- expect(Object.keys(t).sort()).toEqual(['created_at', 'id', 'last_used_at', 'name', 'private_facts', 'private_pages', 'scopes', 'status']);
+ expect(Object.keys(t).sort()).toEqual(['created_at', 'id', 'last_used_at', 'member_status', 'name', 'private_facts', 'private_pages', 'scopes', 'status']);
}
expect(JSON.stringify(tokens)).not.toContain('token_hash');
const byName = Object.fromEntries(tokens.map(t => [t.name as string, [t.status, t.private_pages]]));
diff --git a/test/e2e/access-read-by-nobody-gbra593-postgres.test.ts b/test/e2e/access-read-by-nobody-gbra593-postgres.test.ts
new file mode 100644
index 0000000000..3952750200
--- /dev/null
+++ b/test/e2e/access-read-by-nobody-gbra593-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../access-read-by-nobody-gbra593.test.ts'));
diff --git a/test/e2e/thin-client.test.ts b/test/e2e/thin-client.test.ts
index c529cc188a..7a2c51c1cd 100644
--- a/test/e2e/thin-client.test.ts
+++ b/test/e2e/thin-client.test.ts
@@ -412,6 +412,29 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {
expect(r.stderr).toMatch(/OAuth (auth|\/token) failed/);
});
+ test('a client bound to a disabled member is told so by the real host, not that its credentials were revoked', async () => {
+ const host = async (args: string[]) => {
+ const r = await spawn(args, hostHome);
+ expect(r.exitCode, cliDiagnostic(`host ${args.join(' ')}`, r)).toBe(0);
+ };
+ await host(['access', 'member', 'add', 'alice-example']);
+ await host(['auth', 'rescope', '--client', clientId, '--member', 'alice-example']);
+ await host(['access', 'member', 'disable', 'alice-example']);
+ try {
+ const r = await spawn(['search', G3_MARKER, '--json'], clientHome);
+ expect(r.exitCode, cliDiagnostic('thin-client CLI', r)).toBe(1);
+ expect(r.stderr).toContain('bound to a member who is disabled, removed or missing (access_member_disabled)');
+ expect(r.stderr).not.toContain('Credentials may have been revoked');
+ expect(r.stderr).not.toContain('gbrain remote doctor');
+ } finally {
+ await host(['auth', 'rescope', '--client', clientId, '--member', 'none']);
+ await host(['access', 'member', 'enable', 'alice-example']);
+ // The refused call dropped the cached token; the stopped-host test below needs one again.
+ const warm = await spawn(['search', G3_MARKER, '--json'], clientHome);
+ expect(warm.exitCode, cliDiagnostic('thin-client CLI', warm)).toBe(0);
+ }
+ });
+
test('stopped host: routed verbs fail fast with the canonical unreachable error, not a hang', async () => {
// Kill the live serve. This test is LAST in the file by design (see the
// ordering note above); afterAll's kill is a no-op afterwards.
diff --git a/test/mcp-client.test.ts b/test/mcp-client.test.ts
index 8ada8823fe..a5967b6478 100644
--- a/test/mcp-client.test.ts
+++ b/test/mcp-client.test.ts
@@ -18,6 +18,7 @@
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import {
callRemoteTool,
+ forwardRemoteToolCall,
unpackToolResult,
RemoteMcpError,
_clearMcpClientTokenCache,
@@ -29,6 +30,7 @@ import { VERSION } from '../src/version.ts';
import { pendingReceiptOf, writeErrorExitCode } from '../src/core/persistence/write-wait.ts';
import { PENDING_WRITE_EXIT_CODE } from '../src/core/exit-codes.ts';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InvalidTokenError } from '@modelcontextprotocol/sdk/server/auth/errors.js';
let server: ReturnType<typeof Bun.serve>;
let port: number;
@@ -40,6 +42,7 @@ let tokenMintCount = 0;
type Stage = 'discovery' | 'token' | 'initialize' | 'notifications/initialized' | 'tools/call';
let requests: Partial<Record<Stage, number>> = {};
let statusFor: (stage: Stage, attempt: number) => number | undefined = () => undefined;
+let rejectionBody = 'fixture rejection';
let hangingStage: Stage | undefined;
let hangFromAttempt = 1;
let hangAfterHeaders = false;
@@ -69,7 +72,7 @@ function intercept(stage: Stage, req: Request): Response | Promise<Response> | u
});
}
const status = statusFor(stage, requests[stage]!);
- if (status !== undefined) return new Response('fixture rejection', { status });
+ if (status !== undefined) return new Response(rejectionBody, { status });
}
beforeAll(() => {
@@ -130,6 +133,7 @@ beforeEach(() => {
tokenMintCount = 0;
requests = {};
statusFor = () => undefined;
+ rejectionBody = 'fixture rejection';
hangingStage = undefined;
hangFromAttempt = 1;
hangAfterHeaders = false;
@@ -308,6 +312,32 @@ describe('callRemoteTool — HTTP authentication boundaries', () => {
expect(toolExecutions).toBe(1);
});
+ test('a 401 naming access_member_disabled is relayed: the member is disabled, not the client revoked', async () => {
+ statusFor = current => current === 'tools/call' ? 401 : undefined;
+ rejectionBody = JSON.stringify({ error: 'invalid_token', code: 'access_member_disabled', message: 'This token is bound to a member who is disabled, removed or missing.' });
+ const error = await callRemoteTool(makeConfig(), 'write_example').then(() => null, (e: unknown) => e);
+ expect(error).toMatchObject({ reason: 'auth_after_refresh', detail: { status: 401, code: 'access_member_disabled' } });
+ expect((error as Error).message).toContain('bound to a member who is disabled, removed or missing');
+ expect(tokenMintCount).toBe(2);
+ expect(toolExecutions).toBe(0);
+ });
+
+ test('the OAuth host\'s own 401 body (error_description, no code key) is relayed as access_member_disabled', async () => {
+ statusFor = current => current === 'tools/call' ? 401 : undefined;
+ rejectionBody = JSON.stringify(new InvalidTokenError('access_member_disabled: this credential is bound to member "bob-example", which is disabled.').toResponseObject());
+ const error = await callRemoteTool(makeConfig(), 'write_example').then(() => null, (e: unknown) => e);
+ expect(error).toMatchObject({ reason: 'auth_after_refresh', detail: { status: 401, code: 'access_member_disabled' } });
+ expect(toolExecutions).toBe(0);
+ });
+
+ test('forwardRemoteToolCall relays access_member_disabled from the OAuth host\'s 401 body', async () => {
+ statusFor = current => current === 'tools/call' ? 401 : undefined;
+ rejectionBody = JSON.stringify(new InvalidTokenError('access_member_disabled: this credential is bound to member "bob-example", which is disabled.').toResponseObject());
+ const error = await forwardRemoteToolCall(makeConfig(), 'write_example', {}).then(() => null, (e: unknown) => e);
+ expect(error).toMatchObject({ reason: 'auth_after_refresh', detail: { status: 401, code: 'access_member_disabled' } });
+ expect(toolExecutions).toBe(0);
+ });
+
test('rejected token refresh stops before a second tool request', async () => {
statusFor = (stage, attempt) => stage === 'tools/call' ? 401 : stage === 'token' && attempt === 2 ? 401 : undefined;
await expect(callRemoteTool(makeConfig(), 'write_example')).rejects.toMatchObject({ reason: 'auth_after_refresh', detail: { status: 401 } });
diff --git a/test/remote-bridge-errors.test.ts b/test/remote-bridge-errors.test.ts
index 8acac0ce2f..07c98206cc 100644
--- a/test/remote-bridge-errors.test.ts
+++ b/test/remote-bridge-errors.test.ts
@@ -60,6 +60,7 @@ const CASES: Array<[string, RemoteMcpError, string]> = [
['rate_limited', new RemoteMcpError('rate_limited', 'slow down', { mcp_url: SECRET_URL }), 'rate_limited'],
['auth', new RemoteMcpError('auth', 'bad creds', { mcp_url: SECRET_URL }), 'invalid_client'],
['auth_after_refresh', new RemoteMcpError('auth_after_refresh', 'still 401', { mcp_url: SECRET_URL }), 'invalid_client'],
+ ['auth_after_refresh, member disabled', new RemoteMcpError('auth_after_refresh', 'member disabled', { mcp_url: SECRET_URL, status: 401, code: 'access_member_disabled' }), 'access_member_disabled'],
['network timeout', new RemoteMcpError('network', `timed out ${SECRET_URL}`, { mcp_url: SECRET_URL, kind: 'timeout' }), 'timeout'],
['network aborted', new RemoteMcpError('network', 'aborted', { mcp_url: SECRET_URL, kind: 'aborted' }), 'cancelled'],
['network unreachable', new RemoteMcpError('network', `ECONNREFUSED ${SECRET_URL}`, { mcp_url: SECRET_URL, kind: 'unreachable' }), 'unavailable'],