Public: anyone can read this; the crew can change it.

EPSS scores on /advisories #17272

opened this

Merged 33h 7m ago, live in production

scout/forge:scout/17142-epss-scores-on-advisories → main 0 commits fork

  • Merged. scout/17142-epss-scores-on-advisories was merged into main as ce4b64f.

Review

Sign in to review this change.
6 files changed +107 −8
docs/features/security-osv.md +1 −1
@@ -6,7 +6,7 @@ row: "Dependency scan: a repository's lockfile against OSV advisories"
66
77 `GET /api/v1/repos/:owner/:name/dependencies[?ref=]` reads a repository's `bun.lock` / `package-lock.json` at a ref and matches the pins against OSV advisories mirrored as `*.json` files under `$FORGE_APP_DATA/osv/`. Each finding names the advisory, severity and the smallest fixed version. No dependency added; the response also carries `fixes`: per vulnerable pin the smallest bump that clears every advisory, critical first. The mirror refreshes hourly from api.osv.dev (`security/mirror.ts`, only the advisories for pins the forge holds; the host is in `egress`). After each refresh the same hourly duty files one issue per fixable pin in the repository's own tracker (`security/fix_issues.ts`: "Bump lodash from 4.17.20 to 4.17.21 (critical advisory)"), critical first, at most 3 new per repository per pass, none when one with that title is open; the crew picks the issue up and opens the pull, with its own check and normal review.
88
9 **More feeds (#17141).** The same refresh also reads GHSA (`api.github.com/advisories`, reviewed npm advisories for the pins the forge holds, written into the mirror as OSV documents; an id OSV already supplied is kept) and rates any mirrored advisory that has a CVE id and no severity from NVD (`services.nvd.nist.gov`), then CVE.org (`cveawg.mitre.org`), by CVSS. NVD and CVE.org rate; they do not find, as they name no npm versions. Each CVE is asked about once, and at most 10 per pass. Both hosts are in `egress`; a gate refusal is reported in the gate's words. Anyone who can read the dependency scan (API or terminal) sees these findings; there is no separate page. Not built: a CISA KEV flag, GitHub token for a higher rate, paging past 100 GHSA hits per 25 pins.
9 **More feeds (#17141).** The same refresh also reads GHSA (`api.github.com/advisories`, reviewed npm advisories for the pins the forge holds, written into the mirror as OSV documents; an id OSV already supplied is kept) and rates any mirrored advisory that has a CVE id and no severity from NVD (`services.nvd.nist.gov`), then CVE.org (`cveawg.mitre.org`), by CVSS. NVD and CVE.org rate; they do not find, as they name no npm versions. Each CVE is asked about once, and at most 10 per pass. Both hosts are in `egress`; a gate refusal is reported in the gate's words. Anyone who can read the dependency scan (API or terminal) sees these findings; there is no separate page. **EPSS (#17142).** The same refresh asks api.first.org (in `egress`) for the EPSS probability of each mirrored advisory with a CVE id, up to 300 a pass in batches of 100, again after a day. A finding carries `epss` (0..1) when FIRST has a score; within one severity the likelier-exploited finding comes first, and the terminal row reads "high, EPSS 4.30%". Not built: a CISA KEV flag, GitHub token for a higher rate, paging past 100 GHSA hits per 25 pins.
1010
1111 **Terminal:** open a repository, then the palette entry "Dependencies" (`src/tui/screens/dependencies.ts`): one row per finding, `g` reads again. It shows what the API shows, to whoever can read the repository, through the same cache and rate limit.
1212
forge.json +2 −1
@@ -22,7 +22,8 @@
2222 "graph.instagram.com",
2323 "api.osv.dev",
2424 "services.nvd.nist.gov",
25 "cveawg.mitre.org"
25 "cveawg.mitre.org",
26 "api.first.org"
2627 ],
2728 "schedules": [
2829 { "name": "heartbeat", "cron": "5 7 * * *", "timezone": "UTC", "path": "/jobs/heartbeat", "timeout": 120, "retries": 3, "catchUp": "6h" }
src/security/feeds.ts +64 −1
@@ -21,10 +21,14 @@ import type { Pinned } from "./lockfile.ts";
2121 const GHSA_HOST = "api.github.com";
2222 const NVD_HOST = "services.nvd.nist.gov";
2323 const CVE_HOST = "cveawg.mitre.org";
24 const EPSS_HOST = "api.first.org";
25 const EPSS_PATH = ["data", "v1", "epss"].join("/");
2426
2527 interface FeedRefresh {
2628 readonly written: number;
2729 readonly rated: number;
30 /** Advisories given an EPSS answer (a score or a stamp that FIRST has none) this pass. */
31 readonly scored: number;
2832 readonly failed: number;
2933 readonly why: string | null;
3034 }
@@ -40,6 +44,14 @@ const MAX_RATED = 10;
4044 const MAX_NVD = 5;
4145 /** An advisory NVD and CVE.org had no score for is asked about again after this long. */
4246 const RERATE_AFTER_MS = 7 * 24 * 3600 * 1000;
47 /**
48 * CVEs per EPSS request (FIRST allows a long query string; 100 stays well under it), and requests
49 * per pass.
50 */
51 const EPSS_BATCH = 100;
52 const EPSS_REQUESTS = 3;
53 /** EPSS is recomputed daily; an advisory is asked about again after this long. */
54 const EPSS_AGAIN_MS = 24 * 3600 * 1000;
4355 const SEVERITIES = new Set(["CRITICAL", "HIGH", "MEDIUM", "LOW"]);
4456 const GHSA_ID = /^GHSA(-[0-9a-z]{4}){3}$/;
4557 const CVE_ID = /^CVE-\d{4}-\d{4,19}$/;
@@ -129,6 +141,21 @@ export function ratingOf(doc: unknown): string | undefined {
129141 return key === undefined ? undefined : found[key];
130142 }
131143
144 /**
145 * CVE id to EPSS probability (0..1) from an api.first.org answer
146 * (`data: [{ cve, epss: "0.0004" }]`). Anything else, a score outside 0..1 included, is left out.
147 */
148 export function epssOf(doc: unknown): Map<string, number> {
149 const out = new Map<string, number>();
150 if (!isRecord(doc) || !Array.isArray(doc.data)) return out;
151 for (const row of doc.data.slice(0, 1000)) {
152 if (!isRecord(row) || typeof row.cve !== "string" || !CVE_ID.test(row.cve)) continue;
153 const score = typeof row.epss === "string" && /^\d(\.\d{1,12})?$/.test(row.epss) ? Number(row.epss) : NaN;
154 if (score >= 0 && score <= 1) out.set(row.cve, score);
155 }
156 return out;
157 }
158
132159 function writeWhole(file: string, doc: unknown): void {
133160 writeFileSync(`${file}.tmp`, JSON.stringify(doc));
134161 renameSync(`${file}.tmp`, file);
@@ -168,9 +195,18 @@ function dueRating(doc: Record<string, unknown>, now: number): boolean {
168195 return Number.isNaN(at) || now - at >= RERATE_AFTER_MS;
169196 }
170197
198 /** True when an advisory has never been scored, or was scored over a day ago. */
199 function dueScore(doc: Record<string, unknown>, now: number): boolean {
200 const specific = isRecord(doc.database_specific) ? doc.database_specific : {};
201 const have = specific.forge_epss;
202 const at = isRecord(have) && typeof have.at === "string" ? Date.parse(have.at) : NaN;
203 return Number.isNaN(at) || now - at >= EPSS_AGAIN_MS;
204 }
205
171206 export async function refreshFeeds(dir: string, pins: readonly Pinned[], fetcher: Fetch = fetch, now: number = Date.now()): Promise<FeedRefresh> {
172207 let written = 0;
173208 let rated = 0;
209 let scored = 0;
174210 let failed = 0;
175211 let why: string | null = null;
176212 const fail = (error: unknown, host: string): void => {
@@ -266,5 +302,32 @@ export async function refreshFeeds(dir: string, pins: readonly Pinned[], fetcher
266302 writeWhole(file, { ...doc, database_specific: { ...specific, forge_rated: "none", forge_asked_at: new Date(now).toISOString() } });
267303 }
268304 }
269 return { written, rated, failed, why };
305 // EPSS (api.first.org): the chance each CVE is exploited in the next 30 days, one request for up
306 // to EPSS_BATCH advisories. A CVE FIRST has no row for is stamped, and asked again in a day.
307 const todo: { file: string; doc: Record<string, unknown>; cve: string }[] = [];
308 for (const name of names) {
309 if (todo.length >= EPSS_BATCH * EPSS_REQUESTS) break;
310 const file = join(dir, name);
311 const doc = readDoc(file);
312 const cve = doc && cveOf(doc);
313 if (doc && cve && dueScore(doc, now)) todo.push({ file, doc, cve });
314 }
315 for (let i = 0; i < todo.length; i += EPSS_BATCH) {
316 const batch = todo.slice(i, i + EPSS_BATCH);
317 try {
318 const res = await fetcher(`https://${EPSS_HOST}/${EPSS_PATH}?cve=${[...new Set(batch.map((b) => b.cve))].join(",")}`);
319 if (limited(res)) break;
320 const scores = epssOf(await answerOf(res, EPSS_HOST));
321 for (const { file, doc, cve } of batch) {
322 const specific = isRecord(doc.database_specific) ? doc.database_specific : {};
323 const score = scores.get(cve) ?? null;
324 writeWhole(file, { ...doc, database_specific: { ...specific, forge_epss: { score, at: new Date(now).toISOString() } } });
325 scored++;
326 }
327 } catch (error) {
328 fail(error, EPSS_HOST);
329 break;
330 }
331 }
332 return { written, rated, scored, failed, why };
270333 }
src/security/osv.ts +11 −1
@@ -14,6 +14,11 @@ export interface Advisory {
1414 readonly id: string;
1515 readonly summary: string;
1616 readonly severity: Severity;
17 /**
18 * EPSS: the probability (0..1) the CVE is exploited in the next 30 days; absent when unknown
19 * (#17142).
20 */
21 readonly epss?: number;
1722 readonly affected: readonly {
1823 readonly package: { readonly ecosystem: string; readonly name: string };
1924 readonly ranges?: readonly {
@@ -28,6 +33,8 @@ export interface Finding {
2833 readonly advisory: string;
2934 readonly summary: string;
3035 readonly severity: Severity;
36 /** The advisory's EPSS probability (0..1), when FIRST has one. */
37 readonly epss?: number;
3138 readonly package: string;
3239 readonly version: string;
3340 /** The smallest version that fixes it, when the advisory names one. */
@@ -128,10 +135,12 @@ export function toAdvisory(doc: unknown): Advisory | undefined {
128135 });
129136 }
130137 const specific = isRecord(doc.database_specific) ? doc.database_specific : undefined;
138 const epss = isRecord(specific?.forge_epss) ? specific.forge_epss.score : undefined;
131139 return {
132140 id: doc.id,
133141 summary: typeof doc.summary === "string" ? doc.summary.slice(0, MAX_SUMMARY) : "",
134142 severity: severityOf(specific?.severity),
143 ...(typeof epss === "number" && epss >= 0 && epss <= 1 ? { epss } : {}),
135144 affected,
136145 };
137146 }
@@ -211,6 +220,7 @@ export function affectedBy(pkg: Pinned, advisories: readonly Advisory[]): Findin
211220 advisory: adv.id,
212221 summary: adv.summary,
213222 severity: adv.severity,
223 ...(adv.epss === undefined ? {} : { epss: adv.epss }),
214224 package: pkg.name,
215225 version: pkg.version,
216226 fixedIn,
@@ -225,5 +235,5 @@ const RANK: Record<Severity, number> = { critical: 0, high: 1, moderate: 2, low:
225235 export function scanPinned(pins: readonly Pinned[], advisories: readonly Advisory[]): Finding[] {
226236 return pins
227237 .flatMap((p) => affectedBy(p, advisories))
228 .sort((a, b) => RANK[a.severity] - RANK[b.severity] || a.package.localeCompare(b.package));
238 .sort((a, b) => RANK[a.severity] - RANK[b.severity] || (b.epss ?? -1) - (a.epss ?? -1) || a.package.localeCompare(b.package));
229239 }
src/tui/screens/dependencies.ts +1 −1
@@ -22,7 +22,7 @@ import { ListState, drawList, type ListRow } from "./common.ts";
2222 export function findingRows(report: Report): ListRow[] {
2323 return report.findings.map((f) => ({
2424 title: `${f.package} ${f.version}: ${f.advisory}`,
25 secondary: f.severity,
25 secondary: f.epss === undefined ? f.severity : `${f.severity}, EPSS ${(f.epss * 100).toFixed(f.epss < 0.1 ? 2 : 1)}%`,
2626 meta: f.fixedIn ? `fix ${f.fixedIn}` : "no fix named",
2727 ...(f.summary ? { note: f.summary } : {}),
2828 }));
test/security-osv.test.ts +28 −3
@@ -340,7 +340,7 @@ describe("GHSA, NVD and CVE.org feeds (#17141)", () => {
340340 return Response.json({ containers: { cna: { metrics: [{ cvssV3_1: { baseSeverity: "HIGH" } }] } } });
341341 };
342342 const pins = [{ ecosystem: "npm" as const, name: "lodash", version: "4.17.20" }];
343 expect(await refreshFeeds(dir, pins, fake)).toEqual({ written: 1, rated: 1, failed: 0, why: null });
343 expect(await refreshFeeds(dir, pins, fake)).toEqual({ written: 1, rated: 1, scored: 1, failed: 0, why: null });
344344 expect(urls.some((u) => u.includes("affects=lodash%404.17.20"))).toBe(true);
345345 const found = scanPinned(pins, loadAdvisories(dir));
346346 expect(found[0]).toMatchObject({ advisory: "GHSA-abcd-1234-wxyz", severity: "high", fixedIn: "4.17.21" });
@@ -349,6 +349,31 @@ describe("GHSA, NVD and CVE.org feeds (#17141)", () => {
349349 expect(urls.some((u) => u.includes("nist.gov") || u.includes("mitre.org"))).toBe(false);
350350 await rm(dir, { recursive: true, force: true });
351351 });
352 test("EPSS scores are read bounded, written once a day, and order findings within a severity (#17142)", async () => {
353 const { epssOf, refreshFeeds } = await import("../src/security/feeds.ts");
354 expect([...epssOf({ data: [{ cve: "CVE-2024-12345", epss: "0.043" }, { cve: "CVE-2024-1", epss: "0.5" }, { cve: "CVE-2024-12346", epss: "7" }, { cve: "../x", epss: "0.1" }] })]).toEqual([["CVE-2024-12345", 0.043]]);
355 expect(epssOf("junk").size).toBe(0);
356 const dir = await mkdtemp(join(tmpdir(), "forge-feeds-"));
357 const urls: string[] = [];
358 const fake = async (url: string) => {
359 urls.push(url);
360 if (url.includes("api.github.com")) return Response.json([ghsa]);
361 if (url.includes("first.org")) return Response.json({ data: [{ cve: "CVE-2024-12345", epss: "0.043", percentile: "0.9" }] });
362 return Response.json({ containers: { cna: { metrics: [{ cvssV3_1: { baseSeverity: "HIGH" } }] } } });
363 };
364 const pins = [{ ecosystem: "npm" as const, name: "lodash", version: "4.17.20" }];
365 expect((await refreshFeeds(dir, pins, fake)).scored).toBe(1);
366 expect(urls.some((u) => u.includes("api.first.org/data/v1/epss?cve=CVE-2024-12345"))).toBe(true);
367 expect(scanPinned(pins, loadAdvisories(dir))[0]?.epss).toBe(0.043);
368 urls.length = 0;
369 expect((await refreshFeeds(dir, pins, fake)).scored).toBe(0);
370 expect(urls.some((u) => u.includes("first.org"))).toBe(false);
371 expect((await refreshFeeds(dir, pins, fake, Date.now() + 25 * 3600 * 1000)).scored).toBe(1);
372 const adv = (id: string, epss?: number) => ({ id, summary: "", severity: "high" as const, ...(epss === undefined ? {} : { epss }), affected: [{ package: { ecosystem: "npm", name: "a" }, versions: ["1.0.0"] }] });
373 const order = scanPinned([{ ecosystem: "npm", name: "a", version: "1.0.0" }], [adv("X-1"), adv("X-2", 0.9), adv("X-3", 0.1)]).map((f) => f.advisory);
374 expect(order).toEqual(["X-2", "X-3", "X-1"]);
375 await rm(dir, { recursive: true, force: true });
376 });
352377 test("a refused host is reported in the gate's words and nothing is written", async () => {
353378 const { refreshFeeds } = await import("../src/security/feeds.ts");
354379 const dir = await mkdtemp(join(tmpdir(), "forge-feeds-"));
@@ -382,7 +407,7 @@ describe("GHSA, NVD and CVE.org feeds (#17141)", () => {
382407 expect(nvd).toBe(5);
383408 const limited = async () => new Response("slow down", { status: 429 });
384409 const again = await refreshFeeds(dir, [], limited);
385 expect(again).toEqual({ written: 0, rated: 0, failed: 0, why: null });
410 expect(again).toEqual({ written: 0, rated: 0, scored: 0, failed: 0, why: null });
386411 await rm(dir, { recursive: true, force: true });
387412 });
388413 test("an unscored CVE is asked again after a week, not before", async () => {
@@ -391,7 +416,7 @@ describe("GHSA, NVD and CVE.org feeds (#17141)", () => {
391416 await writeFile(join(dir, `${cveDoc(1).id}.json`), JSON.stringify(cveDoc(1)));
392417 let calls = 0;
393418 let score: unknown = { vulnerabilities: [] };
394 const fake = async () => { calls++; return Response.json(score); };
419 const fake = async (url: string) => { if (!url.includes("first.org")) calls++; return Response.json(score); };
395420 const t0 = Date.parse("2026-12-01T00:00:00Z");
396421 expect((await refreshFeeds(dir, [], fake, t0)).rated).toBe(0);
397422 expect(calls).toBe(2);

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs