diff --git a/docs/security/advisory-early-warning.md b/docs/security/advisory-early-warning.md index 22cb2ff3779..f1cf40b02c5 100644 --- a/docs/security/advisory-early-warning.md +++ b/docs/security/advisory-early-warning.md @@ -40,10 +40,13 @@ shape unchanged. - `scripts/lib/advisory-early-warning.mts` correlates GitHub Security Advisory JSON (repository-level and global records share the shape) with the reviewed npm inventory and emits structured signals: - `{advisoryId, package, vulnerableRange, matchedVersions, source, confidence, action}`. + `{advisoryId, cveId?, package, vulnerableRange, matchedVersions, source, confidence, action}` + (`cveId` is present only when the advisory record carries a well-formed + `cve_id`, and exists solely for the supplementary NVD reconciliation below). - The inventory is derived from `ci/reviewed-npm-audit.json`: every committed archive package spec plus the installed packages of each locked graph's `package-lock.json`. + Pass `--inventory ` to the scan CLI to substitute an explicit `{name, version}` inventory for hermetic offline runs; a malformed entry fails the run instead of silently shrinking the inventory. - Confidence is encoded, never guessed: only an exact npm ecosystem + package-name + parseable semver-range match yields `confidence: "exact"` and `action: "investigate"`. Name collisions from non-npm (CPE-derived) records @@ -77,6 +80,17 @@ owners to define the supported historical-image scope, rescan ownership, alert destination, and response expectations first. A follow-up adds the scheduled workflow once that sign-off is recorded on the issue. +## NVD supplementary reconciliation + +Signals that carry a CVE id can additionally be reconciled against the National Vulnerability Database (`services.nvd.nist.gov/rest/json/cves/2.0`). +NVD is a supplementary source only — #7338 explicitly forbids treating ambiguous NVD/CPE matches as authoritative npm mappings — so a reconciliation is a purely informational annotation that never changes a signal's `action` or `confidence`: + +- `scripts/lib/nvd-reconciliation.mts` parses NVD 2.0 API responses (CVE id, `vulnStatus`, published/last-modified dates, and the CPE criteria flagged vulnerable) and annotates each signal with one of three agreement states: `corroborated` (NVD lists the same CVE id and has not rejected it), `nvd-missing` (no NVD record — typical while a CVE is reserved or awaiting NVD processing; the earlier upstream signal stands on its own), or `nvd-divergent` (NVD rejected the CVE id, or the record answers a different one). + CPE criteria surface only as a count in the note, never as package matches. +- Pass `--nvd-records ` to `scripts/advisory-early-warning-scan.mts` to attach reconciliations from a file of previously fetched NVD responses; the CLI itself never performs network requests. + +Querying NVD on a schedule and annotating the alert destination belong to the scheduled workflow, which follows the same #7338 sign-off gate as the rest of the scheduled operation. + ## Provenance recorded per audit Each reviewed npm audit report now has a `*.provenance.json` sidecar @@ -99,3 +113,36 @@ the WeChat locked runtime graph audit) recording: Comparing the `advisoryIds` of consecutive retained runs identifies the last comparable non-detection and the first detection of a newly surfaced advisory, even when an unrelated finding failed the earlier run. + +## #7276 post-mortem: detection triggers + +Issue #7338 asks two questions of the #7276 evidence. +The answers below rest strictly on that retained evidence and inherit its limits: the evidence does not support one universal feed-delay root cause, and a finding the evidence cannot prove is classified unproven rather than attributed. + +### Q1 — what trigger caused `npm audit` to begin detecting when it did + +Per #7338's acceptance criteria, each finding is classified as reviewed-mapping delay, audit/rescan coverage, or unproven due to missing evidence. + +- `fast-uri` (CVE-2026-13676, GHSA-4c8g-83qw-93j6) — **reviewed-mapping delay, directly demonstrated.** + The upstream repository advisory existed from June 29, yet the 18:46 UTC `npm audit` on July 21 did not report `fast-uri@3.1.2`. + The global reviewed ecosystem record propagated at 19:03 UTC, and the 20:09 UTC audit of the same vulnerable version returned GHSA-4c8g-83qw-93j6 as High: strong before/after evidence that reviewed package-mapping propagation triggered detection. +- `@opentelemetry/core` (CVE-2026-54285, GHSA-8988-4f7v-96qf) — **audit/rescan coverage gap.** + Its reviewed record had existed since June 15, more than a month before detection, so delayed reviewed-feed publication cannot explain it. + It first surfaced when the July 21 build reached the plugin audit — an audit-coverage/execution-order gap. +- Jaeger propagator (CVE-2026-59892, GHSA-45rx-2jwx-cxfr) — **consistent with reviewed-mapping delay, but unproven.** + The reviewed record appeared at 19:07 UTC on July 21 and the first plugin audit that reached this graph reported the finding at 20:26 UTC — consistent with reviewed mapping propagation, but earlier builds stopped before this plugin audit, so there is no controlled pre-review comparison. +- `tar` (CVE-2026-59873, GHSA-23hp-3jrh-7fpw) — **unproven due to missing evidence.** + The June 27 upstream disclosure-to-detection gap is real (a July 21 Trivy scan reported vulnerable `tar@7.5.11` and `7.5.15`; the reviewed record dates to July 20), but no comparable pre-review scan was retained, so the exact trigger is unproven. + +### Q2 — the ideal trigger, and what covers each gap now + +The ideal trigger is the earliest public upstream disclosure, evaluated against the exact dependency inventory on a schedule that does not depend on how far any one build progressed. +Mapping each demonstrated gap to a mechanism: + +- Reviewed-mapping delay (`fast-uri`; plausibly the Jaeger propagator): covered by the correlation path above — it fetches unreviewed (NVD-sourced, pre-curation) advisory records alongside reviewed and malware ones, so a disclosure naming an inventory package raises a signal before the reviewed mapping exists, with NVD reconciliation as supplementary corroboration. + Running it every six hours is the scheduled workflow, gated on the #7338 sign-off. + Not yet shipped — polling upstream *repository* advisories directly (the earliest public signal) needs a package-to-repository map and remains the planned extension. +- Audit/rescan coverage gap (`@opentelemetry/core`; what limited the Jaeger conclusion): covered by the scheduled scan correlating every advisory type against the full reviewed inventory every six hours, independent of build execution order — same #7338 sign-off gate. + Not yet shipped — rescanning maintained immutable image digests (an image-scan pipeline) waits on the supported-image scope that product/security owners must define (#7338's policy criterion). +- Unproven trigger (`tar`): no trigger design recovers missing evidence. + Shipped — every reviewed npm audit now writes a provenance sidecar (endpoints, timestamps, advisory ids), so consecutive retained runs establish the last comparable non-detection and first detection for any future finding. diff --git a/scripts/advisory-early-warning-scan.mts b/scripts/advisory-early-warning-scan.mts index b91b9bfebc1..27109f7b098 100755 --- a/scripts/advisory-early-warning-scan.mts +++ b/scripts/advisory-early-warning-scan.mts @@ -9,19 +9,30 @@ // fail the process: enforcement stays with the reviewed npm audit gate. // // Usage: -// advisory-early-warning-scan.mts --list-packages -// advisory-early-warning-scan.mts --advisories [--output ] +// advisory-early-warning-scan.mts [--inventory ] --list-packages +// advisory-early-warning-scan.mts [--inventory ] +// --advisories +// [--nvd-records ] [--output ] +// +// --inventory replaces the repo-derived reviewed inventory with an explicit +// JSON array of {name, version[, origin]} entries, so offline callers and +// tests can run hermetically; without it (the workflow default) the inventory +// is built from ci/reviewed-npm-audit.json and the locked-graph package-locks. +// +// --nvd-records attaches supplementary NVD reconciliations from a file of +// previously fetched NVD 2.0 API responses. The CLI itself never performs +// network requests; the caller (the early-warning workflow) fetches. import fs from "node:fs"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { - type AdvisorySignal, correlateAdvisories, type InventoryEntry, parseInventoryFromAuditConfig, parseInventoryFromPackageLock, } from "./lib/advisory-early-warning.mts"; +import { attachNvdReconciliations, type NvdAnnotatedSignal } from "./lib/nvd-reconciliation.mts"; const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const CONFIG_RELATIVE_PATH = path.join("ci", "reviewed-npm-audit.json"); @@ -49,8 +60,53 @@ function loadAdvisories(advisoriesPath: string): unknown[] { return Array.isArray(parsed) ? parsed : [parsed]; } -function describeSignal(signal: AdvisorySignal): string { - return `${signal.advisoryId} ${signal.package} ${signal.vulnerableRange || "(no range)"} -> ${signal.action} (${signal.confidence}, matched ${signal.matchedVersions.join(", ")})`; +function loadNvdResponses(nvdRecordsPath: string): unknown[] { + const parsed = JSON.parse(fs.readFileSync(nvdRecordsPath, "utf-8")) as unknown; + return Array.isArray(parsed) ? parsed : [parsed]; +} + +function loadInventoryOverride(inventoryPath: string): InventoryEntry[] { + const parsed = JSON.parse(fs.readFileSync(inventoryPath, "utf-8")) as unknown; + if (!Array.isArray(parsed)) { + throw new Error(`--inventory file '${inventoryPath}' must contain a JSON array.`); + } + // A malformed entry fails the run instead of being skipped: silently + // shrinking the inventory would under-report advisories with no signal + // that anything was dropped. + return parsed.map((entry, index) => { + if (typeof entry !== "object" || entry === null) { + throw new Error(`--inventory entry ${index} in '${inventoryPath}' is not an object.`); + } + const name = (entry as Record).name; + const version = (entry as Record).version; + if (typeof name !== "string" || name.length === 0) { + throw new Error( + `--inventory entry ${index} in '${inventoryPath}' is missing a non-empty string "name".`, + ); + } + if (typeof version !== "string" || version.length === 0) { + throw new Error( + `--inventory entry ${index} in '${inventoryPath}' is missing a non-empty string "version".`, + ); + } + const origin = (entry as Record).origin; + return { + name, + version, + origin: typeof origin === "string" && origin.length > 0 ? origin : inventoryPath, + }; + }); +} + +function describeNvd(signal: NvdAnnotatedSignal): string { + if (!signal.nvd) return ""; + const published = + signal.nvd.nvdPublished === null ? "" : ` (published ${signal.nvd.nvdPublished.slice(0, 10)})`; + return ` — NVD: ${signal.nvd.agreement}${published}`; +} + +function describeSignal(signal: NvdAnnotatedSignal): string { + return `${signal.advisoryId} ${signal.package} ${signal.vulnerableRange || "(no range)"} -> ${signal.action} (${signal.confidence}, matched ${signal.matchedVersions.join(", ")})${describeNvd(signal)}`; } function readFlagValue(argv: readonly string[], flag: string): string | undefined { @@ -64,7 +120,8 @@ function readFlagValue(argv: readonly string[], flag: string): string | undefine } function main(argv: readonly string[]): void { - const inventory = loadReviewedInventory(); + const inventoryPath = readFlagValue(argv, "--inventory"); + const inventory = inventoryPath ? loadInventoryOverride(inventoryPath) : loadReviewedInventory(); if (argv.includes("--list-packages")) { const names = [...new Set(inventory.map((entry) => entry.name))].sort(); for (const name of names) console.log(name); @@ -73,11 +130,17 @@ function main(argv: readonly string[]): void { const advisoriesPath = readFlagValue(argv, "--advisories"); if (!advisoriesPath) { throw new Error( - "usage: advisory-early-warning-scan.mts --list-packages | --advisories [--output ]", + "usage: advisory-early-warning-scan.mts [--inventory ] --list-packages | [--inventory ] --advisories [--nvd-records ] [--output ]", ); } const advisories = loadAdvisories(advisoriesPath); - const signals = correlateAdvisories(advisories, inventory); + const correlated = correlateAdvisories(advisories, inventory); + const nvdRecordsPath = readFlagValue(argv, "--nvd-records"); + // NVD reconciliation is offline here by design: responses come from a file + // the caller fetched, and annotations are informational only. + const signals: readonly NvdAnnotatedSignal[] = nvdRecordsPath + ? attachNvdReconciliations(correlated, loadNvdResponses(nvdRecordsPath)) + : correlated; const outputPath = readFlagValue(argv, "--output"); if (outputPath) { fs.writeFileSync(outputPath, `${JSON.stringify(signals, null, 2)}\n`); diff --git a/scripts/lib/advisory-early-warning.mts b/scripts/lib/advisory-early-warning.mts index bd27064c246..fc554284af1 100644 --- a/scripts/lib/advisory-early-warning.mts +++ b/scripts/lib/advisory-early-warning.mts @@ -9,11 +9,19 @@ // gate: only exact npm package-name plus semver-range matches are marked // "investigate", and ambiguous CPE-to-npm matches stay "informational". +import { deriveCveId } from "./nvd-reconciliation.mts"; + export type AdvisoryConfidence = "exact" | "ambiguous"; export type AdvisoryAction = "investigate" | "informational"; export type AdvisorySignal = Readonly<{ advisoryId: string; + /** + * CVE id from the advisory record's `cve_id` field, present only when + * well-formed. Used solely for supplementary NVD reconciliation + * (scripts/lib/nvd-reconciliation.mts); it never affects correlation. + */ + cveId?: string; package: string; vulnerableRange: string; matchedVersions: readonly string[]; @@ -222,6 +230,7 @@ type SignalEvidence = { type SignalDraft = { advisoryId: string; + cveId?: string; package: string; exact: SignalEvidence; ambiguous: SignalEvidence; @@ -263,6 +272,7 @@ export function correlateAdvisories( for (const input of advisories) { const advisory = parseAdvisory(input); if (!advisory) continue; + const cveId = deriveCveId(input) ?? undefined; for (const vulnerability of advisory.vulnerabilities) { const versions = versionsByName.get(vulnerability.packageName); if (!versions || versions.size === 0) continue; @@ -295,6 +305,10 @@ export function correlateAdvisories( exact: { ranges: [], versions: new Set() }, ambiguous: { ranges: [], versions: new Set() }, }; + // Duplicate records for one advisory may disagree on carrying a CVE id + // (e.g. repository-level vs global fetch); the first record with a + // well-formed cve_id wins. + draft.cveId ??= cveId; addEvidence( confidence === "exact" ? draft.exact : draft.ambiguous, vulnerability.vulnerableRange, @@ -309,6 +323,7 @@ export function correlateAdvisories( const evidence = confidence === "exact" ? draft.exact : draft.ambiguous; return { advisoryId: draft.advisoryId, + ...(draft.cveId === undefined ? {} : { cveId: draft.cveId }), package: draft.package, vulnerableRange: evidence.ranges.join("; "), matchedVersions: [...evidence.versions].sort(), diff --git a/scripts/lib/nvd-reconciliation.mts b/scripts/lib/nvd-reconciliation.mts new file mode 100644 index 00000000000..3c87bb013b0 --- /dev/null +++ b/scripts/lib/nvd-reconciliation.mts @@ -0,0 +1,195 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// Supplementary NVD reconciliation for advisory early-warning signals (#7338). +// NVD is never an authoritative npm mapping: a reconciliation only records +// whether NVD independently corroborates a signal's CVE id, and CPE +// applicability criteria are surfaced for awareness, never turned into npm +// package matches. Reconciliations are purely informational annotations — they +// never change a signal's action or confidence, and enforcement stays with the +// reviewed npm audit gate. + +import type { AdvisorySignal } from "./advisory-early-warning.mts"; + +export type NvdAgreement = "corroborated" | "nvd-missing" | "nvd-divergent"; + +export type NvdRecord = Readonly<{ + cveId: string; + vulnStatus: string; + published: string; + lastModified: string; + cpeCriteria: readonly string[]; +}>; + +export type NvdReconciliation = Readonly<{ + cveId: string; + nvdStatus: string | null; + nvdPublished: string | null; + agreement: NvdAgreement; + note: string; +}>; + +export type NvdAnnotatedSignal = AdvisorySignal & Readonly<{ nvd?: NvdReconciliation }>; + +const CVE_ID_PATTERN = /^CVE-\d{4}-\d{4,}$/; + +/** + * Derive the CVE id to reconcile from a GHSA advisory record: both the global + * `/advisories` and repository-level security-advisory responses carry a + * `cve_id` field (null until a CVE is assigned). Anything that is not a + * well-formed CVE id yields null, so only pattern-validated ids ever reach an + * NVD query. + */ +export function deriveCveId(input: unknown): string | null { + if (typeof input !== "object" || input === null || Array.isArray(input)) return null; + const cveId = (input as Record).cve_id; + if (typeof cveId !== "string" || !CVE_ID_PATTERN.test(cveId)) return null; + return cveId; +} + +function collectVulnerableCpeCriteria(cve: Record): string[] { + const criteria: string[] = []; + const configurations = Array.isArray(cve.configurations) ? cve.configurations : []; + for (const configuration of configurations) { + if (typeof configuration !== "object" || configuration === null) continue; + const nodes = (configuration as Record).nodes; + if (!Array.isArray(nodes)) continue; + const pendingNodes = [...nodes]; + const seenNodes = new Set(); + for (let index = 0; index < pendingNodes.length; index += 1) { + const node = pendingNodes[index]; + if (typeof node !== "object" || node === null) continue; + if (seenNodes.has(node)) continue; + seenNodes.add(node); + const nodeRecord = node as Record; + const childNodes = nodeRecord.nodes; + if (Array.isArray(childNodes)) pendingNodes.push(...childNodes); + const matches = nodeRecord.cpeMatch; + if (Array.isArray(matches)) { + for (const match of matches) { + if (typeof match !== "object" || match === null) continue; + const entry = match as Record; + // Only cpeMatch entries flagged vulnerable name the vulnerable + // product; the rest are platform context ("running on/with"). + if (entry.vulnerable !== true) continue; + const criterion = entry.criteria; + if (typeof criterion !== "string" || criterion.length === 0) continue; + if (!criteria.includes(criterion)) criteria.push(criterion); + } + } + } + } + return criteria; +} + +/** + * Extract the reconciliation-relevant fields from one NVD 2.0 API response + * (GET services.nvd.nist.gov/rest/json/cves/2.0?cveId=...). A cveId query + * answers with at most one vulnerability; the first entry with a well-formed + * CVE id is used. The well-formed empty response NVD serves for reserved or + * unknown CVE ids — and any malformed input — yields null instead of throwing, + * so one bad record cannot break a scan. + */ +export function parseNvdRecord(input: unknown): NvdRecord | null { + if (typeof input !== "object" || input === null || Array.isArray(input)) return null; + const vulnerabilities = (input as Record).vulnerabilities; + if (!Array.isArray(vulnerabilities)) return null; + for (const entry of vulnerabilities) { + if (typeof entry !== "object" || entry === null) continue; + const cve = (entry as Record).cve; + if (typeof cve !== "object" || cve === null || Array.isArray(cve)) continue; + const record = cve as Record; + const cveId = record.id; + if (typeof cveId !== "string" || !CVE_ID_PATTERN.test(cveId)) continue; + return { + cveId, + vulnStatus: typeof record.vulnStatus === "string" ? record.vulnStatus : "", + published: typeof record.published === "string" ? record.published : "", + lastModified: typeof record.lastModified === "string" ? record.lastModified : "", + cpeCriteria: collectVulnerableCpeCriteria(record), + }; + } + return null; +} + +/** + * Reconcile one signal with the NVD record fetched for its CVE id. The result + * is a purely informational annotation: + * + * - "corroborated": NVD lists the same CVE id and has not rejected it; + * - "nvd-missing": no NVD record (typical while a CVE is reserved at MITRE or + * awaiting NVD processing — the earlier upstream signal stands on its own); + * - "nvd-divergent": NVD rejected the CVE id, or the record answers a + * different one. + * + * A reconciliation never changes the signal's action or confidence, and a + * signal without a CVE id has nothing to reconcile (null). + */ +export function reconcileSignalWithNvd( + signal: AdvisorySignal, + nvdRecord: NvdRecord | null, +): NvdReconciliation | null { + const cveId = signal.cveId; + if (cveId === undefined) return null; + if (nvdRecord === null) { + return { + cveId, + nvdStatus: null, + nvdPublished: null, + agreement: "nvd-missing", + note: `NVD has no record for ${cveId} — typical while a CVE is reserved or awaiting NVD processing; the upstream advisory signal stands on its own.`, + }; + } + const nvdStatus = nvdRecord.vulnStatus.length > 0 ? nvdRecord.vulnStatus : null; + const nvdPublished = nvdRecord.published.length > 0 ? nvdRecord.published : null; + if (nvdRecord.cveId !== cveId) { + return { + cveId, + nvdStatus, + nvdPublished, + agreement: "nvd-divergent", + note: `NVD record ${nvdRecord.cveId} does not answer the advisory's ${cveId}; treat the NVD data as unrelated and keep the signal as-is.`, + }; + } + if (nvdRecord.vulnStatus.toLowerCase() === "rejected") { + return { + cveId, + nvdStatus, + nvdPublished, + agreement: "nvd-divergent", + note: `NVD rejected ${cveId} while the GHSA advisory is still published; investigate the divergence instead of dropping the signal.`, + }; + } + return { + cveId, + nvdStatus, + nvdPublished, + agreement: "corroborated", + note: `NVD independently lists ${cveId} (status ${nvdStatus ?? "unknown"}); ${nvdRecord.cpeCriteria.length} vulnerable CPE criteria on file — a CPE match is never an authoritative npm mapping.`, + }; +} + +/** + * Attach NVD reconciliations to correlated signals. Purely additive: base + * signal fields are copied unchanged, signals without a CVE id pass through + * unannotated, and a CVE id no fetched response answers reconciles as + * "nvd-missing" (which also covers the empty response NVD serves for reserved + * ids, since that response parses to null and registers no record). When + * responses duplicate a CVE id the first parseable one wins. + */ +export function attachNvdReconciliations( + signals: readonly AdvisorySignal[], + nvdResponses: readonly unknown[], +): NvdAnnotatedSignal[] { + const recordsByCveId = new Map(); + for (const response of nvdResponses) { + const record = parseNvdRecord(response); + if (record === null) continue; + if (!recordsByCveId.has(record.cveId)) recordsByCveId.set(record.cveId, record); + } + return signals.map((signal) => { + const record = signal.cveId === undefined ? null : (recordsByCveId.get(signal.cveId) ?? null); + const reconciliation = reconcileSignalWithNvd(signal, record); + return reconciliation === null ? { ...signal } : { ...signal, nvd: reconciliation }; + }); +} diff --git a/test/advisory-early-warning.test.ts b/test/advisory-early-warning.test.ts index 2bd74b0b9ae..0b01b31146f 100644 --- a/test/advisory-early-warning.test.ts +++ b/test/advisory-early-warning.test.ts @@ -72,6 +72,7 @@ describe("advisory early warning correlation", () => { expect(signals).toEqual([ { advisoryId: "GHSA-4c8g-83qw-93j6", + cveId: "CVE-2026-13676", package: "fast-uri", vulnerableRange: ">= 3.0.0, < 3.1.3", matchedVersions: ["3.1.2"], @@ -87,6 +88,7 @@ describe("advisory early warning correlation", () => { expect(signals).toEqual([ { advisoryId: "GHSA-45rx-2jwx-cxfr", + cveId: "CVE-2026-59892", package: "fast-uri", vulnerableRange: "cpe:2.3:a:fastify:fast-uri:*:*", matchedVersions: ["3.1.2"], diff --git a/test/nvd-reconciliation.test.ts b/test/nvd-reconciliation.test.ts new file mode 100644 index 00000000000..89ff851142c --- /dev/null +++ b/test/nvd-reconciliation.test.ts @@ -0,0 +1,597 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import { correlateAdvisories } from "../scripts/lib/advisory-early-warning.mts"; +import { + attachNvdReconciliations, + deriveCveId, + type NvdRecord, + parseNvdRecord, + reconcileSignalWithNvd, +} from "../scripts/lib/nvd-reconciliation.mts"; + +// NVD 2.0 API response (GET services.nvd.nist.gov/rest/json/cves/2.0?cveId=...) +// modeled on the fast-uri advisory from the #7276 evidence table: analyzed by +// NVD with CPE applicability criteria. NVD timestamps carry no timezone +// designator. Only the cpeMatch entry flagged vulnerable names the vulnerable +// product; the second entry is platform context and must not be collected. +const analyzedFastUriResponse = { + resultsPerPage: 1, + startIndex: 0, + totalResults: 1, + format: "NVD_CVE", + version: "2.0", + timestamp: "2026-07-22T09:15:04.113", + vulnerabilities: [ + { + cve: { + id: "CVE-2026-13676", + sourceIdentifier: "security-advisories@github.com", + published: "2026-06-29T16:15:09.230", + lastModified: "2026-07-08T14:02:33.410", + vulnStatus: "Analyzed", + descriptions: [ + { lang: "en", value: "fast-uri URI parsing divergence enables authority spoofing." }, + ], + metrics: { + cvssMetricV31: [ + { + source: "nvd@nist.gov", + type: "Primary", + cvssData: { version: "3.1", baseScore: 7.5, baseSeverity: "HIGH" }, + }, + ], + }, + weaknesses: [ + { + source: "nvd@nist.gov", + type: "Primary", + description: [{ lang: "en", value: "CWE-436" }], + }, + ], + configurations: [ + { + nodes: [ + { + operator: "OR", + negate: false, + cpeMatch: [ + { + vulnerable: true, + criteria: "cpe:2.3:a:fastify:fast-uri:*:*:*:*:*:node.js:*:*", + versionStartIncluding: "3.0.0", + versionEndExcluding: "3.1.3", + matchCriteriaId: "5C7E71C1-3D3B-4B7E-9DF9-32AA1F6A38D1", + }, + { + vulnerable: false, + criteria: "cpe:2.3:a:nodejs:node.js:-:*:*:*:*:*:*:*", + matchCriteriaId: "9A1B49B7-77C2-4A0E-8A2B-2D0E0A5B6F44", + }, + ], + }, + ], + }, + ], + references: [ + { + url: "https://github.com/fastify/fast-uri/security/advisories/GHSA-4c8g-83qw-93j6", + source: "security-advisories@github.com", + }, + ], + }, + }, + ], +} as const; + +// Synthetic rejected record: NVD keeps serving withdrawn CVE ids with +// vulnStatus "Rejected" instead of removing them. +const rejectedCveResponse = { + resultsPerPage: 1, + startIndex: 0, + totalResults: 1, + format: "NVD_CVE", + version: "2.0", + timestamp: "2026-07-22T09:15:04.113", + vulnerabilities: [ + { + cve: { + id: "CVE-2026-20340", + sourceIdentifier: "cve@mitre.org", + published: "2026-06-27T21:15:11.870", + lastModified: "2026-07-19T08:30:00.000", + vulnStatus: "Rejected", + descriptions: [{ lang: "en", value: "Rejected reason: withdrawn by its CNA." }], + references: [], + }, + }, + ], +} as const; + +// The well-formed empty response NVD serves for a CVE id that is still +// RESERVED at MITRE (or unknown): zero results, no vulnerabilities. +const reservedCveResponse = { + resultsPerPage: 0, + startIndex: 0, + totalResults: 0, + format: "NVD_CVE", + version: "2.0", + timestamp: "2026-07-22T09:15:04.113", + vulnerabilities: [], +} as const; + +const testInventory = [ + { + name: "fast-uri", + version: "3.1.2", + origin: "agents/openclaw/mcporter-runtime/package-lock.json", + }, +] as const; + +const upstreamFastUriAdvisory = { + ghsa_id: "GHSA-4c8g-83qw-93j6", + cve_id: "CVE-2026-13676", + vulnerabilities: [ + { + package: { ecosystem: "npm", name: "fast-uri" }, + vulnerable_version_range: ">= 3.0.0, < 3.1.3", + }, + ], +} as const; + +const expectedFastUriSignal = { + advisoryId: "GHSA-4c8g-83qw-93j6", + cveId: "CVE-2026-13676", + package: "fast-uri", + vulnerableRange: ">= 3.0.0, < 3.1.3", + matchedVersions: ["3.1.2"], + source: "upstream-ghsa", + confidence: "exact", + action: "investigate", +} as const; + +const signalWithoutCveId = { + advisoryId: "GHSA-23hp-3jrh-7fpw", + package: "tar", + vulnerableRange: "< 7.6.0", + matchedVersions: ["7.5.20"], + source: "upstream-ghsa", + confidence: "exact", + action: "investigate", +} as const; + +function parsedRecord(response: unknown): NvdRecord { + const record = parseNvdRecord(response); + expect(record).not.toBeNull(); + return record as NvdRecord; +} + +describe("NVD 2.0 record parsing", () => { + it("parses an analyzed NVD record including only vulnerable CPE criteria", () => { + expect(parseNvdRecord(analyzedFastUriResponse)).toEqual({ + cveId: "CVE-2026-13676", + vulnStatus: "Analyzed", + published: "2026-06-29T16:15:09.230", + lastModified: "2026-07-08T14:02:33.410", + cpeCriteria: ["cpe:2.3:a:fastify:fast-uri:*:*:*:*:*:node.js:*:*"], + }); + }); + + it("parses a rejected NVD record with its Rejected status", () => { + expect(parseNvdRecord(rejectedCveResponse)).toEqual({ + cveId: "CVE-2026-20340", + vulnStatus: "Rejected", + published: "2026-06-27T21:15:11.870", + lastModified: "2026-07-19T08:30:00.000", + cpeCriteria: [], + }); + }); + + it("returns null for the empty response NVD serves for reserved CVE ids", () => { + expect(parseNvdRecord(reservedCveResponse)).toBeNull(); + }); + + it.each([ + ["null", null], + ["a number", 42], + ["an array", []], + ["an empty object", {}], + ["a non-array vulnerabilities field", { vulnerabilities: 7 }], + ["a vulnerability entry without a cve object", { vulnerabilities: [{}] }], + ["a cve object without an id", { vulnerabilities: [{ cve: { vulnStatus: "Analyzed" } }] }], + [ + "a cve id that is not a CVE id", + { vulnerabilities: [{ cve: { id: "GHSA-4c8g-83qw-93j6" } }] }, + ], + ["a numeric cve id", { vulnerabilities: [{ cve: { id: 202613676 } }] }], + ])("returns null without throwing for malformed input: %s", (_label, input) => { + expect(() => parseNvdRecord(input)).not.toThrow(); + expect(parseNvdRecord(input)).toBeNull(); + }); + + it("skips malformed leading entries and parses the first valid vulnerability", () => { + const response = { + vulnerabilities: [{}, { cve: { id: "CVE-2026-13676" } }], + }; + expect(parseNvdRecord(response)).toEqual({ + cveId: "CVE-2026-13676", + vulnStatus: "", + published: "", + lastModified: "", + cpeCriteria: [], + }); + }); + + it("deduplicates repeated CPE criteria across configurations", () => { + const criteria = "cpe:2.3:a:fastify:fast-uri:*:*:*:*:*:node.js:*:*"; + const response = { + vulnerabilities: [ + { + cve: { + id: "CVE-2026-13676", + configurations: [ + { nodes: [{ cpeMatch: [{ vulnerable: true, criteria }] }] }, + { + nodes: [ + { + cpeMatch: [ + { vulnerable: true, criteria }, + { vulnerable: true, criteria: "cpe:2.3:a:isaacs:node-tar:*:*:*:*:*:*:*:*" }, + ], + }, + ], + }, + ], + }, + }, + ], + }; + expect(parsedRecord(response).cpeCriteria).toEqual([ + criteria, + "cpe:2.3:a:isaacs:node-tar:*:*:*:*:*:*:*:*", + ]); + }); + + it("collects vulnerable CPE criteria from nested configuration nodes", () => { + const vulnerableCriterion = "cpe:2.3:a:fastify:fast-uri:*:*:*:*:*:node.js:*:*"; + const contextCriterion = "cpe:2.3:a:nodejs:node.js:-:*:*:*:*:*:*:*"; + const response = { + vulnerabilities: [ + { + cve: { + id: "CVE-2026-13676", + configurations: [ + { + nodes: [ + { + nodes: [ + { + cpeMatch: [ + { vulnerable: true, criteria: vulnerableCriterion }, + { vulnerable: false, criteria: contextCriterion }, + ], + }, + ], + }, + ], + }, + ], + }, + }, + ], + }; + + expect(parsedRecord(response).cpeCriteria).toEqual([vulnerableCriterion]); + }); +}); + +describe("CVE id derivation from GHSA advisory records", () => { + it("derives the CVE id from an advisory record's cve_id field", () => { + expect(deriveCveId(upstreamFastUriAdvisory)).toBe("CVE-2026-13676"); + }); + + it.each([ + ["null", null], + ["a non-object", "CVE-2026-13676"], + ["an array", [{ cve_id: "CVE-2026-13676" }]], + ["a record without cve_id", { ghsa_id: "GHSA-4c8g-83qw-93j6" }], + ["a null cve_id (GitHub serves null before CVE assignment)", { cve_id: null }], + ["a numeric cve_id", { cve_id: 202613676 }], + ["a malformed cve_id", { cve_id: "CVE-26-13676" }], + ["a GHSA id in the cve_id field", { cve_id: "GHSA-4c8g-83qw-93j6" }], + ])("derives no CVE id from %s", (_label, input) => { + expect(deriveCveId(input)).toBeNull(); + }); +}); + +describe("signal reconciliation with NVD", () => { + it("corroborates a signal whose CVE id NVD lists as live", () => { + const reconciliation = reconcileSignalWithNvd( + expectedFastUriSignal, + parsedRecord(analyzedFastUriResponse), + ); + expect(reconciliation).toEqual({ + cveId: "CVE-2026-13676", + nvdStatus: "Analyzed", + nvdPublished: "2026-06-29T16:15:09.230", + agreement: "corroborated", + note: expect.stringMatching(/never an authoritative npm mapping/), + }); + }); + + it("reports nvd-missing when NVD has no record for the CVE id", () => { + expect(reconcileSignalWithNvd(expectedFastUriSignal, null)).toEqual({ + cveId: "CVE-2026-13676", + nvdStatus: null, + nvdPublished: null, + agreement: "nvd-missing", + note: expect.stringMatching(/reserved/), + }); + }); + + it("reports nvd-divergent when NVD rejected the CVE id", () => { + const signal = { ...signalWithoutCveId, cveId: "CVE-2026-20340" } as const; + const reconciliation = reconcileSignalWithNvd(signal, parsedRecord(rejectedCveResponse)); + expect(reconciliation).toMatchObject({ + cveId: "CVE-2026-20340", + nvdStatus: "Rejected", + nvdPublished: "2026-06-27T21:15:11.870", + agreement: "nvd-divergent", + }); + expect(reconciliation?.note).toMatch(/rejected/i); + }); + + it("reports nvd-divergent when the NVD record answers a different CVE id", () => { + const reconciliation = reconcileSignalWithNvd( + expectedFastUriSignal, + parsedRecord(rejectedCveResponse), + ); + expect(reconciliation).toMatchObject({ + cveId: "CVE-2026-13676", + agreement: "nvd-divergent", + }); + expect(reconciliation?.note).toContain("CVE-2026-20340"); + expect(reconciliation?.note).toContain("CVE-2026-13676"); + }); + + it("reconciles nothing for a signal without a CVE id", () => { + expect( + reconcileSignalWithNvd(signalWithoutCveId, parsedRecord(analyzedFastUriResponse)), + ).toBeNull(); + expect(reconcileSignalWithNvd(signalWithoutCveId, null)).toBeNull(); + }); + + it("never mutates the signal and never carries action or confidence", () => { + const signal = structuredClone(expectedFastUriSignal); + const reconciliation = reconcileSignalWithNvd(signal, parsedRecord(analyzedFastUriResponse)); + expect(signal).toEqual(expectedFastUriSignal); + expect(reconciliation).not.toHaveProperty("action"); + expect(reconciliation).not.toHaveProperty("confidence"); + }); +}); + +describe("cveId plumbing through advisory correlation", () => { + it("carries the advisory's cve_id onto the emitted signal", () => { + expect(correlateAdvisories([upstreamFastUriAdvisory], testInventory)).toEqual([ + expectedFastUriSignal, + ]); + }); + + it("omits cveId when the advisory has none", () => { + const advisory = { + ghsa_id: upstreamFastUriAdvisory.ghsa_id, + vulnerabilities: upstreamFastUriAdvisory.vulnerabilities, + }; + const signals = correlateAdvisories([advisory], testInventory); + expect(signals).toHaveLength(1); + expect(signals[0]).not.toHaveProperty("cveId"); + }); + + it("omits cveId when the advisory's cve_id is malformed", () => { + const advisory = { ...upstreamFastUriAdvisory, cve_id: "not-a-cve-id" }; + const signals = correlateAdvisories([advisory], testInventory); + expect(signals).toHaveLength(1); + expect(signals[0]).not.toHaveProperty("cveId"); + }); + + it("keeps the CVE id when a duplicate record without one merges into the signal", () => { + const advisoryWithoutCve = { + ghsa_id: upstreamFastUriAdvisory.ghsa_id, + vulnerabilities: upstreamFastUriAdvisory.vulnerabilities, + }; + expect( + correlateAdvisories([advisoryWithoutCve, upstreamFastUriAdvisory], testInventory), + ).toEqual([expectedFastUriSignal]); + }); +}); + +describe("attaching NVD reconciliations to signals", () => { + it("annotates a correlated signal with a corroborating NVD record", () => { + const signals = correlateAdvisories([upstreamFastUriAdvisory], testInventory); + const annotated = attachNvdReconciliations(signals, [analyzedFastUriResponse]); + expect(annotated).toEqual([ + { + ...expectedFastUriSignal, + nvd: { + cveId: "CVE-2026-13676", + nvdStatus: "Analyzed", + nvdPublished: "2026-06-29T16:15:09.230", + agreement: "corroborated", + note: expect.stringMatching(/never an authoritative npm mapping/), + }, + }, + ]); + }); + + it("annotates nvd-missing when no fetched record answers the signal's CVE id", () => { + const annotated = attachNvdReconciliations([expectedFastUriSignal], []); + expect(annotated[0]?.nvd).toMatchObject({ + cveId: "CVE-2026-13676", + agreement: "nvd-missing", + }); + }); + + it("annotates nvd-missing when NVD served the empty reserved-id response", () => { + const annotated = attachNvdReconciliations([expectedFastUriSignal], [reservedCveResponse]); + expect(annotated[0]?.nvd).toMatchObject({ agreement: "nvd-missing" }); + }); + + it("passes signals without a CVE id through unannotated", () => { + const annotated = attachNvdReconciliations([signalWithoutCveId], [analyzedFastUriResponse]); + expect(annotated).toEqual([signalWithoutCveId]); + expect(annotated[0]).not.toHaveProperty("nvd"); + }); + + it("keeps the first parseable response when duplicates answer one CVE id", () => { + const laterRejected = JSON.parse(JSON.stringify(analyzedFastUriResponse)) as { + vulnerabilities: { cve: { vulnStatus: string } }[]; + }; + laterRejected.vulnerabilities[0].cve.vulnStatus = "Rejected"; + const annotated = attachNvdReconciliations( + [expectedFastUriSignal], + [analyzedFastUriResponse, laterRejected], + ); + expect(annotated[0]?.nvd).toMatchObject({ agreement: "corroborated", nvdStatus: "Analyzed" }); + }); + + it("skips malformed NVD responses without throwing", () => { + const malformed = [null, 42, {}, { vulnerabilities: 7 }]; + expect(() => attachNvdReconciliations([expectedFastUriSignal], malformed)).not.toThrow(); + expect(attachNvdReconciliations([expectedFastUriSignal], malformed)[0]?.nvd).toMatchObject({ + agreement: "nvd-missing", + }); + }); + + it("does not mutate the input signals", () => { + const signals = structuredClone([expectedFastUriSignal, signalWithoutCveId]); + attachNvdReconciliations(signals, [analyzedFastUriResponse]); + expect(signals).toEqual([expectedFastUriSignal, signalWithoutCveId]); + }); +}); + +describe("advisory early-warning CLI --nvd-records", () => { + const SCAN_CLI = path.join( + import.meta.dirname, + "..", + "scripts", + "advisory-early-warning-scan.mts", + ); + // A synthetic package that exists only in the test's --inventory file keeps + // the CLI run hermetic: no expectation derives from the repo's committed + // reviewed inventory. + const cliInventory = [{ name: "nemoclaw-fixture-package", version: "3.1.2" }]; + const cliAdvisory = { + ghsa_id: "GHSA-4c8g-83qw-93j6", + cve_id: "CVE-2026-13676", + vulnerabilities: [ + { + package: { ecosystem: "npm", name: "nemoclaw-fixture-package" }, + vulnerable_version_range: ">= 3.0.0, < 3.1.3", + }, + ], + }; + const expectedCliSignal = { + advisoryId: "GHSA-4c8g-83qw-93j6", + cveId: "CVE-2026-13676", + package: "nemoclaw-fixture-package", + vulnerableRange: ">= 3.0.0, < 3.1.3", + matchedVersions: ["3.1.2"], + source: "upstream-ghsa", + confidence: "exact", + action: "investigate", + }; + + function runScanCli(args: readonly string[]): string { + return execFileSync(process.execPath, ["--experimental-strip-types", SCAN_CLI, ...args], { + encoding: "utf-8", + }); + } + + it("attaches reconciliations offline from --nvd-records without any network access", () => { + const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-nvd-reconciliation-")); + try { + const inventoryPath = path.join(tempRoot, "inventory.json"); + const advisoriesPath = path.join(tempRoot, "advisories.json"); + const nvdRecordsPath = path.join(tempRoot, "nvd-records.json"); + const outputPath = path.join(tempRoot, "signals.json"); + fs.writeFileSync(inventoryPath, JSON.stringify(cliInventory)); + fs.writeFileSync(advisoriesPath, JSON.stringify([cliAdvisory])); + fs.writeFileSync(nvdRecordsPath, JSON.stringify([analyzedFastUriResponse])); + const stdout = runScanCli([ + "--inventory", + inventoryPath, + "--advisories", + advisoriesPath, + "--nvd-records", + nvdRecordsPath, + "--output", + outputPath, + ]); + const signals = JSON.parse(fs.readFileSync(outputPath, "utf-8")) as Record[]; + expect(signals).toEqual([ + { + ...expectedCliSignal, + nvd: { + cveId: "CVE-2026-13676", + nvdStatus: "Analyzed", + nvdPublished: "2026-06-29T16:15:09.230", + agreement: "corroborated", + note: expect.stringMatching(/never an authoritative npm mapping/), + }, + }, + ]); + expect(stdout).toContain("NVD: corroborated (published 2026-06-29)"); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } + }); + + it("fails loudly on a malformed --inventory entry instead of shrinking the inventory", () => { + const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-nvd-reconciliation-")); + try { + const inventoryPath = path.join(tempRoot, "inventory.json"); + fs.writeFileSync( + inventoryPath, + JSON.stringify([ + { name: "fast-uri", version: "3.1.2" }, + { name: "", version: "1.0.0" }, + ]), + ); + expect(() => runScanCli(["--inventory", inventoryPath, "--list-packages"])).toThrow( + /entry 1 .* missing a non-empty string "name"/, + ); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } + }); + + it("emits unannotated signals when --nvd-records is not given", () => { + const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-nvd-reconciliation-")); + try { + const inventoryPath = path.join(tempRoot, "inventory.json"); + const advisoriesPath = path.join(tempRoot, "advisories.json"); + const outputPath = path.join(tempRoot, "signals.json"); + fs.writeFileSync(inventoryPath, JSON.stringify(cliInventory)); + fs.writeFileSync(advisoriesPath, JSON.stringify([cliAdvisory])); + const stdout = runScanCli([ + "--inventory", + inventoryPath, + "--advisories", + advisoriesPath, + "--output", + outputPath, + ]); + const signals = JSON.parse(fs.readFileSync(outputPath, "utf-8")) as Record[]; + expect(signals).toEqual([expectedCliSignal]); + expect(signals[0]).not.toHaveProperty("nvd"); + expect(stdout).not.toContain("NVD:"); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } + }); +});