* 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>
349 lines
16 KiB
TypeScript
349 lines
16 KiB
TypeScript
/**
|
|
* oauth_client_scope_health (cathedral-6) — scoped-client grant hygiene.
|
|
*
|
|
* - (a) a federated read grant naming a nonexistent source (federated_read
|
|
* is a TEXT[] with no FK) → warn naming the client + the missing id.
|
|
* - (b) an empty auto-created '<name>-workspace' source with no live client
|
|
* referencing it (the post-failure / post-revoke residue from
|
|
* `gbrain agent register`) → warn naming the source.
|
|
* - A pages-bearing non-default source is NEVER flagged (that shape is
|
|
* every ordinary local brain, not residue).
|
|
* - An empty workspace still referenced by a live client is NOT residue.
|
|
* - Deleted clients (deleted_at set) don't produce dangling-grant warns.
|
|
*
|
|
* Hermetic via PGLite. Imports from doctor.ts (the façade re-export), same
|
|
* as the sibling routing-federation check tests.
|
|
*/
|
|
|
|
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
|
|
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
|
import { checkOauthClientScopeHealth } from '../src/commands/doctor.ts';
|
|
import { DCR_PRIVILEGED_SCOPES } from '../src/commands/doctor/checks/routing-federation.ts';
|
|
import { ALLOWED_SCOPES_LIST, DCR_REGISTRABLE_SCOPES } from '../src/core/scope.ts';
|
|
|
|
let engine: PGLiteEngine;
|
|
|
|
beforeAll(async () => {
|
|
engine = new PGLiteEngine();
|
|
await engine.connect({});
|
|
await engine.initSchema();
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await engine.disconnect();
|
|
});
|
|
|
|
async function truncate(): Promise<void> {
|
|
for (const t of ['pages', 'facts', 'oauth_tokens', 'oauth_codes', 'oauth_clients']) {
|
|
await (engine as any).db.exec(`DELETE FROM ${t}`);
|
|
}
|
|
await (engine as any).db.exec(`DELETE FROM sources WHERE id <> 'default'`);
|
|
}
|
|
|
|
describe('checkOauthClientScopeHealth', () => {
|
|
beforeEach(truncate);
|
|
|
|
test('clean brain → ok', async () => {
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('ok');
|
|
expect(r.message).toMatch(/consistent/i);
|
|
});
|
|
|
|
test('dangling federated grant + orphaned empty workspace → both warn', async () => {
|
|
// (a) live client granted a read on a source that no longer exists.
|
|
await engine.executeRaw(
|
|
`INSERT INTO oauth_clients (client_id, client_name, scope, federated_read)
|
|
VALUES ('c-dangler', 'nova-daily', 'read write', $1)`,
|
|
[['default', 'ghost-source']],
|
|
);
|
|
// (b) empty derived workspace, DB-only, referenced by no live client.
|
|
await engine.executeRaw(
|
|
`INSERT INTO sources (id, name) VALUES ('aurora-coder-workspace', 'aurora-coder-workspace')`,
|
|
);
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('warn');
|
|
// Arm (a): names the client and the missing grant id, with the rescope hint.
|
|
expect(r.message).toMatch(/nova-daily/);
|
|
expect(r.message).toMatch(/ghost-source/);
|
|
expect(r.message).toMatch(/rescope-client/);
|
|
// Arm (b): names the orphaned workspace, with the removal hint.
|
|
expect(r.message).toMatch(/aurora-coder-workspace/);
|
|
expect(r.message).toMatch(/gbrain sources remove/);
|
|
});
|
|
|
|
test('zero-page workspace WITH facts → NOT flagged (revoked agent memory, not residue)', async () => {
|
|
// A revoked agent's workspace: the client row is gone, no pages were ever
|
|
// written, but FACTS exist (the primary agent write lane). Recommending
|
|
// `gbrain sources remove` here would cascade the facts away.
|
|
await engine.executeRaw(
|
|
`INSERT INTO sources (id, name) VALUES ('revoked-agent-workspace', 'revoked-agent-workspace')`,
|
|
);
|
|
await engine.executeRaw(
|
|
`INSERT INTO facts (source_id, fact, source)
|
|
VALUES ('revoked-agent-workspace', 'agent memory row', 'test')`,
|
|
);
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('ok');
|
|
expect(r.message).not.toMatch(/revoked-agent-workspace/);
|
|
});
|
|
|
|
test('pages-bearing non-default source → NOT flagged', async () => {
|
|
await engine.executeRaw(
|
|
`INSERT INTO sources (id, name) VALUES ('proj-widget-workspace', 'proj-widget-workspace')`,
|
|
);
|
|
await engine.executeRaw(
|
|
`INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline)
|
|
VALUES ('p1', 'proj-widget-workspace', 'note', 'p1', '', '')`,
|
|
);
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('ok');
|
|
});
|
|
|
|
test('empty workspace referenced by a live client → NOT flagged', async () => {
|
|
await engine.executeRaw(
|
|
`INSERT INTO sources (id, name) VALUES ('aurora-coder-workspace', 'aurora-coder-workspace')`,
|
|
);
|
|
await engine.executeRaw(
|
|
`INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read)
|
|
VALUES ('c-live', 'aurora-coder', 'read write', 'aurora-coder-workspace', $1)`,
|
|
[['aurora-coder-workspace', 'default']],
|
|
);
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('ok');
|
|
});
|
|
|
|
test('deleted client with a dangling grant → NOT flagged', async () => {
|
|
await engine.executeRaw(
|
|
`INSERT INTO oauth_clients (client_id, client_name, scope, federated_read, deleted_at)
|
|
VALUES ('c-deleted', 'retired-agent', 'read', $1, now())`,
|
|
[['ghost-source']],
|
|
);
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('ok');
|
|
});
|
|
|
|
// (c) Privileged self-registered clients. A row created through the
|
|
// anonymous DCR path carries grant_revision = 0 and no oauth_grant_audit
|
|
// 'register' row (operator paths write one). Rows that hold a scope beyond
|
|
// the DCR ceiling with that signature predate the ceiling (or predate the
|
|
// grant audit log) and deserve an operator look — advisory WARN with the
|
|
// rescope / revoke remedy.
|
|
describe('privileged self-registered (DCR-signature) clients', () => {
|
|
async function seedClient(id: string, scope: string, opts: { audited?: boolean; revision?: number; deleted?: boolean } = {}): Promise<void> {
|
|
await engine.executeRaw(
|
|
`INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, grant_revision, deleted_at)
|
|
VALUES ($1, $2, $3, 'default', $4, $5, ${opts.deleted ? 'now()' : 'NULL'})`,
|
|
[id, `${id}-name`, scope, ['default'], opts.revision ?? 0],
|
|
);
|
|
if (opts.audited) {
|
|
await engine.executeRaw(
|
|
`INSERT INTO oauth_grant_audit (client_id, actor, action, revision, before_grant, after_grant)
|
|
VALUES ($1, 'operator', 'register', 0, NULL, '{}'::jsonb)`,
|
|
[id],
|
|
);
|
|
}
|
|
}
|
|
|
|
beforeEach(async () => {
|
|
await (engine as any).db.exec('DELETE FROM oauth_grant_audit');
|
|
});
|
|
|
|
test('admin-scoped DCR-signature row → warn naming the client + rescope/revoke remedy', async () => {
|
|
await seedClient('c-dcr-admin', 'read admin');
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('warn');
|
|
expect(r.message).toMatch(/c-dcr-admin/);
|
|
expect(r.message).toMatch(/admin/);
|
|
expect(r.message).toMatch(/rescope-client <client_id> --scopes read,write|rescope-client .*--scopes/);
|
|
expect(r.message).toMatch(/revoke-client/);
|
|
});
|
|
|
|
test('sources_admin and users_admin also trip the arm; the client name is shown', async () => {
|
|
await seedClient('c-dcr-sources', 'sources_admin');
|
|
await seedClient('c-dcr-users', 'read users_admin');
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('warn');
|
|
expect(r.message).toMatch(/c-dcr-sources-name/);
|
|
expect(r.message).toMatch(/c-dcr-users-name/);
|
|
});
|
|
|
|
test('read/write DCR-signature rows are within the ceiling → NOT flagged', async () => {
|
|
await seedClient('c-dcr-rw', 'read write');
|
|
await seedClient('c-dcr-empty', '');
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('ok');
|
|
});
|
|
|
|
test('operator-registered admin client (audit register row) → NOT flagged', async () => {
|
|
await seedClient('c-op-admin', 'admin', { audited: true });
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('ok');
|
|
});
|
|
|
|
test('rescoped admin client (grant_revision > 0) → NOT flagged', async () => {
|
|
await seedClient('c-rescoped-admin', 'admin', { revision: 2 });
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('ok');
|
|
});
|
|
|
|
test('revoked (deleted_at) DCR-signature admin row → NOT flagged', async () => {
|
|
await seedClient('c-dcr-revoked', 'admin', { deleted: true });
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('ok');
|
|
});
|
|
|
|
test('grant audit table missing → arm skipped with an explicit note, other arms intact', async () => {
|
|
await seedClient('c-dcr-admin-noaudit', 'admin');
|
|
await (engine as any).db.exec('DROP TABLE oauth_grant_audit');
|
|
try {
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
// Fail-open: cannot tell operator rows from self-registered ones
|
|
// without the audit log, so the arm reports unknown instead of
|
|
// guessing — and says so.
|
|
expect(r.status).toBe('ok');
|
|
expect(r.message).toMatch(/self-registered.*(skipped|unknown)|(skipped|unknown).*self-registered/i);
|
|
} finally {
|
|
const { GRANT_AUDIT_SCHEMA_SQL } = await import('../src/core/grants/schema.ts');
|
|
await (engine as any).db.exec(GRANT_AUDIT_SCHEMA_SQL);
|
|
}
|
|
});
|
|
});
|
|
});
|
|
|
|
// Arm (c) edge shapes not pinned above: the `agent` scope (seeded with the
|
|
// delegation bindings its check constraint demands), the 5-client display cap
|
|
// with its "+N more" tail, and the word-bounded scope match (a token that
|
|
// merely CONTAINS a privileged word is not one).
|
|
describe('checkOauthClientScopeHealth — arm (c) edge shapes', () => {
|
|
async function seed(id: string, scope: string): Promise<void> {
|
|
await engine.executeRaw(
|
|
`INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, grant_revision, deleted_at)
|
|
VALUES ($1, $2, $3, 'default', $4, 0, NULL)`,
|
|
[id, `${id}-name`, scope, ['default']],
|
|
);
|
|
}
|
|
|
|
beforeEach(async () => {
|
|
await truncate();
|
|
await (engine as any).db.exec('DELETE FROM oauth_grant_audit');
|
|
});
|
|
|
|
test('agent-scoped DCR-signature row is flagged (agent sits beyond the ceiling too)', async () => {
|
|
// `oauth_clients_complete_agent_grant` (grants/schema.ts) refuses an agent
|
|
// scope without complete delegation bindings — seed a complete one.
|
|
await engine.executeRaw(
|
|
`INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, grant_revision, deleted_at,
|
|
bound_tools, bound_source_id, delegated_namespace, delegated_slug_prefixes, bound_max_concurrent)
|
|
VALUES ('c-dcr-agent', 'c-dcr-agent-name', 'read agent', 'default', $1, 0, NULL,
|
|
$2, 'default', 'job', NULL, 1)`,
|
|
[['default'], ['get_page']],
|
|
);
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('warn');
|
|
expect(r.message).toMatch(/c-dcr-agent/);
|
|
expect(r.message).toContain('scope=read agent');
|
|
});
|
|
|
|
// (client_name is NOT NULL in the schema, so the `?? client_id` display
|
|
// fallback cannot be reached through the database — not pinned here.)
|
|
|
|
test('more than five offenders: five shown (ordered by client_id), the rest counted', async () => {
|
|
for (let i = 0; i < 7; i++) await seed(`c-dcr-many-${i}`, 'admin');
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('warn');
|
|
expect(r.message).toMatch(/^7 active OAuth client\(s\)/);
|
|
for (let i = 0; i < 5; i++) expect(r.message).toContain(`(c-dcr-many-${i})`);
|
|
expect(r.message).not.toContain('(c-dcr-many-5)');
|
|
expect(r.message).not.toContain('(c-dcr-many-6)');
|
|
expect(r.message).toContain('(+2 more)');
|
|
});
|
|
|
|
test('a scope token that merely CONTAINS a privileged word is not flagged (word-bounded match)', async () => {
|
|
await seed('c-dcr-substring', 'readmin write');
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('ok');
|
|
});
|
|
|
|
test('grant_revision column missing → arm skipped with the explicit note, other arms intact', async () => {
|
|
// A brain whose oauth_clients predates the grant schema: the DCR
|
|
// signature cannot be evaluated, so the arm reports unknown (ok + note)
|
|
// rather than guessing — even with an admin-scoped row present.
|
|
await (engine as any).db.exec('ALTER TABLE oauth_clients DROP COLUMN grant_revision');
|
|
try {
|
|
await engine.executeRaw(
|
|
`INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, deleted_at)
|
|
VALUES ('c-dcr-norev', 'c-dcr-norev-name', 'admin', 'default', $1, NULL)`,
|
|
[['default']],
|
|
);
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('ok');
|
|
expect(r.message).toMatch(/self-registered.*(skipped|unknown)|(skipped|unknown).*self-registered/i);
|
|
expect(r.message).not.toMatch(/c-dcr-norev/);
|
|
} finally {
|
|
await (engine as any).db.exec('ALTER TABLE oauth_clients ADD COLUMN grant_revision integer NOT NULL DEFAULT 0');
|
|
}
|
|
});
|
|
});
|
|
|
|
// The privileged set arm (c) matches is DERIVED from scope.ts (the complement
|
|
// of the DCR ceiling), never a hand-copied literal — so a scope added to
|
|
// ALLOWED_SCOPES_LIST without joining DCR_REGISTRABLE_SCOPES is audited
|
|
// automatically, and the copy names the ceiling from the same constant.
|
|
describe('checkOauthClientScopeHealth — arm (c) privileged set is the derived complement of the DCR ceiling', () => {
|
|
const complement = ALLOWED_SCOPES_LIST.filter((s) => !DCR_REGISTRABLE_SCOPES.has(s));
|
|
|
|
test('DCR_PRIVILEGED_SCOPES === ALLOWED_SCOPES_LIST \\ DCR_REGISTRABLE_SCOPES (disjoint, jointly exhaustive)', () => {
|
|
expect([...DCR_PRIVILEGED_SCOPES]).toEqual(complement);
|
|
expect(DCR_PRIVILEGED_SCOPES.length).toBeGreaterThan(0);
|
|
for (const s of DCR_PRIVILEGED_SCOPES) expect(DCR_REGISTRABLE_SCOPES.has(s as any)).toBe(false);
|
|
expect([...DCR_PRIVILEGED_SCOPES, ...DCR_REGISTRABLE_SCOPES].sort()).toEqual([...ALLOWED_SCOPES_LIST].sort());
|
|
});
|
|
|
|
/** Seed a DCR-signature row; `agent` needs complete delegation bindings (check constraint). */
|
|
async function seedDcrSignature(id: string, scope: string): Promise<void> {
|
|
if (scope.split(' ').includes('agent')) {
|
|
await engine.executeRaw(
|
|
`INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, grant_revision, deleted_at,
|
|
bound_tools, bound_source_id, delegated_namespace, delegated_slug_prefixes, bound_max_concurrent)
|
|
VALUES ($1, $2, $3, 'default', $4, 0, NULL, $5, 'default', 'job', NULL, 1)`,
|
|
[id, `${id}-name`, scope, ['default'], ['get_page']],
|
|
);
|
|
return;
|
|
}
|
|
await engine.executeRaw(
|
|
`INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, grant_revision, deleted_at)
|
|
VALUES ($1, $2, $3, 'default', $4, 0, NULL)`,
|
|
[id, `${id}-name`, scope, ['default']],
|
|
);
|
|
}
|
|
|
|
beforeEach(async () => {
|
|
await truncate();
|
|
await (engine as any).db.exec('DELETE FROM oauth_grant_audit');
|
|
});
|
|
|
|
test('every scope in the complement trips the arm on its own; every ceiling scope does not', async () => {
|
|
for (const scope of complement) {
|
|
await (engine as any).db.exec('DELETE FROM oauth_clients');
|
|
await seedDcrSignature(`c-dcr-${scope}`, scope);
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('warn');
|
|
expect(r.message).toContain(`(c-dcr-${scope}) scope=${scope}`);
|
|
}
|
|
for (const scope of DCR_REGISTRABLE_SCOPES) {
|
|
await (engine as any).db.exec('DELETE FROM oauth_clients');
|
|
await seedDcrSignature(`c-dcr-${scope}`, scope);
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
expect(r.status).toBe('ok');
|
|
}
|
|
});
|
|
|
|
test('the remedy copy names the ceiling from the constant, not a literal', async () => {
|
|
await seedDcrSignature('c-dcr-copy', complement[0]);
|
|
const r = await checkOauthClientScopeHealth(engine);
|
|
const ceiling = [...DCR_REGISTRABLE_SCOPES];
|
|
expect(r.message).toContain(`self-registration ceiling (${ceiling.join('/')})`);
|
|
expect(r.message).toContain(`--scopes ${ceiling.join(',')}`);
|
|
});
|
|
});
|