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

Advisory integrations: notify on a new exploited advisory #17326

opened this

Merged 40h 30m ago, live in production

scout/forge:scout/17144-advisory-integrations-notify-on-a-new-ex → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/17144-advisory-integrations-notify-on-a-new-ex was merged into main as 31c05ee.

Review

Sign in to review this change.
7 files changed +133 −5
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. **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.
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%". **Exploited (#17144).** The same refresh reads CISA's known-exploited catalogue (`www.cisa.gov`, in `egress`, one request a pass, only while a mirrored advisory has a CVE id) and stamps a matching advisory once. A finding carries `exploited: true`, the terminal row reads "high, exploited, EPSS 4.30%", and the hourly duty files one issue per exploited advisory and pin, ahead of the bumps and under the same per-pass cap of 3 ("Exploited: GHSA-… in lodash 4.17.20 (CISA KEV)"), in the same opted-in repositories; the issue is the notice. Not built: a 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, `R` 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
@@ -23,7 +23,8 @@
2323 "api.osv.dev",
2424 "services.nvd.nist.gov",
2525 "cveawg.mitre.org",
26 "api.first.org"
26 "api.first.org",
27 "www.cisa.gov"
2728 ],
2829 "schedules": [
2930 { "name": "heartbeat", "cron": "5 7 * * *", "timezone": "UTC", "path": "/jobs/heartbeat", "timeout": 120, "retries": 3, "catchUp": "6h" }
src/security/feeds.ts +36
@@ -23,6 +23,8 @@ const NVD_HOST = "services.nvd.nist.gov";
2323 const CVE_HOST = "cveawg.mitre.org";
2424 const EPSS_HOST = "api.first.org";
2525 const EPSS_PATH = ["data", "v1", "epss"].join("/");
26 const KEV_HOST = "www.cisa.gov";
27 const KEV_PATH = ["sites", "default", "files", "feeds", "known_exploited_vulnerabilities.json"].join("/");
2628
2729 interface FeedRefresh {
2830 readonly written: number;
@@ -156,6 +158,18 @@ export function epssOf(doc: unknown): Map<string, number> {
156158 return out;
157159 }
158160
161 /**
162 * The CVE ids in a CISA KEV catalogue answer (`vulnerabilities: [{ cveID }]`); anything else is
163 * left out.
164 */
165 export function kevOf(doc: unknown): Set<string> {
166 const out = new Set<string>();
167 if (!isRecord(doc) || !Array.isArray(doc.vulnerabilities)) return out;
168 for (const row of doc.vulnerabilities.slice(0, 20000))
169 if (isRecord(row) && typeof row.cveID === "string" && CVE_ID.test(row.cveID)) out.add(row.cveID);
170 return out;
171 }
172
159173 function writeWhole(file: string, doc: unknown): void {
160174 writeFileSync(`${file}.tmp`, JSON.stringify(doc));
161175 renameSync(`${file}.tmp`, file);
@@ -329,5 +343,27 @@ export async function refreshFeeds(dir: string, pins: readonly Pinned[], fetcher
329343 break;
330344 }
331345 }
346 // CISA KEV: a mirrored advisory whose CVE is on the catalogue of exploited vulnerabilities is
347 // stamped once (`forge_kev`); `fix_issues.ts` files the notice. One request a pass, and none
348 // while no mirrored advisory has a CVE id.
349 const unflagged = names.flatMap((name) => {
350 const file = join(dir, name);
351 const doc = readDoc(file);
352 const cve = doc && cveOf(doc);
353 const specific = doc && isRecord(doc.database_specific) ? doc.database_specific : {};
354 return doc && cve && specific.forge_kev === undefined ? [{ file, doc, cve, specific }] : [];
355 });
356 if (unflagged.length > 0) {
357 try {
358 const res = await fetcher(`https://${KEV_HOST}/${KEV_PATH}`);
359 if (!limited(res)) {
360 const kev = kevOf(await answerOf(res, KEV_HOST));
361 for (const { file, doc, cve, specific } of unflagged)

Every advisory not on the catalogue stays unflagged, so this fetches the whole file every pass forever. Stamp a checked-at on the advisories you asked about, or send If-Modified-Since.

362 if (kev.has(cve)) writeWhole(file, { ...doc, database_specific: { ...specific, forge_kev: { at: new Date(now).toISOString() } } });
363 }
364 } catch (error) {
365 fail(error, KEV_HOST);
366 }
367 }
332368 return { written, rated, scored, failed, why };
333369 }
src/security/fix_issues.ts +18 −1
@@ -14,7 +14,7 @@ import { getRepo } from "../core/repos.ts";
1414 import { getUserById } from "../core/users.ts";
1515 import { repoDir } from "../git/repos.ts";
1616 import { planFixes, type Bump } from "./fix.ts";
17 import { loadAdvisories, type Advisory } from "./osv.ts";
17 import { loadAdvisories, type Advisory, type Finding } from "./osv.ts";
1818 import { optedIn } from "./optin.ts";
1919 import { scanRepo } from "./scan.ts";
2020
@@ -34,6 +34,15 @@ export function fixBody(b: Bump): string {
3434 ].join("\n\n");
3535 }
3636
37 const exploitedTitle = (f: Finding): string => `Exploited: ${f.advisory} in ${f.package} ${f.version} (CISA KEV)`;
38
39 function exploitedBody(f: Finding): string {
40 return [
41 `${f.advisory} is on CISA's catalogue of known exploited vulnerabilities, and \`${f.package}\` ${f.version} is pinned here.`,
42 f.fixedIn === null ? "No fixed version is published yet: remove or replace the package, or say why it cannot be reached." : `Upgrade it to ${f.fixedIn} now.`,
43 ].join("\n\n");

Link the advisory (https://osv.dev/<id>) in this body so the issue is actionable from a phone.

44 }
45
3746 /** One repository: file the bumps not already open as issues; returns how many were filed. */
3847 export async function fileFixIssues(
3948 app: Pick<App, "db" | "reposRoot">,
@@ -52,6 +61,14 @@ export async function fileFixIssues(
5261 if (!repo || !actor) return 0;
5362 const report = await scanRepo(repoDir(app.reposRoot, row.owner, row.name), row.branch, advisories);
5463 let filed = 0;
64 // A pin hit by an exploited advisory is told first, before any bump, once per advisory and pin.
65 for (const f of report.findings) {
66 if (!f.exploited || filed >= PER_PASS) continue;
67 const title = exploitedTitle(f);
68 const seen = listIssues(app.db, repo.id, { state: "all", kind: "issue", query: title, limit: 20 });
69 if (seen.some((i) => i.title === title)) continue;
70 if (openIssue(app as App, actor, repo, { title, body: exploitedBody(f) }).ok) filed++;
71 }
5572 for (const bump of planFixes(report.findings)) {
5673 if (filed >= PER_PASS) break;
5774 const title = fixTitle(bump);
src/security/osv.ts +6
@@ -19,6 +19,8 @@ export interface Advisory {
1919 * (#17142).
2020 */
2121 readonly epss?: number;
22 /** On CISA's catalogue of known exploited vulnerabilities (#17144). */
23 readonly exploited?: true;
2224 readonly affected: readonly {
2325 readonly package: { readonly ecosystem: string; readonly name: string };
2426 readonly ranges?: readonly {
@@ -35,6 +37,8 @@ export interface Finding {
3537 readonly severity: Severity;
3638 /** The advisory's EPSS probability (0..1), when FIRST has one. */
3739 readonly epss?: number;
40 /** Known to be exploited (CISA KEV). */
41 readonly exploited?: true;
3842 readonly package: string;
3943 readonly version: string;
4044 /** The smallest version that fixes it, when the advisory names one. */
@@ -141,6 +145,7 @@ export function toAdvisory(doc: unknown): Advisory | undefined {
141145 summary: typeof doc.summary === "string" ? doc.summary.slice(0, MAX_SUMMARY) : "",
142146 severity: severityOf(specific?.severity),
143147 ...(typeof epss === "number" && epss >= 0 && epss <= 1 ? { epss } : {}),
148 ...(isRecord(specific?.forge_kev) ? { exploited: true as const } : {}),
144149 affected,
145150 };
146151 }
@@ -221,6 +226,7 @@ export function affectedBy(pkg: Pinned, advisories: readonly Advisory[]): Findin
221226 summary: adv.summary,
222227 severity: adv.severity,
223228 ...(adv.epss === undefined ? {} : { epss: adv.epss }),
229 ...(adv.exploited ? { exploited: true as const } : {}),
224230 package: pkg.name,
225231 version: pkg.version,
226232 fixedIn,
src/tui/screens/dependencies.ts +1 −1
@@ -23,7 +23,7 @@ import { ListState, drawList, type ListRow } from "./common.ts";
2323 export function findingRows(report: Report): ListRow[] {
2424 return report.findings.map((f) => ({
2525 title: `${f.package} ${f.version}: ${f.advisory}`,
26 secondary: f.epss === undefined ? f.severity : `${f.severity}, EPSS ${(f.epss * 100).toFixed(f.epss < 0.1 ? 2 : 1)}%`,
26 secondary: [f.severity, ...(f.exploited ? ["exploited"] : []), ...(f.epss === undefined ? [] : [`EPSS ${(f.epss * 100).toFixed(f.epss < 0.1 ? 2 : 1)}%`])].join(", "),
2727 meta: f.fixedIn ? `fix ${f.fixedIn}` : "no fix named",
2828 ...(f.summary ? { note: f.summary } : {}),
2929 }));
test/security-osv.test.ts +69 −1
@@ -219,6 +219,74 @@ describe("fix issues", () => {
219219 });
220220 });
221221
222 describe("exploited advisories (#17144)", () => {
223 test("KEV answers are read bounded; a stamped advisory is an exploited finding", async () => {
224 const { kevOf } = await import("../src/security/feeds.ts");
225 expect([...kevOf({ vulnerabilities: [{ cveID: "CVE-2024-12345" }, { cveID: "../x" }, { nope: 1 }] })]).toEqual(["CVE-2024-12345"]);
226 expect(kevOf("junk").size).toBe(0);
227 const doc = { id: "X-1", affected: [{ package: { ecosystem: "npm", name: "a" }, versions: ["1.0.0"] }] };
228 const pin = [{ ecosystem: "npm" as const, name: "a", version: "1.0.0" }];
229 expect(scanPinned(pin, [toAdvisory(doc)!])[0]?.exploited).toBeUndefined();
230 const flagged = toAdvisory({ ...doc, database_specific: { forge_kev: { at: "2026-01-01T00:00:00Z" } } })!;
231 expect(scanPinned(pin, [flagged])[0]?.exploited).toBe(true);
232 });
233 test("a refresh stamps the CVE once, asks CISA once a pass, and the duty files one notice per pin", async () => {
234 const { refreshFeeds } = await import("../src/security/feeds.ts");
235 const dataDir = await mkdtemp(join(tmpdir(), "forge-kev-"));
236 const dir = join(dataDir, "osv");
237 let asked = 0;
238 const fake = async (url: string) => {
239 if (url.includes("cisa.gov")) {
240 asked++;
241 return Response.json({ vulnerabilities: [{ cveID: "CVE-2024-12345" }] });
242 }
243 if (url.includes("api.github.com"))
244 return Response.json([{ ghsa_id: "GHSA-abcd-1234-wxyz", cve_id: "CVE-2024-12345", summary: "p", severity: "high", withdrawn_at: null, vulnerabilities: [{ package: { ecosystem: "npm", name: "lodash" }, vulnerable_version_range: "< 4.17.21" }] }]);
245 return Response.json({ data: [] });
246 };
247 const pins = [{ ecosystem: "npm" as const, name: "lodash", version: "4.17.20" }];
248 await refreshFeeds(dir, [], fake);
249 expect(asked).toBe(0);
250 await refreshFeeds(dir, pins, fake);
251 expect(asked).toBe(1);
252 expect(scanPinned(pins, loadAdvisories(dir))[0]?.exploited).toBe(true);
253 await refreshFeeds(dir, pins, fake);
254 expect(asked).toBe(1);
255 const app = createApp({ dataDir, port: 0 });
256 const servers = await serve(app);
257 try {
258 await seedAdmin(app, { username: "mira", email: "[email protected]", password: "osv-pass-1234" });
259 const token = await fetch(`${servers.url}/api/v1/tokens`, {
260 method: "POST",
261 headers: { "content-type": "application/json" },
262 body: JSON.stringify({ adminConfirm: true, username: "mira", password: "osv-pass-1234", name: "t", scope: "rw" }),
263 })
264 .then((r) => r.json())
265 .then((j) => (j as { token: string }).token);
266 const h = { authorization: `Bearer ${token}`, "content-type": "application/json" };
267 await fetch(`${servers.url}/api/v1/repos`, { method: "POST", headers: h, body: JSON.stringify({ name: "app", visibility: "public" }) });
268 await fetch(`${servers.url}/api/v1/repos/mira/app/contents`, {
269 method: "POST",
270 headers: h,
271 body: JSON.stringify({ message: "lock", files: [{ path: "bun.lock", content: `{"packages":{"l":["[email protected]","",{}],}}` }] }),
272 });
273 app.configs.set(FORGE_SCOPE, { "osv.repos": ["mira/app"] }, "test", "opt in");
274 expect(await fileAllFixIssues(app)).toBe(2);
275 expect(await fileAllFixIssues(app)).toBe(0);
276 const titles = listIssues(app.db, getRepo(app.db, "mira", "app")!.id, { state: "open", kind: "issue" }).map((i) => i.title);
277 expect(titles).toContain("Exploited: GHSA-abcd-1234-wxyz in lodash 4.17.20 (CISA KEV)");
278 } finally {
279 servers.stop();
280 app.close();
281 await rm(dataDir, { recursive: true, force: true });
282 }
283 });
284 test("the terminal row says exploited", () => {
285 const row = findingRows({ ref: "main", lockfiles: [], packages: 1, fixes: [], findings: [{ advisory: "X-1", summary: "", severity: "high", exploited: true, package: "a", version: "1.0.0", fixedIn: null }] })[0];
286 expect(row?.secondary).toBe("high, exploited");
287 });
288 });
289
222290 describe("mirror refresh", () => {
223291 test("writes new advisories, skips current ones, refuses odd ids and non-advisories", async () => {
224292 const { refreshMirror } = await import("../src/security/mirror.ts");
@@ -416,7 +484,7 @@ describe("GHSA, NVD and CVE.org feeds (#17141)", () => {
416484 await writeFile(join(dir, `${cveDoc(1).id}.json`), JSON.stringify(cveDoc(1)));
417485 let calls = 0;
418486 let score: unknown = { vulnerabilities: [] };
419 const fake = async (url: string) => { if (!url.includes("first.org")) calls++; return Response.json(score); };
487 const fake = async (url: string) => { if (!url.includes("first.org") && !url.includes("cisa.gov")) calls++; return Response.json(score); };
420488 const t0 = Date.parse("2026-12-01T00:00:00Z");
421489 expect((await refreshFeeds(dir, [], fake, t0)).rated).toBe(0);
422490 expect(calls).toBe(2);

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

Keyboard shortcuts

Docs