From 0a3f3ba62e51c940edb118bf460e869f1c836881 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 23 Jun 2026 20:15:32 +0000 Subject: [PATCH] feat(scan): offline air-gap mode (KIT_AIRGAP=1) for `kit scan` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Second step of the no-egress roadmap (#80), building on the configurable triage mirrors. With `KIT_AIRGAP=1`, `kit scan` runs entirely against pre-synced local databases: - `airGapScanners()` (pure, tested) drops cloud-only scanners (snyk, semgrep) and folds each remaining scanner's offline flags/env in: trivy gains `--offline-scan --skip-db-update`, osv-scanner gains `--offline`, grype gets `GRYPE_DB_AUTO_UPDATE=false`. - `isAirGap()` reads the toggle; `cmdScan` applies the plan, injects the offline env into each scanner run, and prints which cloud-only scanners were skipped. - `docs/AIR_GAP.md` §2 documents the toggle + per-scanner behavior and how to pre-sync each DB on a connected host. Local-ruleset support for semgrep offline is a tracked follow-up. No behavior change when KIT_AIRGAP is unset (transform is a no-op). Co-Authored-By: Claude Opus 4.8 (1M context) Claude-Session: https://claude.ai/code/session_015ERHw6bVUz39sAuoQZ1iyg --- docs/AIR_GAP.md | 50 ++++++++++++++++------------ src/cli.ts | 35 +++++++++++++------- src/scanners.test.ts | 42 +++++++++++++++++++++++ src/scanners.ts | 79 +++++++++++++++++++++++++++++++++++++++++--- 4 files changed, 168 insertions(+), 38 deletions(-) diff --git a/docs/AIR_GAP.md b/docs/AIR_GAP.md index 8c9e0a8d..a9bd2e90 100644 --- a/docs/AIR_GAP.md +++ b/docs/AIR_GAP.md @@ -18,17 +18,17 @@ The triage script reads its registry hosts from the environment, defaulting to the public registries. Set these (in the shell, CI job, or the environment kit runs under) to your internal mirrors: -| Env var | Default | Used for | -| :-------------------- | :----------------------------- | :---------------------------------------- | -| `KIT_NPM_REGISTRY` | `https://registry.npmjs.org` | npm package metadata (`kit triage npm:…`) | -| `KIT_PYPI_INDEX` | `https://pypi.org` | PyPI metadata (`pip:…`); expects `/pypi//json` | -| `KIT_GITHUB_API` | `https://api.github.com` | repo metadata (`repo:…`, `skill` fallback) — GitHub Enterprise API base | -| `KIT_DOCKER_REGISTRY` | `https://hub.docker.com` | image metadata (`docker:…`); expects the `/v2/repositories/` shape | +| Env var | Default | Used for | +| :-------------------- | :--------------------------- | :----------------------------------------------------------------------- | +| `KIT_NPM_REGISTRY` | `https://registry.npmjs.org` | npm package metadata (`kit triage npm:…`) | +| `KIT_PYPI_INDEX` | `https://pypi.org` | PyPI metadata (`pip:…`); expects `/pypi//json` | +| `KIT_GITHUB_API` | `https://api.github.com` | repo metadata (`repo:…`, `skill` fallback) — GitHub Enterprise API base | +| `KIT_DOCKER_REGISTRY` | `https://hub.docker.com` | image metadata (`docker:…`); expects the `/v2/repositories/` shape | The mirror must expose the same JSON shapes as the upstream it mirrors (most internal npm/PyPI proxies and GitHub Enterprise do). The package/repo name is the only attacker-influenceable part and is only ever interpolated into the URL -*path* — the host comes from these operator-set vars, never from the target. +_path_ — the host comes from these operator-set vars, never from the target. ```bash export KIT_NPM_REGISTRY="https://npm.corp.internal" @@ -40,21 +40,27 @@ kit triage npm:left-pad # now evaluated against the internal mirror ## 2. Run the scanners locally / offline -`kit scan` orchestrates external scanners that you install locally (resolved -mise-first). Each supports an offline mode against a pre-synced database: - -- **trivy** — `trivy fs --offline-scan` with a DB pulled on a connected host via - `trivy --download-db-only` and shipped in (`TRIVY_DB_REPOSITORY` for an OCI - mirror). -- **grype** — set `GRYPE_DB_AUTO_UPDATE=false` and provide a cached DB via - `GRYPE_DB_CACHE_DIR` (sync with `grype db update` on a connected host). -- **osv-scanner** — use a local/offline vulnerability database (`--offline` with - a synced OSV DB) so no calls leave the enclave. -- **semgrep** — ship rule packs locally and run `--config ` instead of - `--config auto`. - -Install these through your internal package mirror or an approved binary cache; -kit never downloads them itself. +Set **`KIT_AIRGAP=1`** and `kit scan` switches to offline mode: it drops +cloud-only scanners and folds each remaining scanner's offline flags/env in so it +runs against a **pre-synced local DB with no network**. + +```bash +export KIT_AIRGAP=1 +kit scan # → "air-gap mode: offline scanners only (skipping cloud-only: snyk, semgrep)" +``` + +What the mode does per scanner: + +| Scanner | Air-gap behavior | +| :-------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| **trivy** | adds `--offline-scan --skip-db-update` (pre-sync the DB on a connected host with `trivy --download-db-only`, or point `TRIVY_DB_REPOSITORY` at an OCI mirror) | +| **grype** | sets `GRYPE_DB_AUTO_UPDATE=false` (provide a cached DB via `GRYPE_DB_CACHE_DIR`, synced with `grype db update` on a connected host) | +| **osv-scanner** | adds `--offline` (point at a synced local OSV DB) | +| **snyk** | **skipped** — talks to the Snyk cloud | +| **semgrep** | **skipped** — `--config auto` fetches the registry (local-ruleset support is a tracked follow-up) | + +Install the scanners through your internal package mirror or an approved binary +cache; kit never downloads them itself. ## 3. Bumblebee (known-compromise scan) offline diff --git a/src/cli.ts b/src/cli.ts index fe4e41c2..4384cec8 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -4492,8 +4492,16 @@ async function cmdScan(): Promise { const { resolveToolBin } = await import("./utils/resolveTool.js"); const { execFileNoThrow } = await import("./utils/execFileNoThrow.js"); const { loadBaseline, baselineGet, baselineSet, saveBaseline } = await import("./baseline.js"); - const { SCANNERS } = await import("./scanners.js"); + const { SCANNERS, airGapScanners, isAirGap } = await import("./scanners.js"); const cwd = process.cwd(); + // Air-gap mode (KIT_AIRGAP=1): drop cloud-only scanners and run the rest + // against local DBs with no network. See docs/AIR_GAP.md. + const airgap = airGapScanners(SCANNERS, isAirGap()); + if (isAirGap()) { + console.log( + `${c.dim}air-gap mode: offline scanners only${airgap.dropped.length ? ` (skipping cloud-only: ${airgap.dropped.join(", ")})` : ""}${c.reset}`, + ); + } const config = await loadConfig(resolveConfigPath()); // Resolve scanner tokens (SNYK_TOKEN, …) from a configured tooling Infisical @@ -4514,18 +4522,21 @@ async function cmdScan(): Promise { } } - const { merged, runs } = await runScanners({ - resolve: (bin) => resolveToolBin(bin), - run: async (bin, args) => { - const r = await execFileNoThrow(bin, args, { - timeout: 180_000, - env: { ...process.env, ...toolingTokens }, - }); - return { ok: r.ok, stdout: r.stdout }; + const { merged, runs } = await runScanners( + { + resolve: (bin) => resolveToolBin(bin), + run: async (bin, args) => { + const r = await execFileNoThrow(bin, args, { + timeout: 180_000, + env: { ...process.env, ...airgap.env, ...toolingTokens }, + }); + return { ok: r.ok, stdout: r.stdout }; + }, + hasEnv: (name) => Boolean(process.env[name] || toolingTokens[name]), + detect: (markers) => markers.some((m) => existsSync(resolve(cwd, m))), }, - hasEnv: (name) => Boolean(process.env[name] || toolingTokens[name]), - detect: (markers) => markers.some((m) => existsSync(resolve(cwd, m))), - }); + airgap.scanners, + ); // --update-baseline: freeze the current findings as accepted (#59 noise-reduction), // reusing the shared .kit-baseline.json under a "scan" category. diff --git a/src/scanners.test.ts b/src/scanners.test.ts index b591def3..ac42cda3 100644 --- a/src/scanners.test.ts +++ b/src/scanners.test.ts @@ -5,6 +5,9 @@ import { mergeFindings, suppressBaselined, runScanners, + airGapScanners, + isAirGap, + SCANNERS, type ScanDeps, type ScannerDef, } from "./scanners.js"; @@ -83,6 +86,45 @@ describe("runScanners (injected deps)", () => { }); }); +describe("isAirGap", () => { + it("is true for 1/true/yes, false otherwise", () => { + assert.equal(isAirGap({ KIT_AIRGAP: "1" }), true); + assert.equal(isAirGap({ KIT_AIRGAP: "true" }), true); + assert.equal(isAirGap({ KIT_AIRGAP: "YES" }), true); + assert.equal(isAirGap({ KIT_AIRGAP: "0" }), false); + assert.equal(isAirGap({}), false); + }); +}); + +describe("airGapScanners", () => { + it("is a no-op when disabled", () => { + const plan = airGapScanners(SCANNERS, false); + assert.equal(plan.scanners, SCANNERS); + assert.deepEqual(plan.dropped, []); + assert.deepEqual(plan.env, {}); + }); + + it("drops cloud-only scanners and folds offline args/env for the rest", () => { + const plan = airGapScanners(SCANNERS, true); + // cloud-only (snyk, semgrep) are excluded + assert.deepEqual(plan.dropped.sort(), ["semgrep", "snyk"]); + assert.ok(!plan.scanners.some((s) => s.id === "snyk" || s.id === "semgrep")); + // trivy gets its offline flags appended + const trivy = plan.scanners.find((s) => s.id === "trivy")!; + assert.ok(trivy.args.includes("--offline-scan") && trivy.args.includes("--skip-db-update")); + // osv-scanner gets --offline + assert.ok(plan.scanners.find((s) => s.id === "osv-scanner")!.args.includes("--offline")); + // grype contributes offline env, not args + assert.equal(plan.env.GRYPE_DB_AUTO_UPDATE, "false"); + }); + + it("does not mutate the original registry", () => { + const before = JSON.stringify(SCANNERS); + airGapScanners(SCANNERS, true); + assert.equal(JSON.stringify(SCANNERS), before); + }); +}); + describe("suppressBaselined", () => { const merged = mergeFindings([ { diff --git a/src/scanners.ts b/src/scanners.ts index c0e67cb1..b193a3d7 100644 --- a/src/scanners.ts +++ b/src/scanners.ts @@ -24,21 +24,92 @@ export interface ScannerDef { needsToken?: string; /** marker files that make the scanner applicable; undefined = always */ detect?: string[]; + /** Cannot run with no network (needs a hosted backend) — dropped in air-gap mode. */ + cloudOnly?: boolean; + /** Extra args/env applied in air-gap mode so the scanner runs against a local DB. */ + offline?: { args?: string[]; env?: Record }; } export const SCANNERS: ScannerDef[] = [ - { id: "snyk", bin: "snyk", args: ["test", "--sarif"], format: "sarif", needsToken: "SNYK_TOKEN" }, - { id: "trivy", bin: "trivy", args: ["fs", "--format", "sarif", "--quiet", "."], format: "sarif" }, - { id: "grype", bin: "grype", args: ["dir:.", "-o", "sarif", "-q"], format: "sarif" }, + // snyk talks to the Snyk cloud → not usable in a no-egress enclave. { + id: "snyk", + bin: "snyk", + args: ["test", "--sarif"], + format: "sarif", + needsToken: "SNYK_TOKEN", + cloudOnly: true, + }, + { + id: "trivy", + bin: "trivy", + args: ["fs", "--format", "sarif", "--quiet", "."], + format: "sarif", + // run against the pre-synced local DB; never reach out to update it + offline: { args: ["--offline-scan", "--skip-db-update"] }, + }, + { + id: "grype", + bin: "grype", + args: ["dir:.", "-o", "sarif", "-q"], + format: "sarif", + offline: { env: { GRYPE_DB_AUTO_UPDATE: "false" } }, + }, + { + // `--config auto` fetches the semgrep registry; without a local ruleset it + // can't run offline, so it's dropped in air-gap mode (point it at a local + // ruleset via a future KIT_SEMGREP_CONFIG to re-enable — tracked). id: "semgrep", bin: "semgrep", args: ["scan", "--sarif", "--quiet", "--config", "auto", "."], format: "sarif", + cloudOnly: true, + }, + { + id: "osv-scanner", + bin: "osv-scanner", + args: ["--format", "json", "-r", "."], + format: "osv", + offline: { args: ["--offline"] }, }, - { id: "osv-scanner", bin: "osv-scanner", args: ["--format", "json", "-r", "."], format: "osv" }, ]; +/** True when air-gap mode is requested via env (KIT_AIRGAP=1/true/yes). */ +export function isAirGap(env: NodeJS.ProcessEnv = process.env): boolean { + return ["1", "true", "yes"].includes((env.KIT_AIRGAP ?? "").trim().toLowerCase()); +} + +export interface AirGapPlan { + /** Scanners that can run offline, with their offline args folded in. */ + scanners: ScannerDef[]; + /** Env to inject into every scanner run (e.g. disable DB auto-update). */ + env: Record; + /** ids of cloud-only scanners excluded because they need network. */ + dropped: string[]; +} + +/** + * Transform the registry for air-gap mode: drop `cloudOnly` scanners and fold + * each remaining scanner's `offline` args/env in so it runs against a local DB + * with no network. A no-op (returns the input) when `enabled` is false. + */ +export function airGapScanners(defs: ScannerDef[], enabled: boolean): AirGapPlan { + if (!enabled) return { scanners: defs, env: {}, dropped: [] }; + const scanners: ScannerDef[] = []; + const env: Record = {}; + const dropped: string[] = []; + for (const d of defs) { + if (d.cloudOnly) { + dropped.push(d.id); + continue; + } + if (d.offline?.env) Object.assign(env, d.offline.env); + const extra = d.offline?.args ?? []; + scanners.push(extra.length ? { ...d, args: [...d.args, ...extra] } : d); + } + return { scanners, env, dropped }; +} + const RANK: Record = { critical: 4, high: 3, medium: 2, low: 1 }; /** Cross-scanner dedup key: a CVE/GHSA id if present in the finding, else its name. */