* 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>
478 lines
21 KiB
TypeScript
478 lines
21 KiB
TypeScript
/**
|
|
* E2E: gstack /setup-gbrain Path 4 unblock — register a remote source over
|
|
* HTTP MCP, sync it, recover from clone deletion.
|
|
*
|
|
* Spawns a real `gbrain serve --http` against real Postgres with a fake-git
|
|
* binary in PATH (so `git clone` is exercised end-to-end without network),
|
|
* registers a sources_admin-scoped OAuth client, mints a token, calls
|
|
* sources_add via /mcp, asserts the source row + clone exist, then rm-rfs
|
|
* the clone and asserts the auto-recovery branch in performSync re-clones.
|
|
*
|
|
* Run: GBRAIN_DATABASE_URL=... bun test test/e2e/sources-remote-mcp.test.ts
|
|
*/
|
|
|
|
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
|
|
import { mkdirSync, writeFileSync, rmSync, chmodSync, existsSync } from 'fs';
|
|
import { join } from 'path';
|
|
import { tmpdir } from 'os';
|
|
import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
|
|
|
|
const skip = !hasDatabase();
|
|
const describeE2E = skip ? describe.skip : describe;
|
|
|
|
if (skip) {
|
|
console.log('Skipping E2E sources-remote-mcp tests (DATABASE_URL not set)');
|
|
}
|
|
|
|
const PORT = 19132; // Avoid collisions with other E2E tests
|
|
const BASE = `http://localhost:${PORT}`;
|
|
|
|
const FIXTURE_DIR = join(tmpdir(), `gbrain-e2e-sources-${process.pid}`);
|
|
const GBRAIN_HOME = join(FIXTURE_DIR, 'gbrain-home');
|
|
const FAKE_GIT_DIR = join(FIXTURE_DIR, 'fake-git');
|
|
const TEST_URL = 'https://github.com/example-org/test-repo';
|
|
|
|
function writeFakeGit(): void {
|
|
mkdirSync(FAKE_GIT_DIR, { recursive: true });
|
|
// Fake git: writes a .git dir + a sentinel README so the clone looks real.
|
|
// Echoes the test URL on `remote get-url origin` so validateRepoState
|
|
// sees a healthy clone matching config.remote_url.
|
|
const script = `#!/usr/bin/env bash
|
|
has_clone=0
|
|
has_remote_get_url=0
|
|
for ((i=1; i<=$#; i++)); do
|
|
arg="\${!i}"
|
|
next_idx=$((i+1))
|
|
next="\${!next_idx:-}"
|
|
if [ "$arg" = "clone" ]; then has_clone=1; fi
|
|
if [ "$arg" = "remote" ] && [ "$next" = "get-url" ]; then has_remote_get_url=1; fi
|
|
done
|
|
if [ "$has_clone" = "1" ]; then
|
|
dest="\${@: -1}"
|
|
mkdir -p "$dest/.git"
|
|
echo "ref: refs/heads/main" > "$dest/.git/HEAD"
|
|
cat > "$dest/README.md" <<'MD'
|
|
# E2E test fixture
|
|
This file was placed by the fake-git harness for sources-remote-mcp.test.ts.
|
|
MD
|
|
exit 0
|
|
fi
|
|
if [ "$has_remote_get_url" = "1" ]; then
|
|
echo "${TEST_URL}"
|
|
exit 0
|
|
fi
|
|
exit 0
|
|
`;
|
|
const path = join(FAKE_GIT_DIR, 'git');
|
|
writeFileSync(path, script);
|
|
chmodSync(path, 0o755);
|
|
}
|
|
|
|
async function callMcp(token: string, opName: string, args: Record<string, unknown>): Promise<any> {
|
|
const res = await fetch(`${BASE}/mcp`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Authorization': `Bearer ${token}`,
|
|
'Accept': 'application/json, text/event-stream',
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: Math.floor(Math.random() * 1e6),
|
|
method: 'tools/call',
|
|
params: { name: opName, arguments: args },
|
|
}),
|
|
});
|
|
const text = await res.text();
|
|
if (!res.ok) throw new Error(`/mcp ${opName} returned ${res.status}: ${text.slice(0, 300)}`);
|
|
// SSE format: lines starting with `event:` and `data:`. Pull the JSON-RPC
|
|
// payload from the data line.
|
|
let dataLine = '';
|
|
for (const line of text.split('\n')) {
|
|
if (line.startsWith('data: ')) { dataLine = line.slice(6); break; }
|
|
}
|
|
const payload = dataLine ? JSON.parse(dataLine) : JSON.parse(text);
|
|
if (payload.error) {
|
|
throw new Error(`/mcp ${opName} JSON-RPC error: ${JSON.stringify(payload.error)}`);
|
|
}
|
|
// The op result is wrapped: result.content[0].text contains the JSON the op returned.
|
|
const content = payload.result?.content?.[0]?.text;
|
|
if (!content) {
|
|
throw new Error(`/mcp ${opName} no content: ${text.slice(0, 300)}`);
|
|
}
|
|
if (payload.result.isError) {
|
|
return { __isError: true, parsed: JSON.parse(content) };
|
|
}
|
|
return JSON.parse(content);
|
|
}
|
|
|
|
describeE2E('sources-remote-mcp E2E (gstack /setup-gbrain Path 4)', () => {
|
|
let serverProcess: ReturnType<typeof import('child_process').spawn> | null = null;
|
|
let clientId: string | undefined;
|
|
let token: string | undefined;
|
|
let readOnlyClientId: string | undefined;
|
|
let readOnlyToken: string | undefined;
|
|
|
|
beforeAll(async () => {
|
|
// Truncate + apply schema/migrations before any subprocess hits the DB.
|
|
await setupDB();
|
|
// setupDB's ALL_TABLES list does not include sources / oauth_clients —
|
|
// those accumulate across runs and cause Q4 pre-flight collisions on
|
|
// re-run. Wipe them explicitly. CASCADE on sources cleans pages too.
|
|
{
|
|
const { getConn } = await import('./helpers.ts');
|
|
const sql = getConn();
|
|
await sql`TRUNCATE oauth_codes, oauth_tokens, oauth_clients CASCADE`;
|
|
await sql`DELETE FROM sources WHERE id != 'default'`;
|
|
await sql`DELETE FROM access_tokens`;
|
|
}
|
|
|
|
writeFakeGit();
|
|
rmSync(GBRAIN_HOME, { recursive: true, force: true });
|
|
mkdirSync(GBRAIN_HOME, { recursive: true });
|
|
|
|
const { execSync, spawn } = await import('child_process');
|
|
|
|
// Subprocess inherits process.env — but we need to thread:
|
|
// - PATH: prepend FAKE_GIT_DIR so the spawned brain spawns OUR git
|
|
// - GBRAIN_HOME: scope the clone dir to FIXTURE_DIR
|
|
const subprocessEnv = {
|
|
...process.env,
|
|
PATH: `${FAKE_GIT_DIR}:${process.env.PATH ?? ''}`,
|
|
GBRAIN_HOME,
|
|
};
|
|
|
|
// Register a sources_admin-scoped client (the "gstack token").
|
|
// New grants can reference only active sources. sources_admin permits
|
|
// creating a source, but read access is granted explicitly afterward.
|
|
const reg1 = execSync(
|
|
'bun run src/cli.ts auth register-client e2e-sources-admin ' +
|
|
'--grant-types client_credentials --scopes "read sources_admin" ' +
|
|
'--federated-read default',
|
|
{ cwd: process.cwd(), encoding: 'utf8', env: subprocessEnv },
|
|
);
|
|
clientId = reg1.match(/Client ID:\s+(gbrain_cl_\S+)/)?.[1];
|
|
const clientSecret = reg1.match(/Client Secret:\s+(gbrain_cs_\S+)/)?.[1];
|
|
if (!clientId || !clientSecret) throw new Error('Failed to register e2e client:\n' + reg1);
|
|
|
|
// Register a read-only client (proves the scope-enforcement gate).
|
|
const reg2 = execSync(
|
|
'bun run src/cli.ts auth register-client e2e-read-only ' +
|
|
'--grant-types client_credentials --scopes "read"',
|
|
{ cwd: process.cwd(), encoding: 'utf8', env: subprocessEnv },
|
|
);
|
|
readOnlyClientId = reg2.match(/Client ID:\s+(gbrain_cl_\S+)/)?.[1];
|
|
const readOnlySecret = reg2.match(/Client Secret:\s+(gbrain_cs_\S+)/)?.[1];
|
|
if (!readOnlyClientId || !readOnlySecret) throw new Error('Failed to register read-only client');
|
|
|
|
// Start the HTTP server with the fake-git PATH and our GBRAIN_HOME.
|
|
serverProcess = spawn(
|
|
'bun',
|
|
['run', 'src/cli.ts', 'serve', '--http',
|
|
'--port', String(PORT),
|
|
'--public-url', `http://localhost:${PORT}`],
|
|
{
|
|
cwd: process.cwd(),
|
|
env: subprocessEnv,
|
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
},
|
|
);
|
|
let stderr = '';
|
|
serverProcess.stderr?.on('data', (d: Buffer) => { stderr += d.toString(); });
|
|
|
|
// Wait for server health (15s)
|
|
let ready = false;
|
|
for (let i = 0; i < 30; i++) {
|
|
try {
|
|
const res = await fetch(`${BASE}/health`);
|
|
if (res.ok) { ready = true; break; }
|
|
} catch { /* not ready yet */ }
|
|
await new Promise(r => setTimeout(r, 500));
|
|
}
|
|
if (!ready) throw new Error('Server failed to start within 15s.\nstderr tail: ' + stderr.slice(-1000));
|
|
|
|
// Mint tokens via the OAuth /token endpoint.
|
|
const mintToken = async (cid: string, secret: string, scope: string): Promise<string> => {
|
|
const body = new URLSearchParams({
|
|
grant_type: 'client_credentials',
|
|
client_id: cid,
|
|
client_secret: secret,
|
|
scope,
|
|
});
|
|
const r = await fetch(`${BASE}/token`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
body,
|
|
});
|
|
if (!r.ok) throw new Error(`/token failed: ${r.status} ${await r.text()}`);
|
|
const j = await r.json() as { access_token: string };
|
|
return j.access_token;
|
|
};
|
|
token = await mintToken(clientId, clientSecret, 'read sources_admin');
|
|
readOnlyToken = await mintToken(readOnlyClientId, readOnlySecret, 'read');
|
|
}, 30_000);
|
|
|
|
afterAll(async () => {
|
|
if (serverProcess) {
|
|
serverProcess.kill('SIGTERM');
|
|
await new Promise(r => setTimeout(r, 800));
|
|
if (!serverProcess.killed) serverProcess.kill('SIGKILL');
|
|
}
|
|
const { execSync } = await import('child_process');
|
|
for (const id of [clientId, readOnlyClientId].filter(Boolean) as string[]) {
|
|
try {
|
|
execSync(`bun run src/cli.ts auth revoke-client ${id}`, {
|
|
cwd: process.cwd(), encoding: 'utf8', env: { ...process.env, GBRAIN_HOME },
|
|
});
|
|
} catch (e) {
|
|
process.stderr.write(`[afterAll] revoke ${id} failed: ${(e as Error).message}\n`);
|
|
}
|
|
}
|
|
rmSync(FIXTURE_DIR, { recursive: true, force: true });
|
|
await teardownDB();
|
|
}, 30_000);
|
|
|
|
// -------------------------------------------------------------------------
|
|
// Headline flow: gstack /setup-gbrain Path 4 unblock
|
|
// -------------------------------------------------------------------------
|
|
|
|
test('whoami reports oauth transport + sources_admin scope', async () => {
|
|
const result = await callMcp(token!, 'whoami', {});
|
|
expect(result.transport).toBe('oauth');
|
|
expect(result.scopes).toEqual(expect.arrayContaining(['read', 'sources_admin']));
|
|
expect(result.client_id).toBe(clientId);
|
|
});
|
|
|
|
test('OAuth /.well-known advertises all 5 scopes', async () => {
|
|
const r = await fetch(`${BASE}/.well-known/oauth-authorization-server`);
|
|
const meta = await r.json() as any;
|
|
expect(meta.scopes_supported).toEqual(
|
|
expect.arrayContaining(['admin', 'read', 'sources_admin', 'users_admin', 'write']),
|
|
);
|
|
});
|
|
|
|
test('sources_add via MCP: clones, INSERTs, returns row with remote_url', async () => {
|
|
const result = await callMcp(token!, 'sources_add', {
|
|
id: 'e2e-yc-artifacts',
|
|
url: TEST_URL,
|
|
federated: true,
|
|
});
|
|
if (process.env.GBRAIN_E2E_DEBUG) {
|
|
console.error('[debug sources_add]', JSON.stringify(result));
|
|
}
|
|
expect(result.id).toBe('e2e-yc-artifacts');
|
|
// Postgres returns JSONB as a parsed object via postgres.js .unsafe(),
|
|
// but if it ever comes back as a string (engine driver tweak, json
|
|
// serialization), surface the actual shape in the failure message.
|
|
const cfg = typeof result.config === 'string' ? JSON.parse(result.config) : result.config;
|
|
expect(cfg).toBeDefined();
|
|
expect(cfg.remote_url).toBe(TEST_URL);
|
|
expect(cfg.federated).toBe(true);
|
|
// Clone exists with a .git dir (fake-git wrote one).
|
|
expect(existsSync(join(GBRAIN_HOME, '.gbrain', 'clones', 'e2e-yc-artifacts', '.git'))).toBe(true);
|
|
});
|
|
|
|
test('a newly created source stays hidden until rescope; the existing token sees the live grant', async () => {
|
|
const issuedToken = token!;
|
|
const before = await callMcp(issuedToken, 'sources_list', {});
|
|
expect(before.sources.find((s: any) => s.id === 'e2e-yc-artifacts')).toBeUndefined();
|
|
const denied = await callMcp(issuedToken, 'sources_status', { id: 'e2e-yc-artifacts' });
|
|
expect(denied.__isError).toBe(true);
|
|
expect(JSON.stringify(denied.parsed)).toMatch(/not_found/);
|
|
|
|
const { execFileSync } = await import('child_process');
|
|
execFileSync('bun', ['run', 'src/cli.ts', 'auth', 'rescope-client', clientId!,
|
|
'--federated-read', 'default,e2e-yc-artifacts'], {
|
|
cwd: process.cwd(), encoding: 'utf8', env: { ...process.env, GBRAIN_HOME },
|
|
});
|
|
|
|
const identity = await callMcp(issuedToken, 'whoami', {});
|
|
expect(identity.federated_read).toEqual(['default', 'e2e-yc-artifacts']);
|
|
const after = await callMcp(issuedToken, 'sources_list', {});
|
|
expect(after.sources.find((s: any) => s.id === 'e2e-yc-artifacts')).toBeDefined();
|
|
});
|
|
|
|
test('sources_status reports clone_state=healthy', async () => {
|
|
const result = await callMcp(token!, 'sources_status', { id: 'e2e-yc-artifacts' });
|
|
expect(result.clone_state).toBe('healthy');
|
|
expect(result.remote_url).toBe(TEST_URL);
|
|
});
|
|
|
|
test('sources_list surfaces remote_url for the new source', async () => {
|
|
const result = await callMcp(token!, 'sources_list', {});
|
|
const found = result.sources.find((s: any) => s.id === 'e2e-yc-artifacts');
|
|
expect(found).toBeDefined();
|
|
expect(found.remote_url).toBe(TEST_URL);
|
|
expect(found.federated).toBe(true);
|
|
});
|
|
|
|
// -------------------------------------------------------------------------
|
|
// SSRF + scope rejection
|
|
// -------------------------------------------------------------------------
|
|
|
|
test('sources_add rejects RFC1918 URL via parseRemoteUrl gate', async () => {
|
|
const result = await callMcp(token!, 'sources_add', {
|
|
id: 'e2e-bad-ssrf',
|
|
url: 'https://192.168.1.1/x.git',
|
|
});
|
|
expect(result.__isError).toBe(true);
|
|
// The op throws SourceOpError(invalid_remote_url) which wraps a
|
|
// RemoteUrlError(internal_target). The HTTP error serializer flattens
|
|
// to a generic `class: SourceOpError` envelope without preserving the
|
|
// SourceOpError-specific `code` field — but the message survives, so
|
|
// match on the user-visible text.
|
|
expect(JSON.stringify(result.parsed)).toMatch(
|
|
/internal_target|invalid_remote_url|internal\/private network/i,
|
|
);
|
|
});
|
|
|
|
test('read-only token gets insufficient_scope on sources_add', async () => {
|
|
const result = await callMcp(readOnlyToken!, 'sources_add', {
|
|
id: 'e2e-blocked',
|
|
url: TEST_URL,
|
|
});
|
|
expect(result.__isError).toBe(true);
|
|
expect(JSON.stringify(result.parsed)).toMatch(/insufficient_scope/);
|
|
});
|
|
|
|
test('read-only token CAN list sources (read-scoped)', async () => {
|
|
const result = await callMcp(readOnlyToken!, 'sources_list', {});
|
|
expect(Array.isArray(result.sources)).toBe(true);
|
|
// #4433: the listing is row-filtered to the caller's federated read
|
|
// grant. This client kept the registration default (['default']), so a
|
|
// source outside its grant must not leak into its listing.
|
|
expect(result.sources.find((s: any) => s.id === 'e2e-yc-artifacts')).toBeUndefined();
|
|
});
|
|
|
|
test('CLI register-client rejects bogus scope (allowlist)', async () => {
|
|
const { execSync } = await import('child_process');
|
|
let threw = false;
|
|
try {
|
|
execSync(
|
|
'bun run src/cli.ts auth register-client should-fail --scopes "read flying-unicorn"',
|
|
{ cwd: process.cwd(), encoding: 'utf8', env: { ...process.env, GBRAIN_HOME } },
|
|
);
|
|
} catch (e: any) {
|
|
threw = true;
|
|
expect(e.stderr || e.message).toMatch(/Unknown scope|invalid_scope/i);
|
|
}
|
|
expect(threw).toBe(true);
|
|
});
|
|
|
|
// -------------------------------------------------------------------------
|
|
// Recovery: rm the clone, assert the next direct sources_status sees missing
|
|
// ------------------------------------------------------------------------
|
|
|
|
test('recovery: rm clone dir → sources_status reports missing', async () => {
|
|
const clonePath = join(GBRAIN_HOME, '.gbrain', 'clones', 'e2e-yc-artifacts');
|
|
rmSync(clonePath, { recursive: true, force: true });
|
|
expect(existsSync(clonePath)).toBe(false);
|
|
const result = await callMcp(token!, 'sources_status', { id: 'e2e-yc-artifacts' });
|
|
expect(result.clone_state).toBe('missing');
|
|
});
|
|
|
|
// -------------------------------------------------------------------------
|
|
// sources_remove: WRITE authority, cascade + clone cleanup
|
|
// -------------------------------------------------------------------------
|
|
|
|
/**
|
|
* sources_remove is confined to the caller's WRITE authority (O4-1, review
|
|
* cycle 4): a sources_admin token may hard-delete only its own write source.
|
|
* The federated read grant (`--federated-read`) is READ authority by
|
|
* contract and confers no removal right — widening it makes a source
|
|
* visible to sources_status / sources_list, yet sources_remove still
|
|
* answers not_found (indistinguishable from a nonexistent source). Over
|
|
* HTTP every client carries a write source (registration default
|
|
* 'default'), and a client's own row FK-RESTRICTs the removal of that very
|
|
* source, so hard-removing a source is an operator action on the host CLI
|
|
* (`gbrain sources remove`) — mirrored here.
|
|
*/
|
|
async function widenGrantTo(...sourceIds: string[]): Promise<void> {
|
|
const { execFileSync } = await import('child_process');
|
|
execFileSync('bun', ['run', 'src/cli.ts', 'auth', 'rescope-client', clientId!,
|
|
'--federated-read', sourceIds.join(',')], {
|
|
cwd: process.cwd(), encoding: 'utf8', env: { ...process.env, GBRAIN_HOME },
|
|
});
|
|
}
|
|
|
|
async function rescopeWriteSource(sourceId: string): Promise<void> {
|
|
const { execFileSync } = await import('child_process');
|
|
execFileSync('bun', ['run', 'src/cli.ts', 'auth', 'rescope-client', clientId!,
|
|
'--source', sourceId], {
|
|
cwd: process.cwd(), encoding: 'utf8', env: { ...process.env, GBRAIN_HOME },
|
|
});
|
|
}
|
|
|
|
/** The trusted local path: `gbrain sources remove <id> --confirm-destructive` on the host. */
|
|
async function operatorRemovesSource(id: string): Promise<string> {
|
|
const { execFileSync } = await import('child_process');
|
|
return execFileSync('bun', ['run', 'src/cli.ts', 'sources', 'remove', id, '--confirm-destructive'], {
|
|
cwd: process.cwd(), encoding: 'utf8', env: { ...process.env, GBRAIN_HOME },
|
|
});
|
|
}
|
|
|
|
test('sources_remove: a federated READ grant naming the source is not removal authority; the operator removes it on the host CLI', async () => {
|
|
await callMcp(token!, 'sources_add', { id: 'e2e-removable', url: TEST_URL });
|
|
const clonePath = join(GBRAIN_HOME, '.gbrain', 'clones', 'e2e-removable');
|
|
expect(existsSync(clonePath)).toBe(true);
|
|
// Outside the token's grant entirely → not_found, and nothing is removed.
|
|
const fenced = await callMcp(token!, 'sources_remove', {
|
|
id: 'e2e-removable',
|
|
confirm_destructive: true,
|
|
});
|
|
expect(fenced.__isError).toBe(true);
|
|
expect(JSON.stringify(fenced.parsed)).toMatch(/not_found/);
|
|
expect(existsSync(clonePath)).toBe(true);
|
|
// Operator widens the READ grant; the live token now reads the source...
|
|
await widenGrantTo('default', 'e2e-yc-artifacts', 'e2e-removable');
|
|
const status = await callMcp(token!, 'sources_status', { id: 'e2e-removable' });
|
|
expect(status.clone_state).toBe('healthy');
|
|
// ...but removal is WRITE authority: still not_found, still on disk.
|
|
const stillFenced = await callMcp(token!, 'sources_remove', {
|
|
id: 'e2e-removable',
|
|
confirm_destructive: true,
|
|
});
|
|
expect(stillFenced.__isError).toBe(true);
|
|
expect(JSON.stringify(stillFenced.parsed)).toMatch(/not_found/);
|
|
expect(existsSync(clonePath)).toBe(true);
|
|
// The operator removes it on the host CLI (trusted local path).
|
|
const out = await operatorRemovesSource('e2e-removable');
|
|
expect(out).toMatch(/Removed source "e2e-removable"/);
|
|
const after = await callMcp(token!, 'sources_list', {});
|
|
expect(after.sources.find((s: any) => s.id === 'e2e-removable')).toBeUndefined();
|
|
// Drop the dead id from the read grant (hygiene for the tests below).
|
|
await widenGrantTo('default', 'e2e-yc-artifacts');
|
|
});
|
|
|
|
test('sources_remove: rescoping the WRITE source moves the authority — a federated-readable non-write source stays not_found while sources_status still answers', async () => {
|
|
await callMcp(token!, 'sources_add', { id: 'e2e-confirm-test', url: TEST_URL });
|
|
await widenGrantTo('default', 'e2e-yc-artifacts', 'e2e-confirm-test');
|
|
await rescopeWriteSource('e2e-confirm-test');
|
|
try {
|
|
const identity = await callMcp(token!, 'whoami', {});
|
|
expect(identity.source_id).toBe('e2e-confirm-test');
|
|
// e2e-yc-artifacts is readable (federated) but is not the write source.
|
|
const fenced = await callMcp(token!, 'sources_remove', {
|
|
id: 'e2e-yc-artifacts',
|
|
confirm_destructive: true,
|
|
});
|
|
expect(fenced.__isError).toBe(true);
|
|
expect(JSON.stringify(fenced.parsed)).toMatch(/not_found/);
|
|
const status = await callMcp(token!, 'sources_status', { id: 'e2e-yc-artifacts' });
|
|
expect(status.id).toBe('e2e-yc-artifacts');
|
|
// 'default' is neither readable-only nor the write source now: same
|
|
// not_found (the fence answers before the op's protected-id guard).
|
|
const def = await callMcp(token!, 'sources_remove', { id: 'default', confirm_destructive: true });
|
|
expect(def.__isError).toBe(true);
|
|
expect(JSON.stringify(def.parsed)).toMatch(/not_found/);
|
|
} finally {
|
|
// Restore the write source BEFORE the operator removes the fixture — a
|
|
// client row referencing it would FK-RESTRICT the removal.
|
|
await rescopeWriteSource('default');
|
|
}
|
|
const out = await operatorRemovesSource('e2e-confirm-test');
|
|
expect(out).toMatch(/Removed source "e2e-confirm-test"/);
|
|
await widenGrantTo('default', 'e2e-yc-artifacts');
|
|
});
|
|
});
|