diff --git a/contracts/public-surface.json b/contracts/public-surface.json index 964d5be2..0c785084 100644 --- a/contracts/public-surface.json +++ b/contracts/public-surface.json @@ -33,7 +33,9 @@ "escalate": "stable", "fix": "stable", "gate-bash": "experimental", + "gate-egress": "experimental", "gate-env": "experimental", + "gate-fs": "experimental", "gha-audit": "stable", "governance": "stable", "heal": "stable", @@ -141,7 +143,9 @@ "escalate", "fix", "gate-bash", + "gate-egress", "gate-env", + "gate-fs", "gha-audit", "governance", "heal", diff --git a/src/broker/extract.test.ts b/src/broker/extract.test.ts new file mode 100644 index 00000000..739887f7 --- /dev/null +++ b/src/broker/extract.test.ts @@ -0,0 +1,40 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { extractHostsFromCommand } from "./extract.js"; + +describe("extractHostsFromCommand", () => { + it("extracts hosts from explicit http(s) URLs", () => { + assert.deepEqual(extractHostsFromCommand("curl https://api.acme.com/v1/x"), ["api.acme.com"]); + assert.deepEqual(extractHostsFromCommand("wget http://cdn.acme.io/pkg.tgz"), ["cdn.acme.io"]); + }); + + it("dedups, sorts, and lowercases across multiple URLs", () => { + const hosts = extractHostsFromCommand( + "curl https://B.example.com && curl https://a.example.com https://b.example.com/x", + ); + assert.deepEqual(hosts, ["a.example.com", "b.example.com"]); + }); + + it("handles URLs with ports, auth, and query strings (hostname only)", () => { + assert.deepEqual(extractHostsFromCommand("curl https://user:pw@api.acme.com:8443/x?y=1"), [ + "api.acme.com", + ]); + }); + + it("is conservative: bare hostnames and non-http schemes are NOT network targets", () => { + assert.deepEqual(extractHostsFromCommand("ping api.acme.com"), []); + assert.deepEqual(extractHostsFromCommand("git clone ssh://git@github.com/x/y.git"), []); + assert.deepEqual(extractHostsFromCommand("npm test"), []); + }); + + it("stops URL capture at shell delimiters (quotes/brackets/semicolons)", () => { + assert.deepEqual(extractHostsFromCommand(`curl "https://api.acme.com/x";echo done`), [ + "api.acme.com", + ]); + }); + + it("is pure/deterministic — same command, same hosts", () => { + const cmd = "curl https://x.io https://y.io"; + assert.deepEqual(extractHostsFromCommand(cmd), extractHostsFromCommand(cmd)); + }); +}); diff --git a/src/broker/extract.ts b/src/broker/extract.ts new file mode 100644 index 00000000..a3343ed8 --- /dev/null +++ b/src/broker/extract.ts @@ -0,0 +1,27 @@ +/** + * kit exec-broker — conservative network-target extraction (Pillar 3 step 4). + * + * Design: `pillar3-exec-broker-5.0.md` §3.3 / §6.2 — the egress-gate inspects a pending Bash + * command for its network targets. Extraction is deliberately CONSERVATIVE and unambiguous: + * only explicit `http://` / `https://` URLs are parsed (via the WHATWG URL parser), because a + * bare word like `api.acme.com` in a command is ambiguous (an argument? a filename?) and a + * false "network target" would break legitimate work. A command that reaches the network + * without an explicit URL is out of this extractor's reach — honest limitation, documented, + * not papered over. Pure + deterministic: same command → same hosts (unique, sorted). + */ + +const URL_RE = /https?:\/\/[^\s"'`<>\\)\];]+/gi; + +/** Unique, sorted, lowercased hostnames of every explicit http(s) URL in a shell command. */ +export function extractHostsFromCommand(command: string): string[] { + const hosts = new Set(); + for (const match of command.match(URL_RE) ?? []) { + try { + const u = new URL(match); + if (u.hostname) hosts.add(u.hostname.toLowerCase()); + } catch { + /* not a parseable URL after all — skip (conservative: never guess) */ + } + } + return [...hosts].sort(); +} diff --git a/src/broker/gates.test.ts b/src/broker/gates.test.ts new file mode 100644 index 00000000..8218f302 --- /dev/null +++ b/src/broker/gates.test.ts @@ -0,0 +1,119 @@ +/** + * Integration tests for the exec-broker PreToolUse gates (`kit gate-egress` / `kit gate-fs`): + * spawn the REAL compiled CLI with a hook payload on stdin, in a temp project, and assert on + * the exit code — exactly how an agent harness runs the gate. exit 0 = allow, exit 2 = deny. + */ +import { describe, it, beforeEach, afterEach } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { loadOrCreateIdentity } from "../identity.js"; +import { PROFILE_FILE } from "../profile/schema.js"; +import { signProfile } from "../profile/sign.js"; + +const CLI = fileURLToPath(new URL("../cli.js", import.meta.url)); + +let idDir: string; +let proj: string; +let savedIdEnv: string | undefined; + +const SCOPED = `version = 1 +[scope] +egress = ["api.acme.com"] +fs = ["src"] +`; + +function runGate(gate: string, payload: unknown): { status: number | null; stderr: string } { + const res = spawnSync(process.execPath, [CLI, gate], { + input: JSON.stringify(payload), + cwd: proj, + encoding: "utf8", + env: { + ...process.env, + KIT_IDENTITY_DIR: idDir, + KIT_NON_INTERACTIVE: "1", + KIT_NO_UPDATE_CHECK: "1", + KIT_BUMBLEBEE: "0", + KIT_NO_FAILURE_SIM: "1", + }, + }); + return { status: res.status, stderr: res.stderr ?? "" }; +} + +const bash = (command: string) => ({ tool_name: "Bash", tool_input: { command } }); +const write = (file_path: string) => ({ + tool_name: "Write", + tool_input: { file_path, content: "x" }, +}); + +beforeEach(async () => { + idDir = mkdtempSync(join(tmpdir(), "kit-id-")); + proj = mkdtempSync(join(tmpdir(), "kit-gates-")); + savedIdEnv = process.env.KIT_IDENTITY_DIR; + process.env.KIT_IDENTITY_DIR = idDir; + loadOrCreateIdentity(); + writeFileSync(join(proj, PROFILE_FILE), SCOPED); + await signProfile(proj); +}); + +afterEach(() => { + if (savedIdEnv === undefined) delete process.env.KIT_IDENTITY_DIR; + else process.env.KIT_IDENTITY_DIR = savedIdEnv; + rmSync(idDir, { recursive: true, force: true }); + rmSync(proj, { recursive: true, force: true }); +}); + +describe("kit gate-egress (subprocess)", () => { + it("allows an in-scope host and non-network commands", () => { + assert.equal(runGate("gate-egress", bash("curl https://api.acme.com/v1")).status, 0); + assert.equal(runGate("gate-egress", bash("npm test")).status, 0); + }); + + it("denies (exit 2) an off-scope host with an honest reason", () => { + const r = runGate("gate-egress", bash("curl https://evil.example.com/x")); + assert.equal(r.status, 2); + assert.match(r.stderr, /outside the signed egress scope/); + assert.match(r.stderr, /evil\.example\.com/); + }); + + it("denies ALL network targets when the scope is unsigned (wired gate grants nothing)", () => { + rmSync(join(proj, ".kit-profile.sig"), { force: true }); + const r = runGate("gate-egress", bash("curl https://api.acme.com/v1")); + assert.equal(r.status, 2); + assert.match(r.stderr, /no verified scope/); + }); + + it("fails open only on a non-command / unparseable envelope", () => { + assert.equal(runGate("gate-egress", { tool_name: "Read", tool_input: {} }).status, 0); + }); +}); + +describe("kit gate-fs (subprocess)", () => { + it("allows a write inside the signed fs scope", () => { + assert.equal(runGate("gate-fs", write("src/index.ts")).status, 0); + }); + + it("denies (exit 2) a write outside the signed fs scope", () => { + const r = runGate("gate-fs", write("secrets/creds.txt")); + assert.equal(r.status, 2); + assert.match(r.stderr, /outside the signed fs scope/); + }); + + it("denies a traversal escape out of the project root", () => { + assert.equal(runGate("gate-fs", write("../outside.txt")).status, 2); + }); + + it("denies writes when the profile was tampered after signing (fail-closed)", () => { + writeFileSync(join(proj, PROFILE_FILE), SCOPED.replace("src", "anything")); + const r = runGate("gate-fs", write("src/index.ts")); + assert.equal(r.status, 2); + assert.match(r.stderr, /no verified scope/); + }); + + it("passes non-write tool calls through", () => { + assert.equal(runGate("gate-fs", bash("ls")).status, 0); + }); +}); diff --git a/src/cli.ts b/src/cli.ts index b73d6a2b..35facf22 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -49,7 +49,7 @@ import { cmdTeam, } from "./commands/agent.js"; import { cmdSelfAudit, cmdCoverage, cmdAnalyze } from "./commands/coverage.js"; -import { cmdGateBash, cmdGateEnv } from "./commands/gate.js"; +import { cmdGateBash, cmdGateEnv, cmdGateEgress, cmdGateFs } from "./commands/gate.js"; import { cmdCi } from "./commands/ci.js"; import { cmdSentinel } from "./commands/sentinel.js"; import { cmdStandards, cmdBaseline } from "./commands/standards.js"; @@ -705,6 +705,16 @@ const COMMAND_REGISTRY: Record = { stability: "experimental", help: "PreToolUse env-gate: read an agent's pending Write/Edit on stdin, block (exit 2) plaintext secrets aimed at .env* files", }, + "gate-egress": { + handler: cmdGateEgress, + stability: "experimental", + help: "PreToolUse egress-gate (exec-broker): block (exit 2) Bash network targets outside the signed [scope].egress — fail-closed without a verified scope", + }, + "gate-fs": { + handler: cmdGateFs, + stability: "experimental", + help: "PreToolUse fs-gate (exec-broker): block (exit 2) Write/Edit outside the signed [scope].fs — fail-closed without a verified scope", + }, }; // Help for multi-word sub-commands (e.g. `kit memory search`). Help-only: no diff --git a/src/commands/gate.ts b/src/commands/gate.ts index a7f8b571..22637e8f 100644 --- a/src/commands/gate.ts +++ b/src/commands/gate.ts @@ -112,6 +112,131 @@ export async function cmdGateEnv(): Promise { return true; } +/** + * Shared stdin reader for the exec-broker gates: the pending-tool-call JSON, or `null` when + * the envelope is unreadable/unparseable. The envelope comes from the agent HARNESS (not the + * model), so an unparseable one is a harness/config problem — fail-open like gate-bash/gate-env + * (never break the agent on garbage), while the scope decisions themselves stay fail-closed. + */ +async function readHookPayload(): Promise { + let raw = ""; + try { + const chunks: Buffer[] = []; + for await (const chunk of process.stdin) chunks.push(chunk as Buffer); + raw = Buffer.concat(chunks).toString("utf8"); + } catch { + return null; + } + try { + return raw ? (JSON.parse(raw) as unknown) : null; + } catch { + return null; + } +} + +/** Deny helper for the broker gates: Cline stdout-JSON contract or exit-2 PreToolUse deny. */ +async function gateDeny(label: string, message: string): Promise { + if (gateFormat() === "cline") { + console.log(JSON.stringify({ cancel: true, errorMessage: `kit ${label}: ${message}` })); + return true; + } + const { writeSync } = await import("node:fs"); + writeSync(2, `kit ${label}: BLOCKED — ${message}\n`); + process.exit(2); // PreToolUse deny +} + +/** + * Best-effort audit of a broker-gate deny (design §3.3: every deny leaves an audit entry). + * Wrapped: a missing/unreadable .kit.toml or audit backend must never change the verdict — + * the deny already happened, and deny is the safe outcome. + */ +async function auditGateDeny(gate: string, reason: string): Promise { + try { + const { loadConfig } = await import("../config.js"); + const { mergeGovernanceConfigAsync } = await import("../governance.js"); + const { logAuditEvent } = await import("../audit.js"); + const { resolve } = await import("node:path"); + const cfg = await loadConfig(resolve(process.cwd(), ".kit.toml")); + const gov = await mergeGovernanceConfigAsync(cfg.governance); + await logAuditEvent(gov, { + operation: gate, + environment: gov.environment, + success: false, + error: reason, + metadata: { phase: "pretooluse-deny" }, + }); + } catch { + /* best-effort — see above */ + } +} + +/** + * `kit gate-egress` — PreToolUse egress-gate (exec-broker, Pillar 3). Reads the pending tool + * call on stdin; if it is a Bash command with explicit http(s) network targets, they must all + * be inside the SIGNED [scope].egress (verified via brokerScope — fail-closed: a wired gate + * with no verified scope grants nothing). Off-scope → exit 2 + audit. Commands without an + * unambiguous URL pass through (conservative extraction; see broker/extract.ts). + */ +export async function cmdGateEgress(): Promise { + const payload = await readHookPayload(); + if (payload === null) return true; // unreadable envelope → never break the agent + const { extractCommandFromHookPayload } = await import("../install-gate.js"); + const command = extractCommandFromHookPayload(payload); + if (!command) return true; // not a shell command → allow + const { extractHostsFromCommand } = await import("../broker/extract.js"); + const hosts = extractHostsFromCommand(command); + if (hosts.length === 0) return true; // no unambiguous network target → allow + + const { brokerScope } = await import("../broker/decide.js"); + const scope = await brokerScope(process.cwd()); + let denied: string[]; + let why: string; + if (!scope) { + denied = hosts; + why = `network egress to ${hosts.join(", ")} denied — no verified scope/RoE (unsigned, tampered, or missing); a wired egress-gate grants nothing`; + } else { + const { hostInScope } = await import("../broker/scope.js"); + denied = hosts.filter((h) => !hostInScope(h, scope)); + why = `host(s) outside the signed egress scope: ${denied.join(", ")}`; + } + if (denied.length === 0) return true; + await auditGateDeny("gate-egress", why); + return await gateDeny( + "egress-gate", + `${why}\nDeclare the host in .kit-profile.toml [scope].egress and re-sign: \`kit profile sign\`.`, + ); +} + +/** + * `kit gate-fs` — PreToolUse fs-gate (exec-broker, Pillar 3). Reads the pending tool call on + * stdin; a Write/Edit must target a path inside the SIGNED [scope].fs (default: the project + * root), verified via brokerScope — fail-closed: a wired gate with no verified scope grants + * nothing. Off-scope → exit 2 + audit. Non-write tool calls pass through. + */ +export async function cmdGateFs(): Promise { + const payload = await readHookPayload(); + if (payload === null) return true; // unreadable envelope → never break the agent + const { extractWriteFromHookPayload } = await import("../env-write-gate.js"); + const write = extractWriteFromHookPayload(payload); + if (!write) return true; // not a file write → allow + + const { brokerScope } = await import("../broker/decide.js"); + const scope = await brokerScope(process.cwd()); + if (!scope) { + const why = `write to ${write.filePath} denied — no verified scope/RoE (unsigned, tampered, or missing); a wired fs-gate grants nothing`; + await auditGateDeny("gate-fs", why); + return await gateDeny("fs-gate", `${why}\nSign the profile scope: \`kit profile sign\`.`); + } + const { pathInScope } = await import("../broker/scope.js"); + if (pathInScope(write.filePath, scope, process.cwd())) return true; + const why = `write outside the signed fs scope: ${write.filePath}`; + await auditGateDeny("gate-fs", why); + return await gateDeny( + "fs-gate", + `${why}\nDeclare the path in .kit-profile.toml [scope].fs and re-sign: \`kit profile sign\`.`, + ); +} + /** The `--format ` value for gate-bash (`--format cline` | `--format=cline`). */ function gateFormat(): string { const argv = process.argv;