diff --git a/src/commands/triage.ts b/src/commands/triage.ts index 407d62ec..56391547 100644 --- a/src/commands/triage.ts +++ b/src/commands/triage.ts @@ -11,7 +11,8 @@ import { triageVaultConfig } from "../vault-triage.js"; export async function cmdTriage(): Promise { const args = process.argv.slice(3); const sandbox = hasFlag(args, "--sandbox"); - const filtered = args.filter((a) => a !== "--sandbox"); + const deep = hasFlag(args, "--deep"); + const filtered = args.filter((a) => a !== "--sandbox" && a !== "--deep"); const typeArg = filtered[0]; // `check-deps` is a pre-commit subcommand handled below before we narrow // to TriageType; the rest of this function works against TriageType only. @@ -44,6 +45,9 @@ export async function cmdTriage(): Promise { ); console.log(" kit triage repo Evaluate GitHub repository"); console.log(" kit triage skill Evaluate Claude Code / agent skill"); + console.log( + " kit triage skill --deep + SkillSpector (NVIDIA) static Stage 1 (no LLM, no egress) when installed", + ); console.log( " kit triage mcp --tools Evaluate MCP tool metadata (poisoning) + pin against drift", ); @@ -127,7 +131,17 @@ export async function cmdTriage(): Promise { ); } - const overall = result.passed && sandboxClean; + // --deep on a skill: delegate to SkillSpector's STATIC Stage 1 (no LLM, no egress). Fail-closed. + let deepClean = true; + if (deep && type === "skill") { + deepClean = await deepSkillScan(target); + } else if (deep && type !== "skill") { + console.log( + `\n${c.dim}(--deep currently only applies to skill; ignored for ${type})${c.reset}`, + ); + } + + const overall = result.passed && sandboxClean && deepClean; if (!overall) { console.log(`\n${c.yellow}⚠️ Review warnings above before proceeding.${c.reset}`); } @@ -143,6 +157,42 @@ export async function cmdTriage(): Promise { return overall; } +/** + * `kit triage skill … --deep` helper: run SkillSpector's static Stage 1 (no LLM, no egress) and fold + * its normalized findings into the verdict. Returns `false` only on a real high/critical finding or a + * scan error; an ABSENT delegate is surfaced honestly and returns `true` (deep didn't run — the base + * triage verdict still governs; kit never claims a deep-clean it didn't perform). + */ +async function deepSkillScan(target: string): Promise { + const { runSkillspectorStage1, SKILLSPECTOR_SOURCE } = + await import("../skillspector-delegate.js"); + console.log( + `\n${c.bold}Deep scan (${SKILLSPECTOR_SOURCE}, static — no LLM, no egress):${c.reset}`, + ); + const deepRes = await runSkillspectorStage1(target); + if (deepRes.status === "unavailable") { + console.log(` ${c.yellow}! ${deepRes.detail}${c.reset}`); + return true; + } + if (deepRes.status === "error") { + console.log(` ${c.red}✗ deep scan errored: ${deepRes.detail}${c.reset}`); + return false; + } + if (deepRes.findings.length === 0) { + console.log(` ${c.green}✓ no findings from the deep static scan${c.reset}`); + return true; + } + for (const f of deepRes.findings) { + const sev = f.severity ?? "info"; + const tag = + sev === "critical" || sev === "high" + ? `${c.red}[${sev.toUpperCase()}]${c.reset}` + : `${c.yellow}[${sev}]${c.reset}`; + console.log(` ${tag} ${f.detail}`); + } + return !(deepRes.worst === "critical" || deepRes.worst === "high"); +} + /** * `kit triage vault-config` — triage the project's secret-backend SELECTION (`.kit.toml` * `secrets.store` + per-key `source`): flag an unknown/typo'd backend (silently no vault) and diff --git a/src/doctor.test.ts b/src/doctor.test.ts index e321d267..07863f63 100644 --- a/src/doctor.test.ts +++ b/src/doctor.test.ts @@ -159,7 +159,7 @@ describe("runDoctor", () => { } }); - it("exec-broker runtime: skips when enforce_runtime is not opted in", async () => { + it("exec-broker runtime: skips when no [scope] is declared (nothing to mediate)", async () => { const tmpDir = join(tmpdir(), `kit-doctor-test-${process.pid}-rt-skip`); await mkdir(tmpDir, { recursive: true }); try { @@ -167,7 +167,7 @@ describe("runDoctor", () => { const rt = result.checks.find((c) => c.name === "exec-broker runtime"); assert.ok(rt, "exec-broker runtime check should always be present"); assert.equal(rt.status, "skip"); - assert.ok(rt.detail.includes("enforce_runtime"), `unexpected detail: ${rt.detail}`); + assert.ok(rt.detail.includes("no [scope]"), `unexpected detail: ${rt.detail}`); } finally { await rm(tmpDir, { recursive: true }); } diff --git a/src/doctor.ts b/src/doctor.ts index 7f3496d5..e6c4f809 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -309,13 +309,17 @@ async function scopeDegradationStatus(cwd: string): Promise<"warn" | "fail"> { async function checkBrokerRuntime(cwd: string): Promise { const name = "exec-broker runtime"; const category = "security"; - const { runtimeMode, policy } = await profileBrokerPolicy(cwd); + const { runtimeMode, policy, regime } = await profileBrokerPolicy(cwd); if (runtimeMode === "off") { + // Default-on: a declared scope mediates in observe by default, so "off" means either no scope is + // declared here, or the scope explicitly opted OUT with enforce_runtime = false. return { name, status: "skip", detail: - 'MCP-runtime mediation not opted in — set [scope].enforce_runtime = true (or "observe" for a dry-run) and re-sign to mediate governed MCP ops against the scope', + regime === "none" + ? "no [scope] declared — nothing to mediate at the MCP runtime" + : "MCP-runtime mediation explicitly OFF ([scope].enforce_runtime = false); remove it to get observe-by-default, or set true to enforce", category, }; } diff --git a/src/exec-broker/broker.test.ts b/src/exec-broker/broker.test.ts index 41e2621c..94166798 100644 --- a/src/exec-broker/broker.test.ts +++ b/src/exec-broker/broker.test.ts @@ -433,19 +433,48 @@ enforce_runtime = true assert.equal(ran, false); }); - it("signed scope WITHOUT enforce_runtime → runtime unchanged (falls through to passthrough)", async () => { + it("DEFAULT-ON: a signed scope WITHOUT enforce_runtime observes by default (audits would-deny, never denies)", async () => { await writeSignedProfile(`version = 1\n[scope]\negress = ["api.acme.com"]\n`, true); let ran = false; const out = await runBrokered( - CTX({ egressTargets: ["https://evil.com"] }), // off-scope, but no runtime opt-in → not gated + CTX({ egressTargets: ["https://evil.com"] }), // off-scope: enforce WOULD deny; observe records it async () => { ran = true; return "ok"; }, { cwd: sandbox }, ); - assert.equal(out.ok, true, "a signed scope alone does not gate the MCP runtime"); + assert.equal(out.ok, true, "observe-by-default never denies"); assert.equal(ran, true); + const obs = auditLines().find((l) => (l.metadata as { phase?: string })?.phase === "observe"); + assert.ok(obs, "default-on mediates in observe → an observe audit entry is written"); + const wouldDeny = (obs!.metadata as { wouldDeny?: string[] }).wouldDeny ?? []; + assert.ok( + wouldDeny.some((d) => d.includes("evil.com")), + `the would-be denial is recorded: ${JSON.stringify(wouldDeny)}`, + ); + }); + + it("explicit enforce_runtime = false → runtime OFF (opt out of mediation entirely)", async () => { + await writeSignedProfile( + `version = 1\n[scope]\negress = ["api.acme.com"]\nenforce_runtime = false\n`, + true, + ); + let ran = false; + const out = await runBrokered( + CTX({ egressTargets: ["https://evil.com"] }), + async () => { + ran = true; + return "ok"; + }, + { cwd: sandbox }, + ); + assert.equal(out.ok, true); + assert.equal(ran, true); + assert.ok( + !auditLines().some((l) => (l.metadata as { phase?: string })?.phase === "observe"), + "explicit off writes no observe audit entry", + ); }); it("infrastructure op under a restrictive enforce_runtime scope → allowed + audited exemption", async () => { diff --git a/src/exec-broker/profile-policy.test.ts b/src/exec-broker/profile-policy.test.ts index aea7dd49..d781fa72 100644 --- a/src/exec-broker/profile-policy.test.ts +++ b/src/exec-broker/profile-policy.test.ts @@ -145,4 +145,22 @@ describe("profileBrokerPolicy", () => { assert.equal(r.runtimeMode, "observe"); assert.equal(r.policy, null, "unsigned → null policy (observe still reports would-denies)"); }); + + it("DEFAULT-ON: a declared scope with no enforce_runtime defaults to observe", async () => { + writeFileSync(join(proj, PROFILE_FILE), `version = 1\n[scope]\negress = ["h.io"]\n`); + await signProfile(proj); + const r = await profileBrokerPolicy(proj); + assert.equal( + r.runtimeMode, + "observe", + "mediation is on (dry-run) by default for a declared scope", + ); + assert.equal(r.enforceRuntime, false, "default-on is observe, not enforce"); + }); + + it("enforce_runtime = false is an explicit opt-out (runtimeMode off)", async () => { + writeFileSync(join(proj, PROFILE_FILE), `version = 1\n[scope]\nenforce_runtime = false\n`); + await signProfile(proj); + assert.equal((await profileBrokerPolicy(proj)).runtimeMode, "off"); + }); }); diff --git a/src/exec-broker/profile-policy.ts b/src/exec-broker/profile-policy.ts index e46a0440..3a1c0567 100644 --- a/src/exec-broker/profile-policy.ts +++ b/src/exec-broker/profile-policy.ts @@ -64,11 +64,21 @@ interface ScopeShape { enforce_runtime?: boolean | "observe"; } -/** Map the signed `enforce_runtime` declaration onto the runtime posture. */ +/** + * Map the signed `enforce_runtime` declaration onto the runtime posture (Pillar 3 default-on). + * - `"observe"` → dry-run (mediate, audit would-be denials, never deny); + * - `true` → enforce (mediate + deny); + * - `false` → explicit OFF (opt out of runtime mediation entirely); + * - ABSENT → DEFAULT-ON: a declared scope mediates in `observe` by default. Turning mediation + * on by default is safe because observe never denies — nothing an upgrade could break; it only + * starts recording what enforce WOULD block. Enforce-by-default stays an explicit `true` until + * field evidence from observe justifies flipping it. + */ function runtimeModeOf(scope: ScopeShape): "off" | "observe" | "enforce" { if (scope.enforce_runtime === "observe") return "observe"; if (scope.enforce_runtime === true) return "enforce"; - return "off"; + if (scope.enforce_runtime === false) return "off"; + return "observe"; } /** Map a verified profile `[scope]` onto a BrokerPolicy (fs paths resolved against `cwd`). */ diff --git a/src/mcp-server.test.ts b/src/mcp-server.test.ts index baa37ad9..99cf08e7 100644 --- a/src/mcp-server.test.ts +++ b/src/mcp-server.test.ts @@ -426,8 +426,9 @@ describe("kit_secrets + signed-scope runtime enforcement (MCP-runtime adoption s } }); - it("without enforce_runtime the runtime is unchanged (write proceeds)", async () => { - // A signed scope that does NOT opt in ⇒ migration passthrough ⇒ secrets still written. + it("default-on (no enforce_runtime) OBSERVES but never denies (write proceeds)", async () => { + // A signed scope that does NOT set the flag ⇒ default-on observe ⇒ would-be denials are audited + // but the write still proceeds (observe never denies), even though .env.local is off the fs scope. await writeFile(join(tempDir, PROFILE_FILE), `version = 1\n[scope]\nfs = ["src"]\n`); await signProfile(tempDir); const { client, cleanup } = await createTestClient(); @@ -437,7 +438,7 @@ describe("kit_secrets + signed-scope runtime enforcement (MCP-runtime adoption s assert.equal( data.ok, true, - "no enforce_runtime ⇒ not gated even though .env.local is off the fs scope", + "observe-by-default never denies even though .env.local is off the fs scope", ); assert.ok(data.writtenKeys.includes("APP_KEY")); } finally { diff --git a/src/skillspector-delegate.test.ts b/src/skillspector-delegate.test.ts new file mode 100644 index 00000000..07d3cfc9 --- /dev/null +++ b/src/skillspector-delegate.test.ts @@ -0,0 +1,105 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { + scrubbedEnv, + stage1Args, + normalizeSkillspectorSarif, + runSkillspectorStage1, + LLM_ENV_VARS, + SKILLSPECTOR_SOURCE, + SKILLSPECTOR_BIN, +} from "./skillspector-delegate.js"; + +// A minimal SkillSpector-style SARIF 2.1.0 log with one HIGH finding. +const SARIF = JSON.stringify({ + runs: [ + { + tool: { + driver: { + name: "SkillSpector", + rules: [ + { + id: "SC4-curl-bash", + properties: { "security-severity": "8.1", tags: ["supply-chain"] }, + }, + ], + }, + }, + results: [ + { + ruleId: "SC4-curl-bash", + level: "error", + message: { text: "pipes curl into bash" }, + locations: [ + { + physicalLocation: { + artifactLocation: { uri: "install.sh" }, + region: { startLine: 3 }, + }, + }, + ], + }, + ], + }, + ], +}); + +describe("skillspector delegate — zero-LLM enforcement (no egress)", () => { + it("scrubbedEnv strips every provider API key and SKILLSPECTOR_* var", () => { + const base: NodeJS.ProcessEnv = { + PATH: "/usr/bin", + OPENAI_API_KEY: "sk-should-be-gone", + ANTHROPIC_API_KEY: "sk-ant-gone", + SKILLSPECTOR_PROVIDER: "openai", + SKILLSPECTOR_MODEL: "gpt-5.4", + HOME: "/home/x", + }; + const env = scrubbedEnv(base); + assert.equal(env.PATH, "/usr/bin", "innocuous vars survive"); + assert.equal(env.HOME, "/home/x"); + for (const k of LLM_ENV_VARS) assert.equal(env[k], undefined, `${k} must be stripped`); + assert.equal(env.SKILLSPECTOR_MODEL, undefined, "SKILLSPECTOR_* stripped"); + assert.equal(env.SKILLSPECTOR_PROVIDER, "", "provider pinned empty (no network default)"); + }); + + it("does not mutate the passed-in base env", () => { + const base: NodeJS.ProcessEnv = { OPENAI_API_KEY: "sk-x" }; + scrubbedEnv(base); + assert.equal(base.OPENAI_API_KEY, "sk-x", "base env untouched"); + }); + + it("stage1Args never contains an LLM/provider flag", () => { + const args = stage1Args("./skill"); + assert.deepEqual(args, ["scan", "./skill", "--format", "sarif"]); + assert.ok(!args.some((a) => /llm|provider|model|openai|anthropic/i.test(a))); + }); +}); + +describe("skillspector delegate — SARIF normalization (attributed)", () => { + it("maps SARIF findings to supply-chain kit findings tagged with the source", () => { + const findings = normalizeSkillspectorSarif(SARIF); + assert.equal(findings.length, 1); + const f = findings[0]; + assert.equal(f.category, "supply-chain"); + assert.equal(f.status, "fail"); + assert.equal(f.severity, "high", "CVSS 8.1 → high"); + assert.ok(f.name.startsWith(SKILLSPECTOR_SOURCE), `attributed: ${f.name}`); + assert.match(f.detail, /curl into bash/); + assert.match(f.detail, /install\.sh/); + }); + + it("returns [] for empty or invalid SARIF (never throws)", () => { + assert.deepEqual(normalizeSkillspectorSarif(""), []); + assert.deepEqual(normalizeSkillspectorSarif("not json"), []); + assert.deepEqual(normalizeSkillspectorSarif(JSON.stringify({ runs: [] })), []); + }); +}); + +describe("skillspector delegate — fail-closed when the binary is absent", () => { + it("returns unavailable (not a silent pass) when skillspector is not installed", async () => { + // skillspector is not installed in CI → resolveToolBin returns null. + const r = await runSkillspectorStage1("./skill"); + assert.equal(r.status, "unavailable"); + if (r.status === "unavailable") assert.match(r.detail, new RegExp(SKILLSPECTOR_BIN)); + }); +}); diff --git a/src/skillspector-delegate.ts b/src/skillspector-delegate.ts new file mode 100644 index 00000000..f88939ac --- /dev/null +++ b/src/skillspector-delegate.ts @@ -0,0 +1,132 @@ +/** + * `kit triage skill` — SkillSpector (NVIDIA) delegate, Stage-1 ONLY: deterministic, NO LLM, NO egress. + * + * Design: `kit-research/docs/research/pillar-triage-skill-delegate-5.0.md`. + * + * kit does NOT reimplement NVIDIA's 68-pattern agent-skill scanner — it ORCHESTRATES it, the same way + * `kit check` orchestrates bumblebee/trivy/semgrep. We run SkillSpector's STATIC Stage 1 (regex + AST + * + offline OSV) and normalize its SARIF into kit's `SecurityCheckResult`, ATTRIBUTED to the source. + * kit's own value is the governance layer (deterministic, no-egress, one unified verdict, audit) — not + * the detection rules; borrowing an authoritative source's rules strengthens trust rather than diluting + * it, provided the provenance stays visible. + * + * ZERO-LLM / NO-EGRESS INVARIANT — why this file is safe to ship in kit: + * SkillSpector's Stage 2 is an LLM pass that sends file contents to a provider; invoking it would + * break kit's no-egress charter. kit NEVER invokes Stage 2. This is enforced two ways, both testable: + * 1. SCRUBBED ENV — every SKILLSPECTOR_ (and provider-API-key) var is stripped from the child env, so + * Stage 2 cannot silently activate from ambient config (`scrubbedEnv`). + * 2. STATIC INVOCATION — we run a plain `scan … --format sarif` and read only Stage-1 SARIF. + * Fail-CLOSED: a missing binary or a scan error is a DEGRADED result (never a silent pass); the + * caller must not report "deep-clean" when the delegate did not actually run. + * + * Deterministic given (binary, target, env). Offline (Stage 1 uses OSV's offline fallback). + */ +import { resolveToolBin } from "./utils/resolveTool.js"; +import { execFileNoThrow } from "./utils/execFileNoThrow.js"; +import { parseSarif } from "./adapters/ingest.js"; +import type { SecurityCheckResult } from "./check-security.js"; + +/** The delegate binary name (resolved mise-first, then PATH). */ +export const SKILLSPECTOR_BIN = "skillspector"; + +/** Attribution stamped on every normalized finding so borrowed authority stays visible. */ +export const SKILLSPECTOR_SOURCE = "SkillSpector (NVIDIA) Stage 1"; + +/** + * Env vars that could switch SkillSpector's optional Stage-2 LLM on (or hand it a provider key). We + * strip ALL of these from the child env so the delegate can only ever run its deterministic Stage 1 — + * regardless of what the surrounding shell has exported. + */ +export const LLM_ENV_VARS = [ + "OPENAI_API_KEY", + "ANTHROPIC_API_KEY", + "GEMINI_API_KEY", + "GOOGLE_API_KEY", + "AWS_ACCESS_KEY_ID", + "AWS_SECRET_ACCESS_KEY", + "AWS_SESSION_TOKEN", + "OLLAMA_HOST", +]; + +/** Build a child env with every SKILLSPECTOR_* var and known provider key removed (no Stage-2 LLM). */ +export function scrubbedEnv(base: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv { + const out: NodeJS.ProcessEnv = {}; + for (const [k, v] of Object.entries(base)) { + if (k.startsWith("SKILLSPECTOR_")) continue; // provider/model/config for Stage 2 + if (LLM_ENV_VARS.includes(k)) continue; // provider API keys + out[k] = v; + } + // Belt-and-suspenders: pin the provider to empty so an internal default can't reach the network. + out.SKILLSPECTOR_PROVIDER = ""; + return out; +} + +/** Argv for a static, SARIF-emitting Stage-1 scan. No `--llm`/provider flags are ever added. */ +export function stage1Args(target: string): string[] { + return ["scan", target, "--format", "sarif"]; +} + +/** + * Normalize SkillSpector SARIF into kit findings, tagged supply-chain and attributed to the source. + * Pure — reuses the shared `parseSarif`. An empty/invalid SARIF yields `[]` (parseSarif never throws). + */ +export function normalizeSkillspectorSarif(sarifJson: string): SecurityCheckResult[] { + return parseSarif(sarifJson).map((f) => ({ + ...f, + category: "supply-chain", + name: `${SKILLSPECTOR_SOURCE}: ${f.name.replace(/^[^:]+:\s*/, "")}`, + })); +} + +export type SkillspectorResult = + | { status: "ok"; findings: SecurityCheckResult[]; worst: SecurityCheckResult["severity"] } + | { status: "unavailable"; detail: string } + | { status: "error"; detail: string }; + +const SEVERITY_RANK: Record, number> = { + low: 1, + medium: 2, + high: 3, + critical: 4, +}; + +function worstSeverity(findings: SecurityCheckResult[]): SecurityCheckResult["severity"] { + let worst: SecurityCheckResult["severity"] = undefined; + for (const f of findings) { + if (!f.severity) continue; + if (!worst || SEVERITY_RANK[f.severity] > SEVERITY_RANK[worst]) worst = f.severity; + } + return worst; +} + +/** + * Run SkillSpector's Stage 1 on `target` and return normalized findings. Fail-CLOSED and never throws: + * - binary not installed → { status: "unavailable" } (caller must not claim deep-clean) + * - scan crashed (exit 2) → { status: "error" } + * - scanned (exit 0 = clean, 1 = findings) → { status: "ok", findings } + * Always runs with `scrubbedEnv` so Stage 2 can never activate. + */ +export async function runSkillspectorStage1( + target: string, + opts: { cwd?: string; timeout?: number; env?: NodeJS.ProcessEnv } = {}, +): Promise { + const bin = await resolveToolBin(SKILLSPECTOR_BIN); + if (!bin) { + return { + status: "unavailable", + detail: `${SKILLSPECTOR_BIN} not installed — deep skill triage skipped (install to enable; kit never runs its LLM stage)`, + }; + } + const res = await execFileNoThrow(bin, stage1Args(target), { + cwd: opts.cwd, + timeout: opts.timeout ?? 120_000, + env: scrubbedEnv(opts.env), + maxBuffer: 8 * 1024 * 1024, + }); + // SkillSpector exit codes: 0 = risk ≤ 50, 1 = risk > 50 (findings), 2 = error. + if (res.exitCode === 2) { + return { status: "error", detail: res.stderr.trim() || "skillspector scan errored" }; + } + const findings = normalizeSkillspectorSarif(res.stdout); + return { status: "ok", findings, worst: worstSeverity(findings) }; +}