diff --git a/CHANGELOG.md b/CHANGELOG.md index 04fa3633..f90bfaff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +## [1.16.0] - 2026-06-23 + +### Added +- **SARIF + OSV ingestion adapter — one parser per format, not per tool (`kit ingest `).** SARIF 2.1.0 (semgrep/CodeQL/Trivy/Grype/…) and OSV-scanner JSON normalize into kit's `SecurityCheckResult` shape: SARIF maps `security-severity` (CVSS) → severity with a `level` fallback and lifts `CWE-NNN` rule tags into a citation; OSV maps package vulnerabilities to `dependency` findings with an OWASP-A06 citation. Pure (string → findings), fixture-tested; `kit ingest` prints them severity-sorted (`--json` for the raw list). Ingesting the *format* means any SARIF/OSV-emitting scanner feeds kit's finding ledger uniformly. (#48) + ## [1.15.0] - 2026-06-23 ### Added diff --git a/package-lock.json b/package-lock.json index 634aac80..96971a33 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "sandstream-kit", - "version": "1.15.0", + "version": "1.16.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sandstream-kit", - "version": "1.15.0", + "version": "1.16.0", "license": "MIT", "workspaces": [ "packages/*" diff --git a/package.json b/package.json index d040d86a..4af52bf7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sandstream-kit", - "version": "1.15.0", + "version": "1.16.0", "description": "developer kit. zero LLM, local-first, multi-vault. one command from git clone to working dev environment.", "license": "MIT", "funding": "https://buymeacoffee.com/sandstream", diff --git a/src/adapters/ingest.test.ts b/src/adapters/ingest.test.ts new file mode 100644 index 00000000..ae8ddef4 --- /dev/null +++ b/src/adapters/ingest.test.ts @@ -0,0 +1,92 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { parseSarif, parseOsv, ingest } from "./ingest.js"; + +const sarif = JSON.stringify({ + runs: [ + { + tool: { + driver: { + name: "semgrep", + rules: [ + { id: "sql-injection", properties: { tags: ["security", "external/cwe/cwe-89"], "security-severity": "9.1" } }, + { id: "weak-hash", properties: { tags: ["CWE-328"] } }, + ], + }, + }, + results: [ + { + ruleId: "sql-injection", + level: "error", + message: { text: "Possible SQL injection" }, + locations: [{ physicalLocation: { artifactLocation: { uri: "src/db.ts" }, region: { startLine: 42 } } }], + }, + { ruleId: "weak-hash", level: "warning", message: { text: "MD5 used" } }, + ], + }, + ], +}); + +const osv = JSON.stringify({ + results: [ + { + packages: [ + { + package: { name: "lodash", ecosystem: "npm", version: "4.17.11" }, + vulnerabilities: [ + { id: "GHSA-jf85-cpcp-j695", summary: "Prototype pollution in lodash", database_specific: { severity: "HIGH" } }, + ], + }, + ], + }, + ], +}); + +describe("parseSarif", () => { + it("maps results to findings with CVSS-derived severity + CWE citation + location", () => { + const out = parseSarif(sarif); + assert.equal(out.length, 2); + const sqli = out[0]; + assert.equal(sqli.category, "exposure"); + assert.equal(sqli.name, "semgrep: sql-injection"); + assert.equal(sqli.severity, "critical"); // security-severity 9.1 + assert.match(sqli.detail, /src\/db\.ts:42/); + assert.equal(sqli.rule?.id, "CWE-89"); + }); + + it("falls back to level→severity when no security-severity, and reads CWE-NNN tags", () => { + const weak = parseSarif(sarif)[1]; + assert.equal(weak.severity, "medium"); // level warning + assert.equal(weak.rule?.id, "CWE-328"); + }); + + it("returns [] on garbage", () => { + assert.deepEqual(parseSarif("not json"), []); + assert.deepEqual(parseSarif(JSON.stringify({})), []); + }); +}); + +describe("parseOsv", () => { + it("maps package vulnerabilities to dependency findings with OWASP-A06 citation", () => { + const out = parseOsv(osv); + assert.equal(out.length, 1); + assert.equal(out[0].category, "dependency"); + assert.equal(out[0].name, "lodash@4.17.11: GHSA-jf85-cpcp-j695"); + assert.equal(out[0].severity, "high"); + assert.equal(out[0].rule?.id, "OWASP-A06"); + assert.match(out[0].detail, /Prototype pollution/); + }); + + it("returns [] on garbage", () => { + assert.deepEqual(parseOsv("nope"), []); + }); +}); + +describe("ingest dispatch", () => { + it("routes by format; unknown → []", () => { + assert.equal(ingest("sarif", sarif).length, 2); + assert.equal(ingest("osv", osv).length, 1); + // @ts-expect-error unknown format + assert.deepEqual(ingest("nope", sarif), []); + }); +}); diff --git a/src/adapters/ingest.ts b/src/adapters/ingest.ts new file mode 100644 index 00000000..19e2eea9 --- /dev/null +++ b/src/adapters/ingest.ts @@ -0,0 +1,187 @@ +/** + * Scanner-output ingestion adapters: one parser per *format*, not per tool. + * + * SARIF 2.1.0 is emitted by semgrep, CodeQL, Trivy, Grype, …; OSV-scanner JSON by + * osv-scanner and others. Normalizing the format (not each tool) lets kit ingest + * any SARIF/OSV-emitting scanner into its own `SecurityCheckResult` shape — so the + * finding ledger, citations, and severity ranking work uniformly across engines. + * + * Pure (string in → findings out); no I/O, so it's fully fixture-tested. + */ +import type { SecurityCheckResult } from "../check-security.js"; +import type { RuleRef } from "../rules/catalog.js"; + +type Severity = NonNullable; + +/** GitHub's SARIF convention: `security-severity` is a CVSS 0–10 string. */ +function cvssToSeverity(raw: string | undefined): Severity | undefined { + if (raw === undefined) return undefined; + const n = Number.parseFloat(raw); + if (Number.isNaN(n)) return undefined; + if (n >= 9) return "critical"; + if (n >= 7) return "high"; + if (n >= 4) return "medium"; + return "low"; +} + +/** SARIF `level` fallback when no numeric severity is present. */ +function levelToSeverity(level: string | undefined): Severity { + switch ((level ?? "").toLowerCase()) { + case "error": + return "high"; + case "warning": + return "medium"; + default: + return "low"; // note / none / missing + } +} + +/** A CWE citation if any rule tag looks like `CWE-79` / `cwe-79` / `external/cwe/cwe-89`. */ +function cweRuleFromTags(tags: string[] | undefined): RuleRef | undefined { + for (const t of tags ?? []) { + const m = /cwe[-/]?(\d+)/i.exec(t); + if (m) { + const n = m[1]; + return { + id: `CWE-${n}`, + source: "cwe", + ref: `https://cwe.mitre.org/data/definitions/${n}.html`, + title: `CWE-${n}`, + }; + } + } + return undefined; +} + +// ---- SARIF (minimal shape — only the fields we read) ---- +interface SarifRule { + id?: string; + properties?: { tags?: string[]; "security-severity"?: string }; +} +interface SarifLocation { + physicalLocation?: { artifactLocation?: { uri?: string }; region?: { startLine?: number } }; +} +interface SarifResult { + ruleId?: string; + level?: string; + message?: { text?: string }; + locations?: SarifLocation[]; + properties?: { "security-severity"?: string }; +} +interface SarifRun { + tool?: { driver?: { name?: string; rules?: SarifRule[] } }; + results?: SarifResult[]; +} +interface SarifLog { + runs?: SarifRun[]; +} + +export function parseSarif(json: string): SecurityCheckResult[] { + let log: SarifLog; + try { + log = JSON.parse(json) as SarifLog; + } catch { + return []; + } + const out: SecurityCheckResult[] = []; + for (const run of log.runs ?? []) { + const tool = run.tool?.driver?.name ?? "sarif"; + const rulesById = new Map(); + for (const r of run.tool?.driver?.rules ?? []) if (r.id) rulesById.set(r.id, r); + for (const res of run.results ?? []) { + const ruleId = res.ruleId ?? "(rule)"; + const rule = rulesById.get(ruleId); + const severity = + cvssToSeverity(res.properties?.["security-severity"] ?? rule?.properties?.["security-severity"]) ?? + levelToSeverity(res.level); + const loc = res.locations?.[0]?.physicalLocation; + const uri = loc?.artifactLocation?.uri; + const line = loc?.region?.startLine; + const where = uri ? ` (${uri}${line ? `:${line}` : ""})` : ""; + out.push({ + category: "exposure", + name: `${tool}: ${ruleId}`, + status: "fail", + detail: `${res.message?.text ?? ruleId}${where}`, + severity, + rule: cweRuleFromTags(rule?.properties?.tags), + }); + } + } + return out; +} + +// ---- OSV-scanner JSON (minimal shape) ---- +interface OsvVuln { + id?: string; + summary?: string; + database_specific?: { severity?: string }; +} +interface OsvPackage { + package?: { name?: string; ecosystem?: string; version?: string }; + vulnerabilities?: OsvVuln[]; +} +interface OsvResult { + packages?: OsvPackage[]; +} +interface OsvLog { + results?: OsvResult[]; +} + +const OSV_RULE: RuleRef = { + id: "OWASP-A06", + source: "owasp", + ref: "https://owasp.org/Top10/A06_2021-Vulnerable_and_Outdated_Components/", + title: "Vulnerable and Outdated Components", +}; + +function osvSeverity(v: OsvVuln): Severity { + switch ((v.database_specific?.severity ?? "").toLowerCase()) { + case "critical": + return "critical"; + case "high": + return "high"; + case "moderate": + case "medium": + return "medium"; + case "low": + return "low"; + default: + // A reported vuln with an unknown label is still worth flagging high. + return "high"; + } +} + +export function parseOsv(json: string): SecurityCheckResult[] { + let log: OsvLog; + try { + log = JSON.parse(json) as OsvLog; + } catch { + return []; + } + const out: SecurityCheckResult[] = []; + for (const r of log.results ?? []) { + for (const p of r.packages ?? []) { + const name = p.package?.name ?? "(package)"; + const ver = p.package?.version ? `@${p.package.version}` : ""; + for (const v of p.vulnerabilities ?? []) { + out.push({ + category: "dependency", + name: `${name}${ver}: ${v.id ?? "vuln"}`, + status: "fail", + detail: v.summary ?? v.id ?? "known vulnerability", + severity: osvSeverity(v), + rule: OSV_RULE, + }); + } + } + } + return out; +} + +export type IngestFormat = "sarif" | "osv"; + +/** Dispatch to the right parser. Unknown format → []. */ +export function ingest(format: IngestFormat, json: string): SecurityCheckResult[] { + return format === "sarif" ? parseSarif(json) : format === "osv" ? parseOsv(json) : []; +} diff --git a/src/cli.ts b/src/cli.ts index 78b824d3..87a5a71c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -4122,6 +4122,51 @@ async function cmdHealth(): Promise { ); } +async function cmdIngest(): Promise { + const jsonMode = hasFlag(process.argv, "--json"); + const args = process.argv.slice(3).filter((a) => !a.startsWith("-")); + const format = args[0]; + const file = args[1]; + if (format !== "sarif" && format !== "osv") { + console.error(`${c.red}usage: kit ingest ${c.reset}`); + process.exitCode = 1; + return false; + } + if (!file) { + console.error(`${c.red}usage: kit ingest ${format} ${c.reset}`); + process.exitCode = 1; + return false; + } + let json: string; + try { + json = readFileSync(resolve(process.cwd(), file), "utf8"); + } catch { + console.error(`${c.red}could not read ${file}${c.reset}`); + process.exitCode = 1; + return false; + } + + const { ingest } = await import("./adapters/ingest.js"); + const findings = ingest(format, json); + + if (jsonMode) { + console.log(JSON.stringify({ count: findings.length, findings }, null, 2)); + return true; + } + + console.log(`${c.bold}kit ingest${c.reset} ${c.dim}${format} · ${findings.length} finding(s)${c.reset}`); + const order: Record = { critical: 0, high: 1, medium: 2, low: 3 }; + const sorted = [...findings].sort((a, b) => (order[a.severity ?? "low"] ?? 9) - (order[b.severity ?? "low"] ?? 9)); + for (const f of sorted) { + const sev = f.severity ?? "low"; + const color = sev === "critical" || sev === "high" ? c.red : sev === "medium" ? c.yellow : c.dim; + const cite = f.rule ? ` ${c.dim}[${f.rule.id}]${c.reset}` : ""; + console.log(` ${color}${sev.toUpperCase().padEnd(8)}${c.reset} ${f.name}${cite}`); + console.log(` ${c.dim}${f.detail}${c.reset}`); + } + return true; +} + async function cmdWhoami(): Promise { const jsonMode = hasFlag(process.argv, "--json"); @@ -4860,6 +4905,7 @@ async function main(): Promise { whoami: cmdWhoami, check: cmdCheck, health: cmdHealth, + ingest: cmdIngest, init: cmdInit, upgrade: cmdUpgrade, install: cmdInstall,