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

CVE.org, GHSA and NVD feeds into /advisories #17217

opened this

Merged 36h 10m ago, live in production

scout/forge:scout/17141-cve-org-ghsa-and-nvd-feeds-into-advisori → main 0 commits fork 4 threads · 4 unresolved

  • Merged. scout/17141-cve-org-ghsa-and-nvd-feeds-into-advisori was merged into main as 6947127.

Review

Sign in to review this change.
6 files changed +408 −10
docs/features/security-osv.md +2
@@ -6,6 +6,8 @@ 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.
10
911 **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.
1012
1113 **Load.** The report is held by commit oid and the mirror's stamp, so a repeat read costs a lookup; a client address may read 20 times a minute and the forge 300 (429 with `Retry-After` beyond), and one read takes at most 20 lockfiles and 30 MB.
forge.json +3 −1
@@ -20,7 +20,9 @@
2020 "management.azure.com",
2121 "api.typesafe.ai",
2222 "graph.instagram.com",
23 "api.osv.dev"
23 "api.osv.dev",
24 "services.nvd.nist.gov",
25 "cveawg.mitre.org"
2426 ],
2527 "schedules": [
2628 { "name": "heartbeat", "cron": "5 7 * * *", "timezone": "UTC", "path": "/jobs/heartbeat", "timeout": 120, "retries": 3, "catchUp": "6h" }
src/security/duty.ts +7 −2
@@ -7,6 +7,7 @@
77 import { join } from "node:path";
88 import type { App } from "../app.ts";
99 import { repoDir } from "../git/repos.ts";
10 import { refreshFeeds } from "./feeds.ts";
1011 import { refreshMirror, type Fetch, type Refresh } from "./mirror.ts";
1112 import { mayAsk } from "./optin.ts";
1213 import { pinsOf } from "./scan.ts";
@@ -31,10 +32,14 @@ export async function refreshOsv(app: Pick<App, "db" | "reposRoot" | "config" |
3132 // A repository that cannot be read is skipped; the rest still refresh.
3233 }
3334 }
34 const out = await refreshMirror(join(app.config.dataDir, "osv"), pins, fetcher);
35 const dir = join(app.config.dataDir, "osv");
36 const osv = await refreshMirror(dir, pins, fetcher);
37 // GHSA, NVD and CVE.org add to the same mirror (#17141); their failures count with OSV's.
38 const feeds = await refreshFeeds(dir, pins, fetcher);
39 const out: Refresh = { asked: osv.asked, written: osv.written + feeds.written, failed: osv.failed + feeds.failed, why: osv.why ?? feeds.why };
3540 // The outcome is kept for the board: a failure says why and that the old mirror was kept
3641 // (#17047).
3742 recordStanding(app.config.dataDir, out, Date.now());
38 app.log.info("osv mirror refreshed", { asked: out.asked, written: out.written, failed: out.failed, ...(out.why === null ? {} : { why: out.why }) });
43 app.log.info("osv mirror refreshed", { asked: out.asked, written: out.written, rated: feeds.rated, failed: out.failed, ...(out.why === null ? {} : { why: out.why }) });
3944 return out;
4045 }
src/security/feeds.ts added +270
@@ -0,0 +1,270 @@
1 /**
2 * Three more advisory feeds into the same mirror (`$FORGE_APP_DATA/osv/*.json`), so every reader of
3 * the mirror (the scan, the fix issues, the board) sees them with no change of its own (#17141).
4 *
5 * - GHSA (api.github.com/advisories): advisories for the pins the forge holds, rewritten as OSV
6 * documents. An id the mirror already holds from OSV is kept as it is.
7 * - NVD (services.nvd.nist.gov) then CVE.org (cveawg.mitre.org): a mirrored advisory with a CVE id
8 * and no severity gets its CVSS rating from the first of the two that has one. Neither lists npm
9 * package versions in a form that can be matched, so they rate; they do not find.
10 *
11 * Every answer is untrusted: ids are checked as paths, text is bounded, and `toAdvisory` has the
12 * last word on what is written. The only network use here; `fetch` is passed in.
13 */
14
15 import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
16 import { join } from "node:path";
17 import { answerOf, wordsOf, type Fetch } from "./mirror.ts";
18 import { toAdvisory } from "./osv.ts";
19 import type { Pinned } from "./lockfile.ts";
20
21 const GHSA_HOST = "api.github.com";
22 const NVD_HOST = "services.nvd.nist.gov";
23 const CVE_HOST = "cveawg.mitre.org";
24
25 interface FeedRefresh {
26 readonly written: number;
27 readonly rated: number;
28 readonly failed: number;
29 readonly why: string | null;
30 }
31
32 /** Pins per GHSA request, and requests per pass: unauthenticated GitHub allows 60 an hour. */
33 const GHSA_BATCH = 25;
34 const GHSA_REQUESTS = 20;
35 /**
36 * Ratings written per pass, and NVD calls per pass: NVD without a key allows 5 requests in 30
37 * seconds.
38 */
39 const MAX_RATED = 10;
40 const MAX_NVD = 5;
41 /** An advisory NVD and CVE.org had no score for is asked about again after this long. */
42 const RERATE_AFTER_MS = 7 * 24 * 3600 * 1000;
43 const SEVERITIES = new Set(["CRITICAL", "HIGH", "MEDIUM", "LOW"]);
44 const GHSA_ID = /^GHSA(-[0-9a-z]{4}){3}$/;
45 const CVE_ID = /^CVE-\d{4}-\d{4,19}$/;
46
47 const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
48
49 /** `>= 1.0.0, < 1.2.3` (GitHub's range words) as OSV events; undefined for anything else. */
50 export function rangeEvents(range: string): { events: Record<string, string>[]; versions: string[] } | undefined {
51 let lower: string | undefined;
52 let upper: Record<string, string> | undefined;
53 const versions: string[] = [];
54 for (const part of range.split(",")) {
55 const m = /^\s*(>=|>|<=|<|=)\s*(\S+)\s*$/.exec(part);
56 if (!m) return undefined;
57 const [, op, v] = m as unknown as [string, string, string];
58 if (op === "=") versions.push(v);
59 else if (op === ">=" || op === ">") lower = v;
60 else upper = op === "<" ? { fixed: v } : { last_affected: v };
61 }
62 if (versions.length > 0) return lower === undefined && upper === undefined ? { events: [], versions } : undefined;
63 if (lower === undefined && upper === undefined) return undefined;
64 return { events: [{ introduced: lower ?? "0" }, ...(upper ? [upper] : [])], versions };
65 }
66
67 /**
68 * One GHSA advisory as an OSV document, or undefined when it is withdrawn, not npm, or unreadable.
69 * `>` is read as `>=`: the one version named is treated as affected, the safe side.
70 */
71 export function ghsaToOsv(raw: unknown): Record<string, unknown> | undefined {
72 if (!isRecord(raw) || typeof raw.ghsa_id !== "string" || !GHSA_ID.test(raw.ghsa_id)) return undefined;
73 if (raw.withdrawn_at !== undefined && raw.withdrawn_at !== null) return undefined;
74 if (!Array.isArray(raw.vulnerabilities)) return undefined;
75 const affected: Record<string, unknown>[] = [];
76 for (const v of raw.vulnerabilities.slice(0, 200)) {
77 if (!isRecord(v) || !isRecord(v.package) || v.package.ecosystem !== "npm" || typeof v.package.name !== "string") continue;
78 const parsed = typeof v.vulnerable_version_range === "string" ? rangeEvents(v.vulnerable_version_range) : undefined;
79 if (!parsed) continue;
80 affected.push({
81 package: { ecosystem: "npm", name: v.package.name },
82 ranges: parsed.events.length > 0 ? [{ type: "SEMVER", events: parsed.events }] : [],
83 versions: parsed.versions,
84 });
85 }
86 if (affected.length === 0) return undefined;
87 const cve = typeof raw.cve_id === "string" && CVE_ID.test(raw.cve_id) ? [raw.cve_id] : [];
88 return {
89 id: raw.ghsa_id,
90 summary: typeof raw.summary === "string" ? raw.summary : "",
91 aliases: cve,
92 modified: typeof raw.updated_at === "string" ? raw.updated_at : "",
93 database_specific: { severity: typeof raw.severity === "string" ? raw.severity : "", forge_source: "ghsa" },
94 affected,
95 };
96 }
97
98 const SCORES = ["cvssV4_0", "cvssV3_1", "cvssV3_0"] as const;
99
100 /**
101 * The CVSS severity word in an NVD answer (`vulnerabilities[0].cve.metrics`) or a CVE.org record
102 * (`containers.cna.metrics` and each `adp`); the newest CVSS version wins. Undefined when none.
103 */
104 export function ratingOf(doc: unknown): string | undefined {
105 if (!isRecord(doc)) return undefined;
106 const found: Record<string, string> = {};
107 const note = (key: string, data: unknown): void => {
108 if (isRecord(data) && typeof data.baseSeverity === "string" && SEVERITIES.has(data.baseSeverity) && found[key] === undefined)
109 found[key] = data.baseSeverity;
110 };
111 const nvd = Array.isArray(doc.vulnerabilities) && isRecord(doc.vulnerabilities[0]) ? doc.vulnerabilities[0].cve : undefined;
112 if (isRecord(nvd) && isRecord(nvd.metrics)) {
outdated

baseSeverity is accepted as any string. Restrict it to CRITICAL/HIGH/MEDIUM/LOW before it is written to the mirror.

113 const m = nvd.metrics;
114 const pairs: [string, string][] = [["cvssMetricV40", "cvssV4_0"], ["cvssMetricV31", "cvssV3_1"], ["cvssMetricV30", "cvssV3_0"]];
115 for (const [from, to] of pairs) {
116 const list = m[from];
117 if (Array.isArray(list) && isRecord(list[0])) note(to, list[0].cvssData);
118 }
119 }
120 const containers: unknown[] = [];
121 if (isRecord(doc.containers)) {
122 containers.push(doc.containers.cna);
123 if (Array.isArray(doc.containers.adp)) containers.push(...doc.containers.adp.slice(0, 10));
124 }
125 for (const c of containers)
126 if (isRecord(c) && Array.isArray(c.metrics))
127 for (const metric of c.metrics.slice(0, 20)) if (isRecord(metric)) for (const k of SCORES) note(k, metric[k]);
128 const key = SCORES.find((k) => found[k] !== undefined);
129 return key === undefined ? undefined : found[key];
130 }
131
132 function writeWhole(file: string, doc: unknown): void {
133 writeFileSync(`${file}.tmp`, JSON.stringify(doc));
134 renameSync(`${file}.tmp`, file);
135 }
136
137 function readDoc(file: string): Record<string, unknown> | undefined {
138 try {
139 const doc: unknown = JSON.parse(readFileSync(file, "utf8"));
140 return isRecord(doc) ? doc : undefined;
141 } catch {
142 return undefined;
143 }
144 }
145
146 const fromGhsa = (doc: Record<string, unknown> | undefined): boolean =>
147 doc !== undefined && isRecord(doc.database_specific) && doc.database_specific.forge_source === "ghsa";
148
149 /** The CVE id an OSV document is about: its own id or one of its aliases. */
150 function cveOf(doc: Record<string, unknown>): string | undefined {
151 const ids = [doc.id, ...(Array.isArray(doc.aliases) ? doc.aliases : [])];
152 return ids.find((i): i is string => typeof i === "string" && CVE_ID.test(i));
153 }
154
155 /** A rate limit, as opposed to a failure: 429, or a 403 the forge's gate did not send. */
156 const limited = (res: Response): boolean => res.status === 429 || (res.status === 403 && res.headers.get("x-forge-egress") !== "refused");
157
158 /**
159 * True when an advisory has no severity and is due a question: never asked, or asked over a week
160 * ago.
161 */
162 function dueRating(doc: Record<string, unknown>, now: number): boolean {
163 const specific = isRecord(doc.database_specific) ? doc.database_specific : {};
164 if (/^(critical|high|moderate|medium|low)$/i.test(String(specific.severity ?? ""))) return false;
165 if (specific.forge_rated === undefined) return true;
166 if (specific.forge_rated !== "none") return false;
167 const at = typeof specific.forge_asked_at === "string" ? Date.parse(specific.forge_asked_at) : NaN;
outdated

if (readDoc(file)) continue means a GHSA advisory that was later corrected or withdrawn is never refreshed. Compare modified and rewrite, or remove the file on withdrawal.

168 return Number.isNaN(at) || now - at >= RERATE_AFTER_MS;
169 }
170
171 export async function refreshFeeds(dir: string, pins: readonly Pinned[], fetcher: Fetch = fetch, now: number = Date.now()): Promise<FeedRefresh> {
172 let written = 0;
173 let rated = 0;
174 let failed = 0;
175 let why: string | null = null;
176 const fail = (error: unknown, host: string): void => {
177 failed++;
178 why ??= wordsOf(error, host);
179 };
180 mkdirSync(dir, { recursive: true });
181 const unique = [...new Set(pins.map((p) => `${p.name}@${p.version}`))];
182 for (let i = 0, n = 0; i < unique.length && n < GHSA_REQUESTS; i += GHSA_BATCH, n++) {
183 const affects = encodeURIComponent(unique.slice(i, i + GHSA_BATCH).join(","));
184 try {
185 const res = await fetcher(`https://${GHSA_HOST}/advisories?ecosystem=npm&type=reviewed&per_page=100&affects=${affects}`, {
186 headers: { accept: "application/vnd.github+json", "x-github-api-version": "2022-11-28" },
187 });
188 const list = await answerOf(res, GHSA_HOST);
189 for (const raw of Array.isArray(list) ? list : []) {
190 const doc = ghsaToOsv(raw);
191 if (!doc) {
192 // A withdrawn advisory this feed wrote is taken out of the mirror; one OSV wrote is
193 // OSV's.
194 const id = isRecord(raw) && typeof raw.ghsa_id === "string" && GHSA_ID.test(raw.ghsa_id) ? raw.ghsa_id : undefined;
195 const gone = isRecord(raw) && raw.withdrawn_at !== undefined && raw.withdrawn_at !== null;
196 if (id && gone) {
197 const file = join(dir, `${id}.json`);
198 if (fromGhsa(readDoc(file))) {
outdated

Back-to-back NVD requests over the 5-per-30 s allowance: a 429 here makes fail() run every pass. Limit NVD calls per pass or pace them, and treat 429 as a skip, not a failure.

199 rmSync(file, { force: true });
200 written++;
201 }
202 }
203 continue;
204 }
205 if (!toAdvisory(doc)) continue;
206 const file = join(dir, `${String(doc.id)}.json`);
outdated

forge_rated: "none" is never revisited. A freshly published CVE has no NVD score yet, so it stays unrated forever. Store a timestamp and re-ask after a week.

207 const have = readDoc(file);
208 if (have) {
209 // Ours and older than the feed's copy: rewrite it, keeping a rating it was given.
210 if (!fromGhsa(have) || !(Date.parse(String(doc.modified)) > Date.parse(String(have.modified)))) continue;
211 const old = isRecord(have.database_specific) ? have.database_specific : {};
212 const fresh = isRecord(doc.database_specific) ? doc.database_specific : {};
213 if (fresh.severity === "" && old.forge_rated !== undefined) {
214 doc.database_specific = { ...fresh, severity: old.severity, forge_rated: old.forge_rated, forge_asked_at: old.forge_asked_at };
215 }
216 }
217 writeWhole(file, doc);
218 written++;
219 }
220 } catch (error) {
221 fail(error, GHSA_HOST);
222 }
223 }
224 // Advisories with a CVE id and no severity, at most MAX_RATED a pass and MAX_NVD of those asked
225 // of NVD (the rest go to CVE.org). An answer without a score is stamped, and asked again in a
226 // week.
227 let names: string[] = [];
228 try {
229 names = readdirSync(dir).filter((f) => f.endsWith(".json"));
230 } catch {
231 // An unreadable mirror has nothing to rate.
232 }
233 let nvdCalls = 0;
234 for (const name of names) {
235 if (rated >= MAX_RATED) break;
236 const file = join(dir, name);
237 const doc = readDoc(file);
238 const cve = doc && cveOf(doc);
239 if (!doc || !cve || !dueRating(doc, now)) continue;
240 const specific = isRecord(doc.database_specific) ? doc.database_specific : {};
241 let rating: string | undefined;
242 let asked = true;
243 const urls = [`https://${CVE_HOST}/api/cve/${cve}`];
244 if (nvdCalls < MAX_NVD) urls.unshift(`https://${NVD_HOST}/rest/json/cves/2.0?cveId=${cve}`);
245 for (const url of urls) {
246 const host = new URL(url).host;
247 if (host === NVD_HOST) nvdCalls++;
248 try {
249 const res = await fetcher(url);
250 if (limited(res)) {
251 asked = false;
252 nvdCalls = MAX_NVD;
253 continue;
254 }
255 rating = ratingOf(await answerOf(res, host));
256 if (rating) break;
257 } catch (error) {
258 asked = false;
259 fail(error, host);
260 }
261 }
262 if (rating) {
263 writeWhole(file, { ...doc, database_specific: { ...specific, severity: rating, forge_rated: "cvss" } });
264 rated++;
265 } else if (asked) {
266 writeWhole(file, { ...doc, database_specific: { ...specific, forge_rated: "none", forge_asked_at: new Date(now).toISOString() } });
267 }
268 }
269 return { written, rated, failed, why };
270 }
src/security/mirror.ts +7 −7
@@ -36,20 +36,20 @@ export type Fetch = (url: string, init?: RequestInit) => Promise<Response>;
3636 * content-length says. Throws a sentence: the gate's own words when the forge's gate refused the
3737 * host (a 403 marked `x-forge-egress: refused`).
3838 */
39 async function answerOf(res: Response): Promise<unknown> {
40 if (res.status === 403 && res.headers.get("x-forge-egress") === "refused") throw new Error(refusedWords(OSV_HOST));
41 if (!res.ok) throw new Error(`${OSV_HOST} answered HTTP ${String(res.status)}`);
39 export async function answerOf(res: Response, host: string = OSV_HOST): Promise<unknown> {
40 if (res.status === 403 && res.headers.get("x-forge-egress") === "refused") throw new Error(refusedWords(host));
41 if (!res.ok) throw new Error(`${host} answered HTTP ${String(res.status)}`);
4242 const body = await readCapped(res, MAX_BODY);
43 if (body === undefined) throw new Error(`${OSV_HOST} answered more than ${String(MAX_BODY)} bytes, or broke off`);
43 if (body === undefined) throw new Error(`${host} answered more than ${String(MAX_BODY)} bytes, or broke off`);
4444 try {
4545 return JSON.parse(new TextDecoder().decode(body));
4646 } catch {
47 throw new Error(`${OSV_HOST} answered something that is not JSON`);
47 throw new Error(`${host} answered something that is not JSON`);
4848 }
4949 }
5050
51 const wordsOf = (error: unknown): string =>
52 error instanceof GateRefusedError ? refusedWords(OSV_HOST) : error instanceof Error ? error.message : String(error);
51 export const wordsOf = (error: unknown, host: string = OSV_HOST): string =>
52 error instanceof GateRefusedError ? refusedWords(host) : error instanceof Error ? error.message : String(error);
5353
5454 function modifiedAt(file: string): string {
5555 try {
test/security-osv.test.ts +119
@@ -302,3 +302,122 @@ describe("what leaves the forge", () => {
302302 expect(reportWait(owner, "a", 61_000)).toBeUndefined();
303303 });
304304 });
305
306 describe("GHSA, NVD and CVE.org feeds (#17141)", () => {
307 const ghsa = {
308 ghsa_id: "GHSA-abcd-1234-wxyz",
309 cve_id: "CVE-2024-12345",
310 summary: "pollution",
311 severity: "",
312 withdrawn_at: null,
313 vulnerabilities: [{ package: { ecosystem: "npm", name: "lodash" }, vulnerable_version_range: ">= 4.0.0, < 4.17.21" }],
314 };
315 test("ranges become OSV events; odd ranges and withdrawn advisories are nothing", async () => {
316 const { rangeEvents, ghsaToOsv } = await import("../src/security/feeds.ts");
317 expect(rangeEvents("< 1.2.3")?.events).toEqual([{ introduced: "0" }, { fixed: "1.2.3" }]);
318 expect(rangeEvents(">= 1.0.0, <= 1.4.0")?.events).toEqual([{ introduced: "1.0.0" }, { last_affected: "1.4.0" }]);
319 expect(rangeEvents("= 2.0.0")?.versions).toEqual(["2.0.0"]);
320 expect(rangeEvents("~1.2")).toBeUndefined();
321 expect(ghsaToOsv({ ...ghsa, withdrawn_at: "2024-01-01" })).toBeUndefined();
322 expect(ghsaToOsv({ ...ghsa, ghsa_id: "../evil" })).toBeUndefined();
323 expect(toAdvisory(ghsaToOsv(ghsa))?.id).toBe("GHSA-abcd-1234-wxyz");
324 });
325 test("ratings are read from NVD and CVE.org answers, newest CVSS first", async () => {
326 const { ratingOf } = await import("../src/security/feeds.ts");
327 const nvd = { vulnerabilities: [{ cve: { metrics: { cvssMetricV30: [{ cvssData: { baseSeverity: "MEDIUM" } }], cvssMetricV31: [{ cvssData: { baseSeverity: "HIGH" } }] } } }] };
328 expect(ratingOf(nvd)).toBe("HIGH");
329 expect(ratingOf({ containers: { cna: { metrics: [{ cvssV3_1: { baseSeverity: "CRITICAL" } }] } } })).toBe("CRITICAL");
330 expect(ratingOf({ containers: { cna: {} } })).toBeUndefined();
331 });
332 test("a refresh mirrors GHSA, rates from NVD then CVE.org once, and the scan finds it", async () => {
333 const { refreshFeeds } = await import("../src/security/feeds.ts");
334 const dir = await mkdtemp(join(tmpdir(), "forge-feeds-"));
335 const urls: string[] = [];
336 const fake = async (url: string) => {
337 urls.push(url);
338 if (url.includes("api.github.com")) return Response.json([ghsa, { ghsa_id: "nope" }]);
339 if (url.includes("nist.gov")) return Response.json({ vulnerabilities: [] });
340 return Response.json({ containers: { cna: { metrics: [{ cvssV3_1: { baseSeverity: "HIGH" } }] } } });
341 };
342 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 });
344 expect(urls.some((u) => u.includes("affects=lodash%404.17.20"))).toBe(true);
345 const found = scanPinned(pins, loadAdvisories(dir));
346 expect(found[0]).toMatchObject({ advisory: "GHSA-abcd-1234-wxyz", severity: "high", fixedIn: "4.17.21" });
347 urls.length = 0;
348 expect((await refreshFeeds(dir, pins, fake)).rated).toBe(0);
349 expect(urls.some((u) => u.includes("nist.gov") || u.includes("mitre.org"))).toBe(false);
350 await rm(dir, { recursive: true, force: true });
351 });
352 test("a refused host is reported in the gate's words and nothing is written", async () => {
353 const { refreshFeeds } = await import("../src/security/feeds.ts");
354 const dir = await mkdtemp(join(tmpdir(), "forge-feeds-"));
355 const refused = async () => new Response("no", { status: 403, headers: { "x-forge-egress": "refused" } });
356 const out = await refreshFeeds(dir, [{ ecosystem: "npm", name: "a", version: "1.0.0" }], refused);
357 expect(out.written).toBe(0);
358 expect(out.why).toBe("refused by this forge: api.github.com is not in this app's forge.json egress");
359 await rm(dir, { recursive: true, force: true });
360 });
361 test("a rating outside CRITICAL/HIGH/MEDIUM/LOW is nothing", async () => {
362 const { ratingOf } = await import("../src/security/feeds.ts");
363 expect(ratingOf({ containers: { cna: { metrics: [{ cvssV3_1: { baseSeverity: "<script>" } }] } } })).toBeUndefined();
364 expect(ratingOf({ containers: { cna: { metrics: [{ cvssV3_1: { baseSeverity: "x".repeat(5000) } }] } } })).toBeUndefined();
365 });
366 const cveDoc = (n: number) => ({
367 id: `GHSA-aaaa-bbbb-${String(1000 + n)}`, aliases: [`CVE-2024-${String(10000 + n)}`], modified: "2024-01-01T00:00:00Z",
368 database_specific: { severity: "" },
369 affected: [{ package: { ecosystem: "npm", name: `p${String(n)}` }, ranges: [{ type: "SEMVER", events: [{ introduced: "0" }, { fixed: "2.0.0" }] }] }],
370 });
371 test("a pass rates at most 10, asks NVD at most 5 times, and a 429 is a skip, not a failure", async () => {
372 const { refreshFeeds } = await import("../src/security/feeds.ts");
373 const dir = await mkdtemp(join(tmpdir(), "forge-feeds-"));
374 for (let n = 0; n < 12; n++) await writeFile(join(dir, `${cveDoc(n).id}.json`), JSON.stringify(cveDoc(n)));
375 let nvd = 0;
376 const fake = async (url: string) => {
377 if (url.includes("nist.gov")) { nvd++; return Response.json({ vulnerabilities: [] }); }
378 return Response.json({ containers: { cna: { metrics: [{ cvssV3_1: { baseSeverity: "LOW" } }] } } });
379 };
380 const out = await refreshFeeds(dir, [], fake);
381 expect(out.rated).toBe(10);
382 expect(nvd).toBe(5);
383 const limited = async () => new Response("slow down", { status: 429 });
384 const again = await refreshFeeds(dir, [], limited);
385 expect(again).toEqual({ written: 0, rated: 0, failed: 0, why: null });
386 await rm(dir, { recursive: true, force: true });
387 });
388 test("an unscored CVE is asked again after a week, not before", async () => {
389 const { refreshFeeds } = await import("../src/security/feeds.ts");
390 const dir = await mkdtemp(join(tmpdir(), "forge-feeds-"));
391 await writeFile(join(dir, `${cveDoc(1).id}.json`), JSON.stringify(cveDoc(1)));
392 let calls = 0;
393 let score: unknown = { vulnerabilities: [] };
394 const fake = async () => { calls++; return Response.json(score); };
395 const t0 = Date.parse("2026-12-01T00:00:00Z");
396 expect((await refreshFeeds(dir, [], fake, t0)).rated).toBe(0);
397 expect(calls).toBe(2);
398 await refreshFeeds(dir, [], fake, t0 + 6 * 24 * 3600 * 1000);
399 expect(calls).toBe(2);
400 score = { vulnerabilities: [{ cve: { metrics: { cvssMetricV31: [{ cvssData: { baseSeverity: "HIGH" } }] } } }] };
401 expect((await refreshFeeds(dir, [], fake, t0 + 8 * 24 * 3600 * 1000)).rated).toBe(1);
402 await rm(dir, { recursive: true, force: true });
403 });
404 test("a GHSA advisory is rewritten when newer and removed when withdrawn; OSV's own copy is left", async () => {
405 const { refreshFeeds } = await import("../src/security/feeds.ts");
406 const dir = await mkdtemp(join(tmpdir(), "forge-feeds-"));
407 const pins = [{ ecosystem: "npm" as const, name: "lodash", version: "4.17.20" }];
408 let list: unknown[] = [{ ...ghsa, severity: "high", updated_at: "2024-01-01T00:00:00Z" }];
409 const fake = async () => Response.json(list);
410 await refreshFeeds(dir, pins, fake);
411 const file = join(dir, "GHSA-abcd-1234-wxyz.json");
412 list = [{ ...ghsa, severity: "high", updated_at: "2024-02-01T00:00:00Z", vulnerabilities: [{ ...ghsa.vulnerabilities[0], vulnerable_version_range: "< 4.17.30" }] }];
413 expect((await refreshFeeds(dir, pins, fake)).written).toBe(1);
414 expect(await Bun.file(file).text()).toContain("4.17.30");
415 list = [{ ...ghsa, withdrawn_at: "2024-03-01T00:00:00Z" }];
416 await refreshFeeds(dir, pins, fake);
417 expect(await Bun.file(file).exists()).toBe(false);
418 await writeFile(file, JSON.stringify({ id: "GHSA-abcd-1234-wxyz", modified: "2020-01-01T00:00:00Z", database_specific: {} }));
419 await refreshFeeds(dir, pins, fake);
420 expect(await Bun.file(file).exists()).toBe(true);
421 await rm(dir, { recursive: true, force: true });
422 });
423 });

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

Keyboard shortcuts

Docs