Files
gbrain/test/e2e/serve-http-consent.test.ts
Garry Tan 668b9bac30 v0.50.5.0 fix(security): critical+high advisory wave — DCR scope ceiling, cwd .env quarantine, format-based transcript redaction, consent pins (#5130)
* v0.50.2.0 fix(security): critical+high advisory wave — DCR scope ceiling, cwd .env quarantine, format-based transcript redaction, consent pins

Closes the critical- and high-severity items from six privately reported
advisories (GHSA-548g-mhxp-p66h, GHSA-42r8-3jfh-82vr, GHSA-62gp-q5hj-r9mv,
GHSA-q374-hhfh-f79x, GHSA-ghfq-gqmq-7fm4, GHSA-q5p9-qr3g-6v38). Squashed to a
single commit so no intermediate revision carries a test-fixture credential
shape through the gitleaks range gate.

Cluster A — OAuth consent gate (GHSA-548g / -42r8 / -62gp). The v0.50.0.0
owner-approval flow is pinned end to end against a real `serve --http
--enable-dcr` process and in-process: anonymous /authorize mints no code, a
forged code is rejected at /token, revoked clients are refused at grants.begin,
and OAuthGrants.begin() now caps awaiting-decision requests per client_id.

Cluster B — DCR scope ceiling (GHSA-q374 defect B, GHSA-548g fix #2).
registerClient rejects admin/sources_admin/users_admin/agent with HTTP 400 via
scope.ts:dcrScopeViolation; client_credentials DCR clients are read-only.
Remote sources_remove is source-fenced like sources_status. doctor's
oauth_client_scope_health flags privileged self-registered clients.

Cluster C — format-based secret detection (GHSA-ghfq). secret-scan.ts gains
jwt/aws(AKIA|ASIA)/google/stripe/sendgrid/twilio/supabase/gitlab/npm/hf plus
bearer and db_url_credentials catch-alls; the transcripts lane opts into the
digit-gated high-entropy rule; getRawData follows the page soft-delete on both
engines; delete_page --purge (local-CLI only) hard-removes a leaked page.

Cluster D — cwd .env quarantine (GHSA-q5p9). New env-trust.ts + cli-preflight.ts
drop a fixed list of code-loading / exec-target / posture-widening GBRAIN_*
variables when a working-directory .env assigns them (key-presence, since Bun
expands ${VAR}); the guardrails loader refuses cwd-relative and cwd-.env specs.

Release artifacts: VERSION/package.json/three plugin manifests bumped to
0.50.2.0; CHANGELOG entry (reporters credited); SECURITY.md, README, DEPLOY.md,
CHATGPT.md, guardrails.md, ENGINES.md and KEY_FILES updated; template + plugin
trees, skills.lock, flag registry and llms bundle regenerated; module-size
ceilings adjusted with per-row reasons; TODOS follow-ups filed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix: pre-landing review fixes (v0.50.2.0 security wave)

Review cycle 1 of the ship: 6 specialists + red team + coverage audit.

Security / red team:
- env-trust: parse .env with Bun's line grammar (bare CR terminates a line;
  BOM/U+2028 cannot hide an assignment); protect the loader / git / node /
  proxy / AI-CLI variable families a checkout could plant for the programs
  gbrain spawns; cli-preflight re-execs gbrain once with the sanitized
  environment so git, the agent CLI and workers inherit the clean view;
  cwd == ~/.gbrain no longer quarantines the operator's own .env.
- guardrails: GBRAIN_GUARDRAILS_MODULE accepts only absolute or ~/ paths
  (a package name resolves from the cwd's node_modules).
- secret-scan: bounded db_url_credentials quantifiers + per-pattern
  prechecks (linear on long lines), windowed previews that redact every
  sibling span, single-pass longest-first replacement.
- TODOS: follow-up entries reworded to the functional level.

API contract / maintainability:
- delete_page purge: remote callers get permission_denied; a purged
  response always carries write_through; get_raw_data description states
  the soft-delete follow; includeDeleted narrowed to the getRawData
  signature; client_credentials gate evaluated before the DCR ceiling;
  doctor privileged set derived from the scope registry; sources_remove /
  sources_status share assertSourceInCallerScope; shell-job opt-in reaches
  --job-isolation process children as --allow-shell-jobs; stale help copy.
- transcripts ingest: raw-metadata compare uses canonical JSON (JSONB key
  order made every healthy re-run rewrite unchanged rows).

Coverage audit: 5 new test files + 4 extended (25 cases), plus RED-verified
pins for every fix above. Docs/KEY_FILES/CHANGELOG/SECURITY updated; llms
bundle, flag registry, tool catalog, structural suites regenerated;
module-size rows adjusted with reasons.

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

* fix: pre-landing review fixes, cycle 2 (v0.50.2.0 security wave)

Re-exec redesign (security + red team + adversarial findings):
- cli-preflight re-runs gbrain from an empty temporary directory so the
  sanitized child never reloads the hostile .env: dropped keys are absent,
  never carried as '' (git and the dynamic loader presence-check
  GIT_SSL_NO_VERIFY / LD_TRACE_LOADED_OBJECTS; '' broke git ident).
- The re-run marker is JSON {cwd, neutral} honoured only when the process
  provably started in that empty directory — a marker planted via a cwd
  .env is ignored (the ppid-keyed marker was forgeable under systemd/docker).
- SIGINT is delivered by the tty once (wrapper no longer forwards it);
  SIGTERM/SIGHUP forwarded; execArgv preserved under the dev runtime.
- Protected families widened: XDG config roots (git reads
  $XDG_CONFIG_HOME/git/config as global config), GNUPGHOME, TLS trust
  stores, EDITOR/VISUAL/PAGER, every provider endpoint variable, the
  GBRAIN_REMOTE_* / GBRAIN_DIRECT_DATABASE_URL redirects, and the marker.
- cwd dotenv parsed once per start; jobs start uses the same '1' literal.

secret-scan (cycle-2 findings):
- db_url_credentials password class only stops at whitespace, '@' and
  string delimiters again (unescaped / { } < > | ^ ` \ passwords redact);
  BEARER uppercase recognized; jwt / high_entropy_assignment / PEM body
  bounded (adversarial '-eyJ' / '_token' runs and header-only PEM texts
  were quadratic); incremental PEM line cursor; redactFindings rebuilds
  the text by span-splice in one pass (was O(unique values x text)).

Contract / docs:
- delete_page purge responses carry a residuals hint (git history, exports,
  compiled context, slug-keyed derived rows); CHANGELOG states a single
  truth for GBRAIN_GUARDRAILS_MODULE (absolute or ~/ only, listed under
  Changed with a migration note); SECURITY.md / KEY_FILES / docs guides /
  minion-orchestrator skill describe the new mechanism and the
  --allow-shell-jobs opt-in; TODOS follow-ups filed; test-reads-source
  marker on the hook spawn-shape test; new PEM fixtures fragmented.

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

* fix: pre-landing review fixes, cycle 3 (v0.50.2.0 security wave)

- Compiled binaries: every `bun build --compile` invocation passes
  `--no-compile-autoload-bunfig`; new `scripts/check-compile-autoload.sh`
  guard (self-tested, in verify CHECKS) keeps it that way.
- cwd `.env` quarantine: `GBRAIN_DATABASE_URL`, `GBRAIN_OAUTH_RELAY_URL`,
  OpenSSL config/engine/module loaders, temp roots and HOME/USERPROFILE
  join the protected set; the neutral hop dir is realpath'd; signal
  handlers are installed before the spawn; non-tty wrappers forward SIGINT
  once; guardrails fail closed when a dropped GBRAIN_GUARDRAILS_MODULE had
  a value.
- secret-scan: PEM header-line cursor is O(text) on newline-free tails;
  bounded bearer echo pass redacts bare re-occurrences of claimed tokens.
- transcripts ingest: raw-metadata probe reads active rows only.
- Tests: afterAll cleanup, execArgv/SIGHUP/chdir-back pins, pty SIGINT,
  perf pins; docs/CHANGELOG/TODOS/KEY_FILES/SECURITY updated; llms +
  skills.lock + plugin trees regenerated.

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

* fix: pre-landing review fixes, cycle 4 (v0.50.2.0 security wave)

Cross-model adversarial pass (Codex) + Claude verifier findings:
- env-trust: shell-startup / interpreter-home family (BASH_ENV, SHELLOPTS,
  PS4, BASHOPTS, PROMPT_COMMAND, ZDOTDIR, PYTHONHOME, PERLLIB, GCONV_PATH,
  BASH_FUNC_* prefix) protected; sh `ENV` deliberately excluded.
- cli-preflight: config-dir exemption refused when the cwd .env assigns
  GBRAIN_HOME/HOME/USERPROFILE; wrapper removes pre-existing signal
  listeners so its exit is always the child's; SIGINT forwarded only
  without a controlling terminal (/dev/tty probe); a dropped planted HOME
  is restored from the passwd home; script-mode runs warn once when the
  cwd bunfig.toml declares a top-level preload.
- secret-scan: overlapping matches redact the UNION of matched spans;
  echo pass covers bearer + high-entropy values (64 unique, <=512 chars)
  via per-value sweeps over unclaimed gaps only; planRedaction/
  applyRedaction share a session-wide echo dictionary in transcripts
  render.
- sources_remove keys on write authority (assertSourceInCallerWriteScope);
  federated read grants confer no removal right.
- delete_page --purge retries the tombstone's file removal and fails
  closed (storage_error) while the file remains.
- Docs: SECURITY.md quarantine example no longer uses the one key that
  refuses instead of re-running; KEY_FILES/CHANGELOG/TODOS updated; llms.

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

* v0.50.3.0 chore: re-bump the security wave to 0.50.3.0 (master claimed 0.50.2.0 in #5122)

Five-file lockstep + BOOTSTRAP stamp + CHANGELOG header/date + TODOS
follow-up refs + bun.lock, template repo and plugin trees regenerated.

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

* fix: pre-landing review fixes, cycle 5 — Codex structured-review gate (v0.50.3.0 security wave)

- cli-preflight: hop marker carries the wrapper pid; a verified re-run arms
  an unref'd 1 s watchdog and exits 137 (removing its neutral dir) when the
  wrapper is force-killed, so supervisor restarts never orphan a worker;
  relative path-bearing runtime flags (--preload/-r/--require/--import,
  --config/-c, --env-file, --tsconfig-override) are resolved against the
  original cwd before the hop.
- secret-scan: echo pass is a streaming leftmost-longest merge with O(values)
  retained state (Codex repro: 64 short claims + 2 MiB repetitive tail went
  from +233 MiB RSS / 1.4 s to +16 MiB / 140 ms); repetitive tails are now
  covered wall-to-wall.
- Docs: KEY_FILES, SECURITY.md, CHANGELOG; llms regenerated.

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

* docs: update project documentation for v0.50.3.0

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

* fix(ci): green the three failing checks on the v0.50.3.0 wave

- semgrep: six `nosemgrep` suppressions with justifications for the
  path-join/resolve and non-literal-RegExp taint heuristics on operator-
  controlled cwd/flag paths and compile-time pattern sources (no behaviour
  change).
- test (2): the two pty Ctrl-C pins ran the wrapper through `script -c`'s
  intermediate /bin/sh; on ubuntu-latest that is dash, which re-raises the
  pty's SIGINT on itself after the child exits (130) instead of relaying
  the child's 42. The pty command now `exec`s the wrapper so no shell stays
  in the foreground group; documented in a `ptyCommand` helper.
- Selected E2E: with --enable-dcr, OAuth discovery now advertises exactly
  the self-registration ceiling (`read write`) via
  `scopesSupportedForDiscovery`, so a connector that copies
  `scopes_supported` into /register succeeds (master's #5122 pin); without
  DCR the full operator list minus `agent` is unchanged. Sibling e2e
  assertions that expected privileged scopes on the DCR-enabled server
  updated; unit + PGLite e2e pins added; docs/TODOS/CHANGELOG/KEY_FILES
  updated; llms regenerated.

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

* v0.50.5.0 chore: re-bump the security wave to 0.50.5.0 (master claimed 0.50.4.0 in #5131)

Five-file lockstep + BOOTSTRAP stamp + CHANGELOG header + TODOS follow-up
refs + bun.lock, template repo and plugin trees regenerated.

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-15 21:40:59 -07:00

169 lines
11 KiB
TypeScript

/** Full production admin/login/consent route wiring on an isolated in-memory brain. */
import { afterAll, beforeAll, expect, test } from 'bun:test';
import { mkdtempSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createServer } from 'node:net';
import { spawn, type ChildProcess } from 'node:child_process';
import { TEST_PKCE_CHALLENGE, TEST_PKCE_VERIFIER } from '../helpers/oauth.ts';
let child: ChildProcess;
let home: string;
let base: string;
// ONE admin login for the whole file (the shared admin auth limiter is
// 10/min/IP and the consent routes draw from the same bucket), taken in
// beforeAll so every test is order-independent. `adminSetCookie` keeps the
// raw header for the attribute assertions.
let adminCookie = '';
let adminSetCookie = '';
const BOOTSTRAP = 'synthetic-consent-admin-test-token';
beforeAll(async () => {
home = mkdtempSync(join(tmpdir(), 'gbrain-consent-test-'));
const probe = createServer();
await new Promise<void>(resolve => probe.listen(0, '127.0.0.1', resolve));
const address = probe.address();
if (!address || typeof address === 'string') throw new Error('Expected TCP address');
await new Promise<void>((resolve, reject) => probe.close(err => err ? reject(err) : resolve()));
base = `http://127.0.0.1:${address.port}`;
child = spawn(process.execPath, [join(import.meta.dir, '../fixtures/oauth-consent-server.ts')], {
cwd: join(import.meta.dir, '../..'),
env: { ...process.env, NODE_ENV: 'test', GBRAIN_HOME: home, DATABASE_URL: '', GBRAIN_DATABASE_URL: '',
GBRAIN_TEST_HTTP_PORT: String(address.port), GBRAIN_ADMIN_BOOTSTRAP_TOKEN: BOOTSTRAP },
stdio: ['ignore', 'pipe', 'pipe'],
});
let output = '';
child.stderr?.on('data', chunk => { output += chunk.toString(); });
child.stdout?.on('data', chunk => { output += chunk.toString(); });
let up = false;
for (let attempt = 0; attempt < 150 && !up; attempt++) {
if (child.exitCode !== null) throw new Error(`Consent server exited: ${output.slice(-2000)}`);
try { up = (await fetch(`${base}/health`)).ok; } catch { /* starting */ }
if (!up) await Bun.sleep(100);
}
if (!up) throw new Error(`Consent server did not start: ${output.slice(-2000)}`);
const login = await fetch(`${base}/admin/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: BOOTSTRAP }) });
if (login.status !== 200) throw new Error(`admin login failed: ${login.status}`);
adminSetCookie = login.headers.get('set-cookie') ?? '';
adminCookie = adminSetCookie.split(';')[0];
}, 30_000);
afterAll(async () => {
if (child && child.exitCode === null) {
const exited = new Promise<void>(resolve => child.once('exit', () => resolve()));
child.kill('SIGTERM');
await Promise.race([exited, Bun.sleep(5000)]);
if (child.exitCode === null && child.signalCode === null) { child.kill('SIGKILL'); await exited; }
}
if (home) rmSync(home, { recursive: true, force: true });
});
test('login, magic-link recovery, consent authentication and single-use approval are wired in the real server', async () => {
const registration = await fetch(`${base}/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({
client_name: 'synthetic consent client', redirect_uris: [`${base}/callback`], grant_types: ['authorization_code', 'refresh_token'], scope: 'read write', token_endpoint_auth_method: 'none',
}) });
expect(registration.status).toBe(201);
const client = await registration.json() as any;
const query = new URLSearchParams({ client_id: client.client_id, response_type: 'code', redirect_uri: `${base}/callback`, code_challenge: TEST_PKCE_CHALLENGE, code_challenge_method: 'S256', scope: 'read write', state: 'synthetic-state' });
const authorization = await fetch(`${base}/authorize?${query}`, { redirect: 'manual' });
const pendingUrl = new URL(authorization.headers.get('location')!, base);
expect(pendingUrl.pathname).toBe('/admin/');
expect(pendingUrl.searchParams.has('code')).toBe(false);
const id = pendingUrl.searchParams.get('oauth_request')!;
expect((await fetch(pendingUrl)).status).toBe(200); // unauthenticated page shell
expect((await fetch(`${base}/admin/api/oauth-requests/${id}`)).status).toBe(401);
expect(adminCookie).not.toBe('');
const oldCookie = adminCookie; // the beforeAll login session
expect(adminSetCookie).toContain('SameSite=Strict');
const oldDetails = await (await fetch(`${base}/admin/api/oauth-requests/${id}`, { headers: { Cookie: oldCookie } })).json() as any;
const magic = await fetch(`${base}/admin/api/issue-magic-link`, { method: 'POST', headers: { Authorization: `Bearer ${BOOTSTRAP}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ oauth_request: id, return_url: 'https://untrusted.example' }) });
expect(magic.status).toBe(200);
const magicUrl = (await magic.json() as any).url.replace(`http://localhost:${new URL(base).port}`, base);
const redemption = await fetch(magicUrl, { redirect: 'manual' });
expect(redemption.status).toBe(302);
expect(redemption.headers.get('location')).toBe(`/admin/?oauth_request=${id}#oauth-consent`);
const newCookie = redemption.headers.get('set-cookie')!.split(';')[0];
expect(newCookie).not.toBe(oldCookie);
const endpoint = `${base}/admin/api/oauth-requests/${id}`;
const headers = { Cookie: newCookie, 'Content-Type': 'application/json' };
expect((await fetch(endpoint, { method: 'POST', headers, body: JSON.stringify({ decision: 'approve', csrf: oldDetails.csrf }) })).status).toBe(403);
const details = await (await fetch(endpoint, { headers })).json() as any;
expect(details.clientName).toBe('synthetic consent client');
const approved = await fetch(endpoint, { method: 'POST', headers, body: JSON.stringify({ decision: 'approve', csrf: details.csrf }) });
expect(approved.status).toBe(200);
const redirect = new URL((await approved.json() as any).redirectUrl);
expect(redirect.origin).toBe(base);
expect(redirect.searchParams.get('state')).toBe('synthetic-state');
expect(redirect.searchParams.get('code')).toStartWith('gbrain_code_');
expect((await fetch(endpoint, { method: 'POST', headers, body: JSON.stringify({ decision: 'approve', csrf: details.csrf }) })).status).toBe(410);
}, 15_000);
/** Anonymous self-registration with a foreign redirect_uri: no code without the owner, forged codes do not redeem, revocation closes /authorize. */
test('a self-registered public client cannot obtain or redeem a code without owner approval', async () => {
const foreignRedirect = 'https://client-example.invalid/cb';
const register = async (body: Record<string, unknown>) => {
const response = await fetch(`${base}/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({
client_name: 'synthetic self-registered client', redirect_uris: [foreignRedirect], token_endpoint_auth_method: 'none', ...body }) });
expect(response.status).toBe(201);
return response.json() as Promise<any>;
};
const authorize = async (clientId: string, scope?: string) => {
const query = new URLSearchParams({ client_id: clientId, response_type: 'code', redirect_uri: foreignRedirect, code_challenge: TEST_PKCE_CHALLENGE, code_challenge_method: 'S256', state: 'attacker-state' });
if (scope !== undefined) query.set('scope', scope);
return fetch(`${base}/authorize?${query}`, { redirect: 'manual' });
};
const expectPending = async (clientId: string, scope?: string) => {
const response = await authorize(clientId, scope);
expect(response.status).toBe(302);
const location = new URL(response.headers.get('location')!, base);
expect(location.pathname).toBe('/admin/');
expect(location.searchParams.has('code')).toBe(false);
return location.searchParams.get('oauth_request')!;
};
// grant_types omitted: the default is the consent-bearing authorization_code flow.
const client = await register({ scope: 'read write' });
expect(client.client_secret).toBeUndefined();
await expectPending(client.client_id, 'read write');
const forged = await fetch(`${base}/token`, { method: 'POST', body: new URLSearchParams({
grant_type: 'authorization_code', code: 'gbrain_code_' + 'a'.repeat(43), code_verifier: TEST_PKCE_VERIFIER,
client_id: client.client_id, redirect_uri: foreignRedirect }) });
expect(forged.status).toBe(400);
expect((await forged.json() as any).error).toBe('invalid_grant');
// scope omitted: nothing is registered and the consent request carries no scopes (one consent GET).
const unscoped = await register({ grant_types: ['authorization_code'] });
expect(unscoped.scope ?? '').toBe('');
const id = await expectPending(unscoped.client_id);
const details = await fetch(`${base}/admin/api/oauth-requests/${id}`, { headers: { Cookie: adminCookie } });
expect(details.status).toBe(200);
expect((await details.json() as any).scopes).toEqual([]);
// Revoked self-registered client: /authorize is refused before any consent request exists.
const revoked = await fetch(`${base}/admin/api/revoke-client`, { method: 'POST', headers: { Cookie: adminCookie, 'Content-Type': 'application/json' }, body: JSON.stringify({ clientId: client.client_id }) });
expect(revoked.status).toBe(200);
const refused = await authorize(client.client_id, 'read write');
expect(refused.status).toBe(400);
expect((await refused.json() as any).error).toBe('invalid_client');
}, 15_000);
/** With self-registration on, discovery advertises exactly what a self-registering client may request — and a client that copies it registers. */
test('OAuth discovery advertises the self-registration ceiling and a client that copies it registers', async () => {
const metadata = await (await fetch(`${base}/.well-known/oauth-authorization-server`)).json() as any;
expect(metadata.scopes_supported).toEqual(['read', 'write']);
expect(new URL(metadata.registration_endpoint).pathname).toBe('/register');
const register = (scope: string) => fetch(`${base}/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({
client_name: 'synthetic discovered-scopes client', redirect_uris: ['https://client-example.invalid/cb'], grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'], token_endpoint_auth_method: 'none', scope }) });
const response = await register(metadata.scopes_supported.join(' '));
expect(response.status).toBe(201);
const client = await response.json() as any;
expect(client.scope.split(' ')).toEqual(metadata.scopes_supported);
for (const path of ['/.well-known/oauth-protected-resource/mcp', '/.well-known/oauth-protected-resource']) {
const resource = await (await fetch(`${base}${path}`)).json() as any;
expect(resource.scopes_supported).toEqual(metadata.scopes_supported);
}
// Narrowed discovery does not loosen the ceiling: an explicit privileged request is still refused.
const refused = await register('read write admin');
expect(refused.status).toBe(400);
expect((await refused.json() as any).error).toBe('invalid_client_metadata');
}, 15_000);