Files
gbrain/test/agent-voice-cors.serial.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

267 lines
11 KiB
TypeScript

/**
* #2477 — agent-voice reference server ships default-deny CORS, an Origin
* gate on the side-effectful POSTs, and a loopback-default bind.
*
* Spawns the real server (recipes/agent-voice/code/server.mjs) and asserts:
*
* 1. Default posture (no env): no Access-Control-Allow-Origin header is
* ever emitted; cross-origin POSTs to /session and /tool are rejected
* 403 BEFORE any work (proven by ordering: a no-Origin POST /session
* reaches the handler and 500s on the missing OPENAI_API_KEY instead).
* Same-origin requests (Origin host == Host header) pass the gate.
* 2. Allowlist posture (AGENT_VOICE_CORS_ORIGIN): exact-match origins get
* ACAO echo + Vary: Origin (+ preflight headers on OPTIONS) and pass
* the gate; everything else stays default-deny. Spaces around commas
* are trimmed.
*
* `.serial` suffix: binds TCP ports, runs in the serial pass.
* Pattern per test/admin-embed-spawn.serial.test.ts (spawn + /health poll +
* SIGTERM→SIGKILL cleanup). The default HOST bind (127.0.0.1) is covered
* implicitly — every request here reaches the server via 127.0.0.1.
*/
import { describe, test, expect } from 'bun:test';
import type { Subprocess } from 'bun';
import { join } from 'path';
const SERVER_SCRIPT = join(import.meta.dir, '..', 'recipes', 'agent-voice', 'code', 'server.mjs');
const EVIL = 'https://evil.example';
function pickPort(): number {
return 31000 + Math.floor(Math.random() * 4000);
}
interface VoiceServer {
port: number;
base: string;
proc: Subprocess<'ignore', 'pipe', 'pipe'>;
/** Accumulated stdout — carries the startup bind + CORS posture log lines. */
stdout: () => string;
}
async function spawnVoice(extraEnv: Record<string, string> = {}): Promise<VoiceServer> {
const port = pickPort();
const env: Record<string, string> = {
...(process.env as Record<string, string>),
PORT: String(port),
// The server starts without a key; /session 500s lazily — which the
// ordering assertions below rely on.
OPENAI_API_KEY: '',
};
// A developer's shell must not leak an allowlist or bind override into the
// default-deny spawn.
delete env.AGENT_VOICE_CORS_ORIGIN;
delete env.HOST;
Object.assign(env, extraEnv);
const proc = Bun.spawn([process.execPath, SERVER_SCRIPT], {
env,
stdin: 'ignore',
stdout: 'pipe',
stderr: 'pipe',
});
// Drain stdout in the background so the startup log lines are assertable.
let out = '';
(async () => {
try {
for await (const chunk of proc.stdout as ReadableStream<Uint8Array>) {
out += new TextDecoder().decode(chunk);
}
} catch { /* stream closed on shutdown */ }
})();
const base = `http://127.0.0.1:${port}`;
const deadline = Date.now() + 30_000;
while (Date.now() < deadline) {
try {
const res = await fetch(`${base}/health`, { signal: AbortSignal.timeout(2000) });
if (res.ok) return { port, base, proc, stdout: () => out };
} catch { /* not up yet */ }
await new Promise(r => setTimeout(r, 250));
}
proc.kill();
const stderr = await new Response(proc.stderr).text();
throw new Error(`agent-voice server did not become healthy in 30s\nstderr: ${stderr.slice(-800)}`);
}
async function stopVoice(server: VoiceServer): Promise<void> {
server.proc.kill('SIGTERM');
const graceful = await Promise.race([
server.proc.exited.then(() => true),
new Promise<false>(r => setTimeout(() => r(false), 2000)),
]);
if (!graceful) {
server.proc.kill('SIGKILL');
await server.proc.exited.catch(() => {});
}
}
describe('agent-voice CORS default-deny + origin gate (#2477)', () => {
test('default posture: no CORS headers, cross-origin side-effect POSTs 403 before any work', async () => {
const server = await spawnVoice();
try {
// No ACAO on a cross-origin read — the browser blocks the response.
const health = await fetch(`${server.base}/health`, { headers: { Origin: EVIL } });
expect(health.status).toBe(200);
expect(health.headers.get('access-control-allow-origin')).toBeNull();
expect(health.headers.get('vary') ?? '').not.toContain('Origin');
// Preflight still answers 204, but with no CORS headers it fails in
// the browser — the actual cross-origin request never fires.
const preflight = await fetch(`${server.base}/session`, {
method: 'OPTIONS',
headers: { Origin: EVIL, 'Access-Control-Request-Method': 'POST' },
});
expect(preflight.status).toBe(204);
expect(preflight.headers.get('access-control-allow-origin')).toBeNull();
expect(preflight.headers.get('access-control-allow-methods')).toBeNull();
// Origin gate: a "simple" cross-origin POST (no preflight in real
// browsers) is rejected before the handler runs.
const gated = await fetch(`${server.base}/session`, {
method: 'POST',
headers: { Origin: EVIL, 'Content-Type': 'text/plain' },
body: 'v=0',
});
expect(gated.status).toBe(403);
expect(await gated.text()).toContain('origin not allowed');
// Ordering proof: without an Origin header (curl / Twilio / native)
// the same request PASSES the gate and reaches the handler, which
// 500s on the missing OPENAI_API_KEY. 403 above therefore came from
// the gate, before any upstream spend could happen.
const noOrigin = await fetch(`${server.base}/session`, {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: 'v=0',
});
expect(noOrigin.status).toBe(500);
expect(await noOrigin.text()).toContain('OPENAI_API_KEY not set');
// Same-origin browser requests (Origin host == Host header) pass the
// gate — the served /call page keeps working with zero config.
const sameOrigin = await fetch(`${server.base}/session`, {
method: 'POST',
headers: { Origin: server.base, 'Content-Type': 'text/plain' },
body: 'v=0',
});
expect(sameOrigin.status).toBe(500); // handler reached, not 403
// Malformed Origin (unparseable by new URL()) must fail closed → 403,
// never fall through to the handler. A bypass here would be a real hole.
const malformed = await fetch(`${server.base}/session`, {
method: 'POST',
headers: { Origin: 'http://[::bogus', 'Content-Type': 'text/plain' },
body: 'v=0',
});
expect(malformed.status).toBe(403);
// /tool: gated identically (before the body is even read)…
const toolGated = await fetch(`${server.base}/tool`, {
method: 'POST',
headers: { Origin: EVIL, 'Content-Type': 'text/plain' },
body: 'not json',
});
expect(toolGated.status).toBe(403);
// …while a no-Origin caller reaches the handler (400 invalid_json).
const toolNoOrigin = await fetch(`${server.base}/tool`, {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: 'not json',
});
expect(toolNoOrigin.status).toBe(400);
} finally {
await stopVoice(server);
}
}, 90_000);
test('allowlist posture: exact-match origins get CORS headers and pass the gate; others stay denied', async () => {
// Space after the comma pins trimming.
const server = await spawnVoice({ AGENT_VOICE_CORS_ORIGIN: 'https://ok.example, https://two.example' });
try {
// Allowlisted origin: ACAO echoes the exact origin + Vary: Origin.
const ok = await fetch(`${server.base}/health`, { headers: { Origin: 'https://ok.example' } });
expect(ok.headers.get('access-control-allow-origin')).toBe('https://ok.example');
expect(ok.headers.get('vary') ?? '').toContain('Origin');
// Second (space-padded) entry works too — trimming pinned.
const two = await fetch(`${server.base}/health`, { headers: { Origin: 'https://two.example' } });
expect(two.headers.get('access-control-allow-origin')).toBe('https://two.example');
// Preflight from an allowlisted origin carries the method/header grants.
const preflight = await fetch(`${server.base}/session`, {
method: 'OPTIONS',
headers: { Origin: 'https://ok.example', 'Access-Control-Request-Method': 'POST' },
});
expect(preflight.status).toBe(204);
expect(preflight.headers.get('access-control-allow-origin')).toBe('https://ok.example');
expect(preflight.headers.get('access-control-allow-methods')).toContain('POST');
// Never credentialed, even when allowlisted.
expect(preflight.headers.get('access-control-allow-credentials')).toBeNull();
// Allowlisted origin passes the side-effect gate (handler reached).
const gatePass = await fetch(`${server.base}/session`, {
method: 'POST',
headers: { Origin: 'https://ok.example', 'Content-Type': 'text/plain' },
body: 'v=0',
});
expect(gatePass.status).toBe(500);
expect(await gatePass.text()).toContain('OPENAI_API_KEY not set');
// Exact match, not wildcard: unlisted origins stay fully denied.
const evil = await fetch(`${server.base}/health`, { headers: { Origin: EVIL } });
expect(evil.headers.get('access-control-allow-origin')).toBeNull();
const evilPost = await fetch(`${server.base}/session`, {
method: 'POST',
headers: { Origin: EVIL, 'Content-Type': 'text/plain' },
body: 'v=0',
});
expect(evilPost.status).toBe(403);
} finally {
await stopVoice(server);
}
}, 90_000);
// The loopback-default bind is the security-relevant half of #2477. A raw
// socket probe of a non-loopback interface is flaky in CI (no LAN IP,
// firewalls), so pin the HOST knob via the startup log the listen callback
// emits: default → 127.0.0.1, HOST override → honored.
async function readStartupLog(server: VoiceServer): Promise<string> {
const deadline = Date.now() + 3000;
while (Date.now() < deadline) {
if (server.stdout().includes('listening on')) break;
await new Promise(r => setTimeout(r, 50));
}
return server.stdout();
}
test('HOST default binds loopback (127.0.0.1)', async () => {
const server = await spawnVoice(); // HOST scrubbed from env → default
try {
const log = await readStartupLog(server);
expect(log).toContain(`listening on http://127.0.0.1:${server.port}`);
expect(log).toContain('bind: 127.0.0.1');
// The default log carries a "set HOST=0.0.0.0 to expose" hint, so the
// bind proof is the loopback URL above, not mere absence of "0.0.0.0".
expect(log).not.toContain('http://0.0.0.0');
} finally {
await stopVoice(server);
}
}, 90_000);
test('HOST override is honored (0.0.0.0 for containers/LAN)', async () => {
const server = await spawnVoice({ HOST: '0.0.0.0' });
try {
const log = await readStartupLog(server);
expect(log).toContain(`listening on http://0.0.0.0:${server.port}`);
// Still reachable via loopback when bound to all interfaces.
const health = await fetch(`${server.base}/health`);
expect(health.status).toBe(200);
} finally {
await stopVoice(server);
}
}, 90_000);
});