diff --git a/src/broker/decide.test.ts b/src/broker/decide.test.ts deleted file mode 100644 index 8d4267ec..00000000 --- a/src/broker/decide.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -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 { brokerStatus, brokerScope } from "./decide.js"; - -let idDir: string; -let proj: string; -let savedIdEnv: string | undefined; - -const SCOPED = `version = 1 -name = "acme" -[scope] -egress = ["api.acme.com"] -fs = ["."] -secrets = ["DATABASE_URL"] -`; - -beforeEach(() => { - idDir = mkdtempSync(join(tmpdir(), "kit-id-")); - proj = mkdtempSync(join(tmpdir(), "kit-broker-")); - savedIdEnv = process.env.KIT_IDENTITY_DIR; - process.env.KIT_IDENTITY_DIR = idDir; - loadOrCreateIdentity(); -}); - -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("brokerStatus", () => { - it("reports none when no profile is declared", async () => { - const st = await brokerStatus(proj); - assert.equal(st.state, "none"); - assert.equal(st.scope, null); - }); - - it("reports none when the profile declares no [scope]", async () => { - writeFileSync(join(proj, PROFILE_FILE), `version = 1\nname = "no-scope"\n`); - const st = await brokerStatus(proj); - assert.equal(st.state, "none"); - assert.match(st.detail, /no \[scope\]/); - }); - - it("reports unsigned (grants nothing) for a declared-but-unsigned scope", async () => { - writeFileSync(join(proj, PROFILE_FILE), SCOPED); - const st = await brokerStatus(proj); - assert.equal(st.state, "unsigned"); - assert.equal(st.scope, null); - assert.match(st.detail, /fail-closed/); - }); - - it("reports verified with the governing scope for a signed profile", async () => { - writeFileSync(join(proj, PROFILE_FILE), SCOPED); - await signProfile(proj); - const st = await brokerStatus(proj); - assert.equal(st.state, "verified"); - assert.deepEqual(st.scope?.egress, ["api.acme.com"]); - assert.match(st.detail, /1 egress host/); - }); - - it("reports invalid (grants nothing) when the profile was tampered after signing", async () => { - writeFileSync(join(proj, PROFILE_FILE), SCOPED); - await signProfile(proj); - writeFileSync(join(proj, PROFILE_FILE), SCOPED.replace("api.acme.com", "evil.example.com")); - const st = await brokerStatus(proj); - assert.equal(st.state, "invalid"); - assert.equal(st.scope, null); - }); - - it("reports invalid (never throws) on a malformed profile", async () => { - writeFileSync(join(proj, PROFILE_FILE), "not = = toml"); - const st = await brokerStatus(proj); - assert.equal(st.state, "invalid"); - assert.match(st.detail, /unreadable/); - }); -}); - -describe("brokerScope (fail-closed)", () => { - it("returns the scope only for a verified signature", async () => { - writeFileSync(join(proj, PROFILE_FILE), SCOPED); - await signProfile(proj); - const scope = await brokerScope(proj); - assert.deepEqual(scope?.secrets, ["DATABASE_URL"]); - }); - - it("returns null for unsigned, tampered, malformed, and absent profiles", async () => { - assert.equal(await brokerScope(proj), null); // absent - - writeFileSync(join(proj, PROFILE_FILE), SCOPED); // unsigned - assert.equal(await brokerScope(proj), null); - - await signProfile(proj); // tampered after signing - writeFileSync(join(proj, PROFILE_FILE), SCOPED.replace("acme", "evil")); - assert.equal(await brokerScope(proj), null); - - writeFileSync(join(proj, PROFILE_FILE), "not = = toml"); // malformed — never throws - assert.equal(await brokerScope(proj), null); - }); -}); diff --git a/src/broker/decide.ts b/src/broker/decide.ts deleted file mode 100644 index 58b51cf9..00000000 --- a/src/broker/decide.ts +++ /dev/null @@ -1,102 +0,0 @@ -/** - * kit exec-broker — the fail-closed scope source + honest status (Pillar 3 steps 2–3). - * - * Design: `kit-research/docs/research/pillar3-exec-broker-5.0.md` §3.2. - * - * The broker's SCOPE comes from exactly one place: the profile's signed `[scope]`/RoE via - * `verifiedScope()` (Pillar 4). This module wraps that source for the ENFORCEMENT paths: - * - * - `brokerScope(cwd)` — never-throws: any error (malformed profile, unreadable sig, …) - * resolves to `null`, and a `null` scope GRANTS NOTHING. An enforcement point must never - * crash open — an exception in the trust path is a deny, not a bypass. - * - `brokerStatus(cwd)` — the honest posture for `kit doctor`: verified / unsigned / - * invalid / none. "Enforced" must never silently mean "no-op", and a degradation - * (declared-but-unsigned scope) is surfaced, never swallowed. - * - * Deterministic, zero-LLM, local-only (file reads + offline signature verify). - */ -import { loadProfile, type ProfileScope } from "../profile/schema.js"; -import { verifyProfileSignature } from "../profile/sign.js"; - -export type BrokerScopeState = - /** A `[scope]` is declared and its signature verifies — this scope governs. */ - | "verified" - /** A `[scope]` is declared but unsigned / signer unknown — grants nothing (fail-closed). */ - | "unsigned" - /** Signature invalid/revoked, or the profile itself is malformed — grants nothing. */ - | "invalid" - /** No profile or no `[scope]` section — there is no RoE for the broker to enforce. */ - | "none"; - -export interface BrokerStatus { - state: BrokerScopeState; - /** The governing scope — non-null ONLY when state is "verified". */ - scope: ProfileScope | null; - detail: string; -} - -/** - * The broker's honest posture. Never throws — a malformed profile is reported as `invalid` - * (a broken artifact must not crash the status surface, and must never read as healthy). - */ -export async function brokerStatus(cwd = process.cwd()): Promise { - let scope: ProfileScope | undefined; - try { - const profile = await loadProfile(cwd); - if (!profile) return { state: "none", scope: null, detail: "no profile declared" }; - scope = profile.scope; - } catch (err) { - return { - state: "invalid", - scope: null, - detail: `profile unreadable — ${err instanceof Error ? err.message : String(err)}`, - }; - } - if (!scope) { - return { state: "none", scope: null, detail: "profile declares no [scope]/RoE" }; - } - - const v = await verifyProfileSignature(cwd); - switch (v.status) { - case "valid": { - const parts = [ - `${scope.egress?.length ?? 0} egress host(s)`, - `${scope.fs?.length ?? 0} fs path(s)`, - `${scope.secrets?.length ?? 0} secret key(s)`, - ]; - return { - state: "verified", - scope, - detail: `scope verified — ${parts.join(", ")} (${v.detail})`, - }; - } - case "unsigned": - case "unverifiable": - return { - state: "unsigned", - scope: null, - detail: `scope declared but ${v.detail} — grants nothing (fail-closed)`, - }; - case "invalid": - case "revoked": - return { - state: "invalid", - scope: null, - detail: `scope signature ${v.status} — ${v.detail}; grants nothing (fail-closed)`, - }; - } -} - -/** - * The scope the enforcement points act on: the verified `[scope]`, or `null` when anything - * along the trust path is missing, broken, or forged. Never throws — an exception in the - * trust path is a deny (`null`), not a bypass. - */ -export async function brokerScope(cwd = process.cwd()): Promise { - try { - const st = await brokerStatus(cwd); - return st.state === "verified" ? st.scope : null; - } catch { - return null; - } -} diff --git a/src/broker/needs.ts b/src/broker/needs.ts deleted file mode 100644 index b1afb471..00000000 --- a/src/broker/needs.ts +++ /dev/null @@ -1,69 +0,0 @@ -/** - * 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/broker/scope.test.ts b/src/broker/scope.test.ts deleted file mode 100644 index 258008a6..00000000 --- a/src/broker/scope.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { describe, it } from "node:test"; -import assert from "node:assert/strict"; -import { hostInScope, pathInScope, secretInScope, isLoopbackOrPrivate } from "./scope.js"; -import type { ProfileScope } from "../profile/schema.js"; - -describe("hostInScope", () => { - const scope: ProfileScope = { egress: ["api.acme.com", "acme.io"] }; - - it("allows an exact allowlisted host", () => { - assert.equal(hostInScope("api.acme.com", scope), true); - }); - it("allows a subdomain of an allowlisted entry", () => { - assert.equal(hostInScope("eu.acme.io", scope), true); - assert.equal(hostInScope("a.b.acme.io", scope), true); - }); - it("denies an unrelated host and a sibling/suffix trick", () => { - assert.equal(hostInScope("evil.com", scope), false); - assert.equal(hostInScope("notacme.io", scope), false); // suffix without a dot boundary - assert.equal(hostInScope("acme.io.evil.com", scope), false); - }); - it("denies everything when egress is undefined or empty", () => { - assert.equal(hostInScope("api.acme.com", {}), false); - assert.equal(hostInScope("api.acme.com", { egress: [] }), false); - }); - it("never subdomain-matches loopback/private, but honors an exact listing", () => { - assert.equal(hostInScope("127.0.0.1", { egress: ["0.0.0.1"] }), false); - assert.equal(hostInScope("localhost", { egress: ["host"] }), false); // no subdomain match to loopback - assert.equal(hostInScope("localhost", { egress: ["localhost"] }), true); // explicit wins - }); - it("is case-insensitive and tolerates a trailing FQDN dot", () => { - assert.equal(hostInScope("API.ACME.COM.", scope), true); - }); -}); - -describe("isLoopbackOrPrivate", () => { - it("flags loopback, link-local, and RFC1918 ranges", () => { - for (const h of [ - "localhost", - "127.0.0.1", - "::1", - "10.1.2.3", - "192.168.0.5", - "172.16.0.1", - "169.254.1.1", - ]) { - assert.equal(isLoopbackOrPrivate(h), true, h); - } - }); - it("does not flag public hosts or 172.15/172.32 (outside the private block)", () => { - for (const h of ["api.acme.com", "8.8.8.8", "172.15.0.1", "172.32.0.1"]) { - assert.equal(isLoopbackOrPrivate(h), false, h); - } - }); -}); - -describe("pathInScope", () => { - const root = "/proj"; - - it("allows writes inside the default root when fs is unspecified", () => { - assert.equal(pathInScope("src/x.ts", {}, root), true); - assert.equal(pathInScope("/proj/src/x.ts", {}, root), true); - }); - it("denies a traversal escape out of the root", () => { - assert.equal(pathInScope("../etc/passwd", {}, root), false); - assert.equal(pathInScope("/etc/passwd", {}, root), false); - }); - it("honors an explicit fs sub-scope", () => { - const scope: ProfileScope = { fs: ["src", "dist"] }; - assert.equal(pathInScope("src/a.ts", scope, root), true); - assert.equal(pathInScope("dist/b.js", scope, root), true); - assert.equal(pathInScope("secrets/c", scope, root), false); - }); - it("treats the scope root itself as in-scope", () => { - assert.equal(pathInScope(".", {}, root), true); - }); -}); - -describe("secretInScope", () => { - it("permits only declared keys; empty/undefined ⇒ none", () => { - assert.equal(secretInScope("DATABASE_URL", { secrets: ["DATABASE_URL"] }), true); - assert.equal(secretInScope("AWS_SECRET", { secrets: ["DATABASE_URL"] }), false); - assert.equal(secretInScope("ANY", {}), false); - assert.equal(secretInScope("ANY", { secrets: [] }), false); - }); -}); diff --git a/src/broker/scope.ts b/src/broker/scope.ts deleted file mode 100644 index 0ed1b2bd..00000000 --- a/src/broker/scope.ts +++ /dev/null @@ -1,76 +0,0 @@ -/** - * kit exec-broker — the pure scope-decision core (Pillar 3, 5.0-rc). - * - * Design: `kit-research/docs/research/pillar3-exec-broker-5.0.md` §3.1. - * - * Three deterministic, zero-LLM predicates that answer "is this action inside the agent's - * SCOPE?" against a `ProfileScope` (the signed RoE from Pillar 4). No I/O — the caller supplies - * the already-resolved inputs; the enforcement points (PreToolUse hooks, `withGovernance`) sit - * ABOVE this and feed it the scope via `verifiedScope()` (fail-closed: a null scope never - * reaches here). Pure ⇒ fully unit-testable and safe to diff in CI. - * - * Fail-closed field semantics (within a valid scope): - * - egress: undefined/empty ⇒ NO host allowed (network must be declared explicitly); - * - fs: undefined/empty ⇒ default to the project root "."; - * - secrets: undefined/empty ⇒ NO secret exposed (secret-scoped by default). - */ -import { resolve, relative, isAbsolute } from "node:path"; -import type { ProfileScope } from "../profile/schema.js"; - -/** - * True when `host` is loopback / link-local / an RFC1918 private address. Such hosts are denied - * by SUBDOMAIN matching (they may only be reached if listed VERBATIM in the egress allowlist), - * so a broad `example.com` entry can never be tricked into permitting an internal target. - */ -export function isLoopbackOrPrivate(host: string): boolean { - const h = host.toLowerCase(); - if (h === "localhost" || h.endsWith(".localhost")) return true; - if (h === "0.0.0.0" || h === "::1" || h === "[::1]") return true; - if (/^127\./.test(h)) return true; - if (/^10\./.test(h)) return true; - if (/^192\.168\./.test(h)) return true; - if (/^169\.254\./.test(h)) return true; // link-local - if (/^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(h)) return true; // 172.16.0.0 – 172.31.255.255 - return false; -} - -/** - * Is `host` reachable under this scope's egress allowlist? An exact allowlist entry always wins - * (even a deliberately-listed internal host). Otherwise a host matches an entry when it equals it - * or is a subdomain of it (`api.acme.com` matches entry `acme.com`) — but loopback/private hosts - * are never subdomain-matched. Undefined/empty egress ⇒ nothing is reachable. - */ -export function hostInScope(host: string, scope: ProfileScope): boolean { - const egress = scope.egress ?? []; - const h = host.toLowerCase().replace(/\.$/, ""); // drop a trailing FQDN dot - const entries = egress.map((e) => e.toLowerCase().replace(/\.$/, "")); - if (entries.includes(h)) return true; - if (isLoopbackOrPrivate(h)) return false; - return entries.some((e) => e.length > 0 && h.endsWith(`.${e}`)); -} - -/** - * Is a write to `targetPath` inside this scope's filesystem write-scope? Paths are resolved - * against `root` and compared with a traversal-safe containment check (a `..` escape lands - * outside and is denied). Undefined/empty `fs` defaults to the project root ".". - */ -export function pathInScope(targetPath: string, scope: ProfileScope, root: string): boolean { - const base = resolve(root); - const target = isAbsolute(targetPath) ? resolve(targetPath) : resolve(base, targetPath); - const fsScopes = scope.fs && scope.fs.length > 0 ? scope.fs : ["."]; - return fsScopes.some((entry) => { - const allowed = isAbsolute(entry) ? resolve(entry) : resolve(base, entry); - if (target === allowed) return true; - const rel = relative(allowed, target); - // Inside `allowed` iff the relative path doesn't climb out (no leading "..") and isn't absolute. - return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel); - }); -} - -/** - * Is the secret `key` allowed to be exposed for an operation under this scope? Secret-scoped by - * default: only keys listed in `scope.secrets` are permitted; undefined/empty ⇒ none. - */ -export function secretInScope(key: string, scope: ProfileScope): boolean { - return (scope.secrets ?? []).includes(key); -} diff --git a/src/doctor.ts b/src/doctor.ts index e3b16058..4a16f89a 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -5,7 +5,8 @@ import { promisify } from "node:util"; import type { kitConfig } from "./config.js"; import { resolveToolBin } from "./utils/resolveTool.js"; import { activeKeyStoreStatus, hardwareRequired } from "./keystore/active.js"; -import { brokerStatus } from "./broker/decide.js"; +import { profileBrokerPolicy } from "./exec-broker/profile-policy.js"; +import { verifyProfileSignature } from "./profile/sign.js"; const execFileAsync = promisify(execFile); @@ -260,21 +261,36 @@ function checkIdentityKeystore(): DoctorCheck { async function checkBrokerScope(cwd: string): Promise { const name = "exec-broker scope"; const category = "security"; - const st = await brokerStatus(cwd); - switch (st.state) { - case "verified": - return { name, status: "pass", detail: st.detail, category }; - case "none": - return { - name, - status: "skip", - detail: `${st.detail} — declare [scope] in .kit-profile.toml and run 'kit profile sign' to arm the exec-broker`, - category, - }; - case "unsigned": - return { name, status: "warn", detail: `${st.detail}; run 'kit profile sign'`, category }; - case "invalid": - return { name, status: "fail", detail: st.detail, category }; + // The canonical broker's signed-scope provider (reconciliation R4): one source for the gates, + // the governance floor, AND this posture line — there is one broker, not two. + const { regime, policy, detail } = await profileBrokerPolicy(cwd); + if (regime === "none") { + return { + name, + status: "skip", + detail: `${detail} — declare [scope] in .kit-profile.toml and run 'kit profile sign' to arm the exec-broker`, + category, + }; + } + if (policy) { + return { name, status: "pass", detail, category }; + } + // Declared but untrustworthy (policy null). Preserve the honest warn-vs-fail split: a + // never-signed scope is a WARN (just sign it); a tampered/revoked/malformed one is a FAIL. + const status = await scopeDegradationStatus(cwd); + if (status === "warn") { + return { name, status: "warn", detail: `${detail}; run 'kit profile sign'`, category }; + } + return { name, status: "fail", detail, category }; +} + +/** Distinguish an unsigned (warn) scope from an invalid/revoked/malformed (fail) one. */ +async function scopeDegradationStatus(cwd: string): Promise<"warn" | "fail"> { + try { + const v = await verifyProfileSignature(cwd); + return v.status === "unsigned" || v.status === "unverifiable" ? "warn" : "fail"; + } catch { + return "fail"; // a broken artifact must never read as a mere warning } } diff --git a/src/broker/needs.test.ts b/src/exec-broker/scope-needs.test.ts similarity index 99% rename from src/broker/needs.test.ts rename to src/exec-broker/scope-needs.test.ts index aa1622e7..17fd2ce8 100644 --- a/src/broker/needs.test.ts +++ b/src/exec-broker/scope-needs.test.ts @@ -6,7 +6,7 @@ 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 { checkScopeNeeds } from "./scope-needs.js"; import { withGovernance } from "../governance-middleware.js"; import type { kitConfig, GovernanceConfig } from "../config.js"; diff --git a/src/exec-broker/scope-needs.ts b/src/exec-broker/scope-needs.ts new file mode 100644 index 00000000..dcfcc8e1 --- /dev/null +++ b/src/exec-broker/scope-needs.ts @@ -0,0 +1,77 @@ +/** + * kit exec-broker — declared operation needs vs the signed scope, for the governance floor. + * + * Design: `pillar3-exec-broker-5.0.md` §3.4 / §6.4, unified onto the canonical exec-broker per + * `pillar3-broker-reconciliation-5.0.md` (R4). 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. It is the governance-floor counterpart to + * the PreToolUse gates: both read the SAME signed source (`profileBrokerPolicy`) and use the + * SAME pure decisions (`decisions.ts`), so there is one broker, not two. + * + * 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 (regime "none") → nothing to enforce; advisory floor + * unchanged (backward compatible — projects without a profile see no behavior change); + * - a scope IS declared but unsigned/tampered/malformed (regime "active", policy null) → 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 (regime "active", policy set) → each declared need must be inside the scope. + * + * Deterministic, zero-LLM, local-only. + */ +import { resolve } from "node:path"; +import { profileBrokerPolicy } from "./profile-policy.js"; +import { checkEgress, checkFsWrite } from "./decisions.js"; +import { policyFsRoots } from "./policy.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 `profileBrokerPolicy`'s active+null policy, 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 { regime, policy, detail } = await profileBrokerPolicy(cwd); + if (regime === "none") return null; // no RoE regime declared — advisory floor unchanged + if (!policy) { + // Declared but unsigned/tampered/malformed — the RoE exists but is untrustworthy (fail-closed). + return `scope enforcement: ${detail}`; + } + + const deniedHosts = (needs.egress ?? []).filter( + (h) => !checkEgress(h, { allow: policy.egress.allow }).ok, + ); + if (deniedHosts.length > 0) { + return `scope enforcement: egress to ${deniedHosts.join(", ")} is outside the signed [scope].egress`; + } + const roots = policyFsRoots(policy); + const deniedPaths = (needs.fsWrites ?? []).filter( + (p) => !roots.some((root) => checkFsWrite(resolve(cwd, p), root).ok), + ); + if (deniedPaths.length > 0) { + return `scope enforcement: write to ${deniedPaths.join(", ")} is outside the signed [scope].fs`; + } + const deniedSecrets = (needs.secrets ?? []).filter((k) => !policy.env.declared.includes(k)); + 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 70d3a612..d94df253 100644 --- a/src/governance-middleware.ts +++ b/src/governance-middleware.ts @@ -13,7 +13,7 @@ import { formatSecretExpirationWarnings, hasExpiredSecrets, } from "./secret-expiration.js"; -import { checkScopeNeeds, type ScopeNeeds } from "./broker/needs.js"; +import { checkScopeNeeds, type ScopeNeeds } from "./exec-broker/scope-needs.js"; export interface OperationContext { operation: string; @@ -25,7 +25,7 @@ export interface OperationContext { * 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. + * need must be inside the VERIFIED scope — see exec-broker/scope-needs.ts for the rules. */ scopeNeeds?: ScopeNeeds; }