Files
gbrain/test/e2e/serve-http-takes-holders.test.ts
T
Garry TanandClaude Fable 5 a948dfd6e2 v0.42.74.0 fix(security): honor takes_holders over serve --http + agent-voice default-deny CORS (#2529 #2477) (#3868)
* fix(auth): honor permissions.takes_holders for legacy bearer tokens over serve --http (#2529)

The OAuth provider's legacy access_tokens branch parsed permissions.source_id
but never read permissions.takes_holders, so the /mcp dispatch site's
fail-closed default pinned every remote caller to world-only takes visibility
— set-takes-holders was a silent no-op over serve --http, in both directions
(grants above world never applied; restrictions below world didn't either).

- src/core/legacy-token-scope.ts: new parseTakesHoldersAllowList shared by
  BOTH transports (the drift between the legacy HTTP transport's correct
  inline parse and the OAuth provider is how this bug shipped). [] preserved
  as explicit deny-all; non-array → undefined → consumer defaults ['world'].
- src/core/operations.ts: AuthInfo.takesHoldersAllowList typed field
  (same ride-along as sourceId/allowedSources).
- src/core/oauth-provider.ts: legacy branch threads the stored grant.
  OAuth-client tokens unchanged (no per-client storage — TODO filed).
- src/mcp/http-transport.ts: converged on the shared helper (behavior no-op).
- src/commands/serve-http.ts: sidecar cast replaced by the typed field.
- src/core/facts/meta-hook.ts: hashAllowList gives [] its own cache key
  (cache identity only — payload filtering stays visibility-based).

Tests: 7 verifyAccessToken cases (grant/absent/garbage/deny-all/mixed/
oauth-client/column-default), pure-helper describe, meta-hook cache-key pin,
and a Postgres e2e (test/e2e/serve-http-takes-holders.test.ts) pinning the
issue repro end-to-end over POST /mcp — the seam that had no coverage.

Reported by @Derek95king.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(agent-voice): default-deny CORS + origin gate + loopback bind in reference server (#2477)

The recipe reference server reflected any Origin into
Access-Control-Allow-Origin on every route, including the unauthenticated
side-effectful POSTs. Recipe is install_kind: copy-into-host-repo, so the
reference is the source of truth for every future install.

- Default-deny CORS: headers emitted only for exact matches against the new
  AGENT_VOICE_CORS_ORIGIN allowlist (comma-separated), with Vary: Origin;
  Allow-Credentials never set. Same-origin /call needs no configuration.
- Origin gate on /session and /tool: CORS headers gate response reads, not
  request sends — a no-preflight "simple" cross-origin POST still executes.
  Disallowed Origins now 403 before any body read / upstream fetch / tool
  dispatch. No-Origin callers (curl, Twilio, native) and same-origin pages
  (Origin host == Host, tunnels included) pass. DNS rebinding stays a
  documented production-checklist item (TODO filed).
- Loopback-default bind: HOST env, default 127.0.0.1 (mirrors gbrain
  serve --http --bind default); HOST=0.0.0.0 for containers/LAN.
- Startup log prints the bind + CORS posture; recipe md + install manifest
  bumped to 0.1.1 with the production checklist rewritten to match.

Tests: test/agent-voice-cors.serial.test.ts spawns the real server twice and
pins default-deny, allowlist echo + trimming, preflight behavior, and the
gate's ordering (evil-origin 403 vs no-origin reaching the handler).

Reported by @sebastiondev.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test: agent-voice origin gate fails closed on malformed Origin (#2477)

Coverage-audit follow-up: a cross-origin POST with an unparseable Origin
header must 403 (new URL() throws → originAllowed returns false), never
fall through to the handler. A bypass here would defeat the gate.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test: pin loopback-bind default + wire-level fail-closed takes default (#2529 #2477)

Pre-landing review (testing specialist) flagged two revert-catching gaps:

- #2477 HOST default (127.0.0.1) had no assertion — a regression to
  all-interfaces would pass every test. Capture the server's startup log
  and assert the loopback bind; add a HOST=0.0.0.0 override case.
- #2529 serve-http `?? ['world']` default branch was only unit-covered.
  Add a 4th e2e case: a legacy token with no takes_holders key sees
  world-held takes but NOT brain-held ones over POST /mcp, pinning the
  fail-closed default end-to-end. Also assert the deny-all case returns a
  successful (non-error) tool result so the negatives can't pass vacuously.

Verified: agent-voice 4/4, serve-http-takes-holders e2e 4/4 (real Postgres).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(auth): shared permissions decode + collision-free hot-memory cache key (#2529)

Adversarial-review hardening on the #2529 fix:

- The two transports shared parseTakesHoldersAllowList but still decoded the
  permissions column differently: the OAuth provider JSON.parse'd a
  string-typed value, the legacy HTTP transport didn't. On a double-encoded
  jsonb string scalar (#2339 class) a deny-all token would fail open to
  ['world'] on the HTTP transport while the provider honored it. Extract
  coerceLegacyPermissions into the shared module and route both through it, so
  "the two transports cannot drift" is literally true (shared decode + shared
  parse). Arrays/scalars/malformed strings → undefined (no grant).
- hashAllowList used bare sentinels ('_' for undefined, '(empty)' for []),
  which collided with real holder values ['_'] and ['(empty)']. Encode
  collision-free (undefined → 'none', else JSON.stringify(sorted)) so the
  []-vs-undefined cache separation the #2529 change relies on holds for every
  holder value.

Tests: coerceLegacyPermissions unit cases (object/JSON-string/malformed/
array/scalar), all existing takes-holders + meta-hook + e2e suites green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* v0.42.74.0 fix(security): honor takes_holders over serve --http + agent-voice default-deny CORS (#2529 #2477)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: document agent-voice HOST + AGENT_VOICE_CORS_ORIGIN env vars in install hint (v0.42.74.0)

The post-install hint's env-var quick-start predated the #2477 hardening and
listed neither the loopback-default HOST bind nor the default-deny
AGENT_VOICE_CORS_ORIGIN allowlist. Add both as optional entries (safe by
default) and refresh the stale startup-log line to match the server's actual
loopback-bind output.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: correct CHANGELOG command guidance + TODOS filing version (#2529 #2477)

Ship-stage document-release caught two wrong CLI invocations in the v0.42.74.0
CHANGELOG "To take advantage" block: `gbrain auth permissions <token>` has no
read-only view form (that shape errors + exits 1 — set the scope directly with
`set-takes-holders <values>`), and `integrations install agent-voice --refresh`
requires `--target <host-repo>`. Also correct the follow-ups TODO header from
the plan's stale v0.42.56.0 guess to the actual ship version v0.42.74.0.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(deps): bump js-yaml to 3.15.1 — osv GHSA-5p4m-2wfm-xmqj (#2529 #2477)

osv-scan flagged js-yaml@3.15.0 (High, CVSS 7.5), fixed in 3.15.1. The
transitive copy (gray-matter → js-yaml) was pinned to ^3.15.0 by the
package.json `overrides` block; bump both the direct dependency and the
override to ^3.15.1 so the vulnerable version is gone from bun.lock entirely
(gray-matter/js-yaml now resolves to 3.15.1). Patch bump, in-range, frontmatter
parsing verified (markdown + frontmatter + import + oauth suites green).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(deps): bump admin nanoid to 3.3.18 — osv GHSA-2v37-7h3g-55p8 (#2529 #2477)

osv-scan flagged nanoid@3.3.16 (High, CVSS 8.2) in admin/bun.lock, fixed in
3.3.17. nanoid is transitive (postcss → nanoid), so pin it in the admin
overrides block; refresh resolves to 3.3.18 (latest patched 3.x). Admin SPA
build verified green; both root and admin lockfiles now scan clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 15:31:53 -07:00

190 lines
7.9 KiB
TypeScript

/**
* E2E regression for #2529: `serve --http` honors a legacy bearer token's
* stored `access_tokens.permissions.takes_holders` grant end-to-end.
*
* The seam under test — verifyAccessToken (oauth-provider.ts legacy branch)
* → AuthInfo.takesHoldersAllowList → /mcp dispatch → engine holder filter —
* had NO end-to-end pin before this file; that absence is how #2529 shipped
* (the OAuth provider never read the grant, so every remote caller was
* pinned to ['world'] regardless of what the operator configured).
*
* Spins up a real `gbrain serve --http` against real Postgres, seeds a page
* with a brain-held and a world-held take, inserts legacy tokens with three
* different grants directly (the same rows `gbrain auth create/permissions`
* writes), and asserts `takes_list` over POST /mcp filters per grant:
*
* ['world','brain'] → sees both takes
* ['world'] → world take only (brain take invisible)
* [] → explicit deny-all: sees neither
*
* Run: DATABASE_URL=... bun test test/e2e/serve-http-takes-holders.test.ts
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { setupDB, teardownDB, getConn, hasDatabase } from './helpers.ts';
import { importFromContent } from '../../src/core/import-file.ts';
import { hashToken, generateToken } from '../../src/core/utils.ts';
const skip = !hasDatabase();
const describeE2E = skip ? describe.skip : describe;
if (skip) {
console.log('Skipping E2E serve-http-takes-holders tests (DATABASE_URL not set)');
}
const PORT = 19141; // unique per e2e file — avoid collision with serve-http-oauth (19131)
const BASE = `http://localhost:${PORT}`;
const BRAIN_CLAIM = 'brain-held regression claim for issue 2529';
const WORLD_CLAIM = 'world-held regression claim for issue 2529';
describeE2E('serve --http honors permissions.takes_holders for legacy bearer tokens (#2529)', () => {
let serverProcess: ReturnType<typeof import('child_process').spawn> | null = null;
let fullToken: string;
let worldToken: string;
let denyAllToken: string;
let noGrantToken: string;
async function insertLegacyToken(name: string, takesHolders: string[]): Promise<string> {
const token = generateToken('gbrain_');
const conn = getConn();
await conn.unsafe(
`INSERT INTO access_tokens (id, name, token_hash, permissions)
VALUES (gen_random_uuid(), $1, $2, $3::text::jsonb)`,
[name, hashToken(token), JSON.stringify({ takes_holders: takesHolders })],
);
return token;
}
// A token whose permissions carry NO takes_holders key — the shape an
// OAuth-client token or a pre-`set-takes-holders` legacy token has. The
// dispatch site must coalesce the undefined grant to the fail-closed
// ['world'] default over the wire (serve-http.ts `?? ['world']`).
async function insertNoGrantToken(name: string): Promise<string> {
const token = generateToken('gbrain_');
await getConn().unsafe(
`INSERT INTO access_tokens (id, name, token_hash, permissions)
VALUES (gen_random_uuid(), $1, $2, '{}'::jsonb)`,
[name, hashToken(token)],
);
return token;
}
beforeAll(async () => {
const engine = await setupDB();
const conn = getConn();
// access_tokens is not in helpers' truncate list — clear prior runs' rows
// so the unique name constraint can't collide.
await conn.unsafe(`DELETE FROM access_tokens WHERE name LIKE 'takes-e2e-%'`);
// Seed a page + two takes (one per holder tier).
await importFromContent(engine, 'e2e/takes-regression', '# Takes Regression\n\nSeed page for #2529.', { noEmbed: true });
const [page] = await conn.unsafe(`SELECT id FROM pages WHERE slug = 'e2e/takes-regression'`);
await engine.addTakesBatch([
{ page_id: page.id as number, row_num: 1, claim: BRAIN_CLAIM, kind: 'take', holder: 'brain', weight: 0.75, active: true, superseded_by: null },
{ page_id: page.id as number, row_num: 2, claim: WORLD_CLAIM, kind: 'take', holder: 'world', weight: 0.5, active: true, superseded_by: null },
]);
// Legacy bearer tokens with three grant shapes — the same permissions
// rows `gbrain auth create --takes-holders` / `set-takes-holders` write.
fullToken = await insertLegacyToken('takes-e2e-full', ['world', 'brain']);
worldToken = await insertLegacyToken('takes-e2e-world', ['world']);
denyAllToken = await insertLegacyToken('takes-e2e-denyall', []);
noGrantToken = await insertNoGrantToken('takes-e2e-nogrant');
// Start the HTTP server (same pattern as serve-http-oauth.test.ts).
const { spawn } = await import('child_process');
serverProcess = spawn('bun', [
'run', 'src/cli.ts', 'serve', '--http',
'--port', String(PORT),
'--public-url', `http://localhost:${PORT}`,
], {
cwd: process.cwd(),
env: process.env,
stdio: ['ignore', 'pipe', 'pipe'],
});
let stderr = '';
serverProcess.stderr?.on('data', (d: Buffer) => { stderr += d.toString(); });
let ready = false;
for (let i = 0; i < 30; i++) {
try {
const res = await fetch(`${BASE}/health`);
if (res.ok) { ready = true; break; }
} catch {}
await new Promise(r => setTimeout(r, 500));
}
if (!ready) throw new Error('Server failed to start within 15s.\nstderr: ' + stderr.slice(-500));
}, 60_000);
afterAll(async () => {
if (serverProcess) {
serverProcess.kill('SIGTERM');
await new Promise(r => setTimeout(r, 1000));
if (!serverProcess.killed) serverProcess.kill('SIGKILL');
}
try {
await getConn().unsafe(`DELETE FROM access_tokens WHERE name LIKE 'takes-e2e-%'`);
} catch (e: any) {
// eslint-disable-next-line no-console
console.error(`[afterAll] token cleanup failed: ${e.message}`);
}
await teardownDB();
}, 30_000);
async function takesListBody(token: string): Promise<string> {
const res = await fetch(`${BASE}/mcp`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream',
},
body: JSON.stringify({
jsonrpc: '2.0', id: 1, method: 'tools/call',
params: { name: 'takes_list', arguments: {} },
}),
});
expect(res.status).not.toBe(401);
return res.text();
}
// The MCP transport can answer as JSON or SSE (text/event-stream). Assert
// the body carries a successful tool result, not a JSON-RPC error envelope,
// so a negative-only content check can't pass vacuously on a broken pipeline.
function expectToolResultOk(body: string): void {
expect(body).toContain('"result"');
expect(body).not.toContain('"error"');
}
test("['world','brain'] grant sees the brain-held take (the #2529 repro)", async () => {
const body = await takesListBody(fullToken);
expect(body).toContain(BRAIN_CLAIM);
expect(body).toContain(WORLD_CLAIM);
}, 15_000);
test("['world'] grant sees only world-held takes — brain take stays invisible", async () => {
const body = await takesListBody(worldToken);
expect(body).toContain(WORLD_CLAIM);
expect(body).not.toContain(BRAIN_CLAIM);
}, 15_000);
test('[] grant is explicit deny-all — sees neither take (not silently world)', async () => {
const body = await takesListBody(denyAllToken);
expectToolResultOk(body); // a successful empty result, not an error envelope
expect(body).not.toContain(BRAIN_CLAIM);
expect(body).not.toContain(WORLD_CLAIM);
}, 15_000);
test('no takes_holders grant → fail-closed to world-only over the wire (?? default)', async () => {
// Pins serve-http.ts `authInfo.takesHoldersAllowList ?? ['world']`: an
// undefined grant (OAuth clients, pre-set-takes-holders legacy tokens)
// must see world-held takes and NOT brain-held ones through /mcp dispatch.
const body = await takesListBody(noGrantToken);
expect(body).toContain(WORLD_CLAIM);
expect(body).not.toContain(BRAIN_CLAIM);
}, 15_000);
});