diff --git a/src/broker/needs.test.ts b/src/broker/needs.test.ts new file mode 100644 index 00000000..aa1622e7 --- /dev/null +++ b/src/broker/needs.test.ts @@ -0,0 +1,169 @@ +import { describe, it, beforeEach, afterEach } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { loadOrCreateIdentity } from "../identity.js"; +import { PROFILE_FILE } from "../profile/schema.js"; +import { signProfile } from "../profile/sign.js"; +import { checkScopeNeeds } from "./needs.js"; +import { withGovernance } from "../governance-middleware.js"; +import type { kitConfig, GovernanceConfig } from "../config.js"; + +let idDir: string; +let proj: string; +let savedIdEnv: string | undefined; +let savedCwd: string; + +const SCOPED = `version = 1 +[scope] +egress = ["api.acme.com"] +fs = ["src"] +secrets = ["DATABASE_URL"] +`; + +// Governance enabled with safe test defaults (mirrors governance-middleware.test.ts): +// audit/revocation/expiry off, no approval prompts. +function makeConfig(govOverrides: Partial = {}): kitConfig { + return { + governance: { + enabled: true, + environment: "dev", + audit: { enabled: false }, + revocation: { enabled: false }, + secrets: { check_expiration: false }, + approval: { destructive_operations: [], production_writes: false }, + ...govOverrides, + }, + }; +} + +beforeEach(() => { + idDir = mkdtempSync(join(tmpdir(), "kit-id-")); + proj = mkdtempSync(join(tmpdir(), "kit-needs-")); + savedIdEnv = process.env.KIT_IDENTITY_DIR; + process.env.KIT_IDENTITY_DIR = idDir; + savedCwd = process.cwd(); + process.chdir(proj); + loadOrCreateIdentity(); +}); + +afterEach(() => { + process.chdir(savedCwd); + 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 }); +}); + +async function signScoped(): Promise { + writeFileSync(join(proj, PROFILE_FILE), SCOPED); + await signProfile(proj); +} + +describe("checkScopeNeeds", () => { + it("allows everything when no scope regime is declared (advisory floor unchanged)", async () => { + assert.equal(await checkScopeNeeds({ egress: ["evil.com"] }, proj), null); + }); + + it("allows an empty declaration without consulting the scope", async () => { + assert.equal(await checkScopeNeeds({}, proj), null); + assert.equal(await checkScopeNeeds({ egress: [] }, proj), null); + }); + + it("denies declared needs when the scope is declared but unsigned (fail-closed)", async () => { + writeFileSync(join(proj, PROFILE_FILE), SCOPED); + const denial = await checkScopeNeeds({ egress: ["api.acme.com"] }, proj); + assert.match(denial ?? "", /scope enforcement/); + assert.match(denial ?? "", /fail-closed/); + }); + + it("grants in-scope needs and denies off-scope ones against a verified scope", async () => { + await signScoped(); + assert.equal( + await checkScopeNeeds( + { egress: ["api.acme.com"], fsWrites: ["src/x.ts"], secrets: ["DATABASE_URL"] }, + proj, + ), + null, + ); + assert.match( + (await checkScopeNeeds({ egress: ["evil.com"] }, proj)) ?? "", + /egress to evil\.com/, + ); + assert.match( + (await checkScopeNeeds({ fsWrites: ["secrets/creds"] }, proj)) ?? "", + /write to secrets\/creds/, + ); + assert.match( + (await checkScopeNeeds({ secrets: ["AWS_SECRET"] }, proj)) ?? "", + /secret\(s\) AWS_SECRET/, + ); + }); + + it("denies declared needs after the profile is tampered (fail-closed)", async () => { + await signScoped(); + writeFileSync(join(proj, PROFILE_FILE), SCOPED.replace("api.acme.com", "evil.com")); + assert.match( + (await checkScopeNeeds({ egress: ["evil.com"] }, proj)) ?? "", + /scope enforcement/, + ); + }); +}); + +describe("withGovernance + scopeNeeds (exec-broker proper)", () => { + it("runs an operation whose declared needs are inside the verified scope", async () => { + await signScoped(); + const result = await withGovernance( + makeConfig(), + { + operation: "deploy", + operationType: "write", + scopeNeeds: { egress: ["api.acme.com"], secrets: ["DATABASE_URL"] }, + }, + async () => "ran", + ); + assert.equal(result, "ran"); + }); + + it("rejects (never executes) an operation with off-scope needs", async () => { + await signScoped(); + let executed = false; + await assert.rejects( + withGovernance( + makeConfig(), + { + operation: "exfil", + operationType: "write", + scopeNeeds: { egress: ["evil.com"] }, + }, + async () => { + executed = true; + }, + ), + /scope enforcement/, + ); + assert.equal(executed, false); + }); + + it("rejects declared needs when the scope regime is unsigned (fail-closed)", async () => { + writeFileSync(join(proj, PROFILE_FILE), SCOPED); + await assert.rejects( + withGovernance( + makeConfig(), + { operation: "op", operationType: "write", scopeNeeds: { secrets: ["DATABASE_URL"] } }, + async () => "x", + ), + /scope enforcement/, + ); + }); + + it("is backward compatible: no profile + no scopeNeeds ⇒ unchanged behavior", async () => { + const result = await withGovernance( + makeConfig(), + { operation: "plain", operationType: "write" }, + async () => "ok", + ); + assert.equal(result, "ok"); + }); +}); diff --git a/src/broker/needs.ts b/src/broker/needs.ts new file mode 100644 index 00000000..b1afb471 --- /dev/null +++ b/src/broker/needs.ts @@ -0,0 +1,69 @@ +/** + * kit exec-broker — declared operation needs vs the signed scope (Pillar 3 step 5). + * + * Design: `pillar3-exec-broker-5.0.md` §3.4 / §6.4. An operation running under + * `withGovernance` DECLARES what it is about to touch — hosts, write paths, secret env keys — + * and this module answers whether the signed `[scope]`/RoE grants it. This is what makes the + * governance floor an exec-broker: secret-scoped env lives here (an op that doesn't declare a + * key doesn't get it granted), alongside egress and fs. + * + * Opt-in semantics, mirrored from the PreToolUse gates but adapted to a floor that runs for + * EVERY governed op: + * - no scope regime declared at all ("none") → nothing to enforce; advisory floor unchanged + * (backward compatible — projects without a profile see no behavior change); + * - a scope IS declared but unsigned/tampered ("unsigned"/"invalid") → the regime exists but + * is not trustworthy: declared needs are DENIED (fail-closed — declaring a scope is the + * opt-in, and only a verified one grants); + * - verified → each declared need must be inside the scope (pure predicates from scope.ts). + * + * Deterministic, zero-LLM, local-only. + */ +import { brokerStatus } from "./decide.js"; +import { hostInScope, pathInScope, secretInScope } from "./scope.js"; + +/** What a governed operation declares it is about to touch. All fields optional/additive. */ +export interface ScopeNeeds { + /** Hosts the operation will contact. */ + egress?: string[]; + /** Paths the operation will write. */ + fsWrites?: string[]; + /** Secret env keys the operation needs exposed (secret-scoped env). */ + secrets?: string[]; +} + +/** + * Check declared needs against the project's scope regime. Returns a human-readable denial + * reason, or `null` when allowed. Never throws (an error along the trust path surfaces as a + * denial via brokerStatus's `invalid` state, not an exception). + */ +export async function checkScopeNeeds( + needs: ScopeNeeds, + cwd = process.cwd(), +): Promise { + const declaresAnything = + (needs.egress?.length ?? 0) > 0 || + (needs.fsWrites?.length ?? 0) > 0 || + (needs.secrets?.length ?? 0) > 0; + if (!declaresAnything) return null; + + const st = await brokerStatus(cwd); + if (st.state === "none") return null; // no RoE regime declared — advisory floor unchanged + if (st.state !== "verified" || !st.scope) { + return `scope enforcement: ${st.detail}`; + } + + const scope = st.scope; + const deniedHosts = (needs.egress ?? []).filter((h) => !hostInScope(h, scope)); + if (deniedHosts.length > 0) { + return `scope enforcement: egress to ${deniedHosts.join(", ")} is outside the signed [scope].egress`; + } + const deniedPaths = (needs.fsWrites ?? []).filter((p) => !pathInScope(p, scope, cwd)); + if (deniedPaths.length > 0) { + return `scope enforcement: write to ${deniedPaths.join(", ")} is outside the signed [scope].fs`; + } + const deniedSecrets = (needs.secrets ?? []).filter((k) => !secretInScope(k, scope)); + if (deniedSecrets.length > 0) { + return `scope enforcement: secret(s) ${deniedSecrets.join(", ")} outside the signed [scope].secrets`; + } + return null; +} diff --git a/src/governance-middleware.ts b/src/governance-middleware.ts index be718682..70d3a612 100644 --- a/src/governance-middleware.ts +++ b/src/governance-middleware.ts @@ -13,6 +13,7 @@ import { formatSecretExpirationWarnings, hasExpiredSecrets, } from "./secret-expiration.js"; +import { checkScopeNeeds, type ScopeNeeds } from "./broker/needs.js"; export interface OperationContext { operation: string; @@ -20,6 +21,13 @@ export interface OperationContext { destructive?: boolean; metadata?: Record; estimatedTokens?: number; + /** + * What this operation is about to touch (hosts / write paths / secret env keys) — the + * exec-broker's input (Pillar 3). Optional and additive: undeclared ⇒ no scope check (the + * advisory floor is unchanged). When declared AND the project declares a [scope]/RoE, every + * need must be inside the VERIFIED scope — see broker/needs.ts for the fail-closed rules. + */ + scopeNeeds?: ScopeNeeds; } export interface GovernanceResult { @@ -70,6 +78,18 @@ export async function withGovernance( throw new Error(budgetCheck.reason || "Budget limit exceeded"); } + // 2.5 Scope enforcement (exec-broker, Pillar 3): declared needs vs the signed [scope]/RoE. + // Checked BEFORE any approval prompt — a scope denial is not operator-overridable (the + // RoE is a signed artifact; widening it means editing + re-signing the profile), so the + // operator is never prompted to approve an operation that will be scope-denied anyway. + if (context.scopeNeeds) { + const scopeDenial = await checkScopeNeeds(context.scopeNeeds); + if (scopeDenial) { + await auditDeny(scopeDenial); + throw new Error(scopeDenial); + } + } + // Track whether the operator already approved this op in step 3, so a // destructive op that also needed permission-approval isn't prompted twice. let approvedForOp = false;