From 79d66256c3da7d3a051414c77eb43fe6c22f5350 Mon Sep 17 00:00:00 2001 From: Dongni-Yang Date: Wed, 22 Jul 2026 11:32:05 +0800 Subject: [PATCH 1/8] feat(security): advisory early-warning scan and audit provenance records Public advisories can affect maintained packages weeks before they reach the reviewed corpus that npm audit enforces (#7276 timeline). Add an early-warning path and per-audit provenance so those windows become visible and provable from retained artifacts: - scripts/lib/advisory-early-warning.mts: dependency-free correlation of GitHub Security Advisory records (reviewed, unreviewed, and malware) against the reviewed-graph package inventories; exact npm name and parseable-range matches produce investigate signals, ambiguous or CPE-style matches stay informational and never block. - .github/workflows/advisory-early-warning.yaml: six-hourly paginated scan of all three advisory types, correlated against the inventory, reporting into one rolling security-labeled issue (marker- and author-verified, deduplicated by advisory id plus package). - scripts/audit-reviewed-npm-graph.mts and the wechat runtime audit action now write a *.provenance.json sidecar next to each raw report: scanner and npm/node versions, configured registry and derived bulk advisory endpoint, run start/end times, extracted advisory ids, and a failure marker whenever the audit attempt itself failed - including npm's parseable-error-JSON failure mode - so a failed attempt can never be mistaken for a comparable non-detection. - docs/security/advisory-early-warning.md: how the path works plus proposed defaults (scope, ownership, alert destination, SLA) pending maintainer confirmation. Refs #7338 Signed-off-by: Dongni-Yang Co-Authored-By: Claude Fable 5 --- .../actions/ci-wechat-runtime-audit/audit.sh | 97 +++++ .github/workflows/advisory-early-warning.yaml | 167 +++++++++ docs/security/advisory-early-warning.md | 101 ++++++ scripts/advisory-early-warning-scan.mts | 106 ++++++ scripts/audit-reviewed-npm-graph.mts | 172 ++++++++- scripts/lib/advisory-early-warning.mts | 325 +++++++++++++++++ test/advisory-early-warning.test.ts | 332 ++++++++++++++++++ test/reviewed-npm-audit.test.ts | 172 +++++++++ 8 files changed, 1470 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/advisory-early-warning.yaml create mode 100644 docs/security/advisory-early-warning.md create mode 100755 scripts/advisory-early-warning-scan.mts create mode 100644 scripts/lib/advisory-early-warning.mts create mode 100644 test/advisory-early-warning.test.ts diff --git a/.github/actions/ci-wechat-runtime-audit/audit.sh b/.github/actions/ci-wechat-runtime-audit/audit.sh index db2fe4ad814..1ec8554d7ed 100755 --- a/.github/actions/ci-wechat-runtime-audit/audit.sh +++ b/.github/actions/ci-wechat-runtime-audit/audit.sh @@ -138,12 +138,109 @@ for package_spec in "$wechat_spec" "qrcode-terminal@0.12.0" "zod@4.4.3"; do done audit_status=0 +audit_started_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)" npm --prefix "$runtime_dir" audit \ --userconfig "$trusted_npmrc" \ --registry "$npm_registry" \ --omit=dev \ --audit-level=low \ --json >"$report_dir/npm-audit.json" || audit_status=$? +audit_finished_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)" + +# Record scanner/database provenance next to the raw report so a later reader +# can establish exactly which registry endpoint served this audit (#7338). +# Mirrors the *.provenance.json sidecars scripts/audit-reviewed-npm-graph.mts +# writes for the reviewed graphs. Keep the endpoint derivation and GHSA id +# extraction below in sync with deriveAuditEndpoints/extractAdvisoryIds in +# that script; a shared implementation would need a Node module boundary this +# shell action does not have. +REPORT_PATH="$report_dir/npm-audit.json" \ + PROVENANCE_PATH="$report_dir/npm-audit.provenance.json" \ + CONFIGURED_REGISTRY="$npm_registry" \ + PACKAGE_SPEC="$wechat_spec" \ + STARTED_AT="$audit_started_at" \ + FINISHED_AT="$audit_finished_at" \ + AUDIT_STATUS="$audit_status" \ + NPM_VERSION="$(npm --version)" \ + node <<'NODE' +const fs = require("node:fs"); +let report = {}; +let failure; +try { + report = JSON.parse(fs.readFileSync(process.env.REPORT_PATH, "utf8")); +} catch { + // A transport failure can leave a non-JSON report; the audit status check + // below still fails the run, and the sidecar records the attempt. + failure = "npm audit did not produce a parseable JSON report"; +} +if (typeof report !== "object" || report === null || Array.isArray(report)) { + // JSON.parse also accepts null, arrays, and bare strings, which real npm + // never emits; normalize so the checks below cannot crash and the sidecar + // still records the attempt as failed. + report = {}; + if (failure === undefined) { + failure = "npm audit did not produce a JSON object report"; + } +} +// npm's dominant failure mode writes PARSEABLE error JSON (`{"error": ...}`) +// and exits nonzero; mirror parseAuditReport in +// scripts/audit-reviewed-npm-graph.mts so such a run is never mistaken for a +// clean scan: report.error, exit status above 1, or a nonzero exit with zero +// findings all mark the attempt as failed. +const auditStatus = Number(process.env.AUDIT_STATUS); +let findingCount = 0; +const severityCounts = report?.metadata?.vulnerabilities; +if (severityCounts && typeof severityCounts === "object" && !Array.isArray(severityCounts)) { + for (const count of Object.values(severityCounts)) { + if (typeof count === "number" && Number.isSafeInteger(count) && count >= 0) { + findingCount += count; + } + } +} +if ( + failure === undefined && + (report.error !== undefined || + !Number.isSafeInteger(auditStatus) || + auditStatus > 1 || + (auditStatus !== 0 && findingCount === 0)) +) { + const detail = report.error === undefined ? "" : `: ${JSON.stringify(report.error)}`; + failure = `npm audit exited ${process.env.AUDIT_STATUS} without a complete vulnerability finding report${detail}`; +} +const advisoryIds = new Set(); +const findings = report && typeof report.vulnerabilities === "object" ? report.vulnerabilities : {}; +for (const finding of Object.values(findings ?? {})) { + const via = Array.isArray(finding?.via) ? finding.via : []; + for (const cause of via) { + const url = typeof cause === "object" && cause !== null ? cause.url : undefined; + if (typeof url !== "string") continue; + for (const match of url.match(/GHSA(?:-[23456789cfghjmpqrvwx]{4}){3}/gi) ?? []) { + advisoryIds.add(`GHSA${match.slice(4).toLowerCase()}`); + } + } +} +const registryBase = process.env.CONFIGURED_REGISTRY.replace(/\/+$/, ""); +const provenance = { + schemaVersion: 1, + scanner: { + name: "npm audit", + npmVersion: process.env.NPM_VERSION, + nodeVersion: process.version, + }, + registry: { + configuredRegistry: process.env.CONFIGURED_REGISTRY, + bulkAdvisoryEndpoint: `${registryBase}/-/npm/v1/security/advisories/bulk`, + note: "npm audit posts the dependency graph to the bulk advisory endpoint of the configured registry; on request failure npm reports no advisory data.", + }, + run: { startedAt: process.env.STARTED_AT, finishedAt: process.env.FINISHED_AT }, + graph: { label: "WeChat locked runtime graph", packageSpecs: [process.env.PACKAGE_SPEC] }, + // rawReportPath is relative to the directory containing the sidecar. + rawReportPath: "npm-audit.json", + advisoryIds: [...advisoryIds].sort(), + ...(failure === undefined ? {} : { failure }), +}; +fs.writeFileSync(process.env.PROVENANCE_PATH, `${JSON.stringify(provenance, null, 2)}\n`); +NODE signature_status=0 npm --prefix "$runtime_dir" audit signatures \ diff --git a/.github/workflows/advisory-early-warning.yaml b/.github/workflows/advisory-early-warning.yaml new file mode 100644 index 00000000000..9bd17df7218 --- /dev/null +++ b/.github/workflows/advisory-early-warning.yaml @@ -0,0 +1,167 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Advisory early warning (#7338): every six hours, fetch public GitHub Security +# Advisories that name packages in the reviewed npm inventory and correlate them +# with scripts/advisory-early-warning-scan.mts. All three advisory types are +# fetched: "reviewed" records (the corpus npm audit already enforces, so a +# match means enforcement is imminent or active), "unreviewed" records +# (NVD-sourced, often published before curation reaches the reviewed feed — +# these commonly lack a verified npm mapping and flow through the module's +# ambiguous, informational-only path), and "malware" records (npm malware +# advisories naming an inventory package). Matches surface as a rolling, +# security-labeled tracking issue — a traceable, NON-blocking investigation +# signal. Enforcement stays with the reviewed npm audit gate; this workflow +# never fails a build or mutates a release. + +name: Security / Advisory Early Warning + +on: + schedule: + - cron: "41 */6 * * *" + workflow_dispatch: + +permissions: + contents: read + issues: write + +concurrency: + group: advisory-early-warning + cancel-in-progress: false + +jobs: + early-warning: + if: github.repository == 'NVIDIA/NemoClaw' + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Checkout + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + persist-credentials: false + + - name: Setup production-compatible Node.js + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6 + with: + node-version: "22.22.2" + + - name: Fetch advisories naming reviewed inventory packages + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + node --experimental-strip-types scripts/advisory-early-warning-scan.mts \ + --list-packages >"$RUNNER_TEMP/inventory-packages.txt" + batches=() + batch="" + batch_count=0 + while IFS= read -r package_name; do + [ -n "$package_name" ] || continue + if [ -z "$batch" ]; then + batch="$package_name" + else + batch="$batch,$package_name" + fi + batch_count=$((batch_count + 1)) + if [ "$batch_count" -ge 25 ]; then + batches+=("$batch") + batch="" + batch_count=0 + fi + done <"$RUNNER_TEMP/inventory-packages.txt" + [ -z "$batch" ] || batches+=("$batch") + : >"$RUNNER_TEMP/advisory-records.jsonl" + for advisory_type in reviewed unreviewed malware; do + for batch in "${batches[@]}"; do + gh api -X GET /advisories \ + -f "type=$advisory_type" \ + -f ecosystem=npm \ + -f "affects=$batch" \ + -f per_page=100 \ + --paginate \ + --jq '.[]' >>"$RUNNER_TEMP/advisory-records.jsonl" + done + done + jq -s 'unique_by(.ghsa_id)' "$RUNNER_TEMP/advisory-records.jsonl" \ + >"$RUNNER_TEMP/advisories.json" + echo "Fetched $(jq 'length' "$RUNNER_TEMP/advisories.json") advisory records" + + - name: Correlate advisories with the reviewed inventory + run: | + set -euo pipefail + node --experimental-strip-types scripts/advisory-early-warning-scan.mts \ + --advisories "$RUNNER_TEMP/advisories.json" \ + --output "$RUNNER_TEMP/signals.json" + + - name: Create or update the rolling early-warning issue + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + run: | + set -euo pipefail + signals="$RUNNER_TEMP/signals.json" + count="$(jq 'length' "$signals")" + if [ "$count" -eq 0 ]; then + echo "No early-warning signals; nothing to report." + exit 0 + fi + title="Advisory early warning: reviewed npm inventory signals" + marker="" + body_file="$RUNNER_TEMP/issue-body.md" + # One line per advisoryId+package signal. Column 1 is the dedupe key + # (" ") and is embedded verbatim in the line, + # always followed by a space (the range column falls back to + # "(no range)"), so existing bodies are checked with a fixed-string + # grep for " " — a prefix-sibling package (tar vs tar-stream) + # can never falsely dedupe. Advisory free text is sanitized so it + # cannot split lines or corrupt the TSV. + jq -r '.[] | + (.advisoryId + " " + (.package | gsub("[\\r\\n\\t]"; " "))) as $key | + [$key, + "- [ ] " + $key + " " + + (if .vulnerableRange == "" then "(no range)" + else (.vulnerableRange | gsub("[\\r\\n\\t]"; " ")) end) + + " [" + .action + ", " + .confidence + ", matched " + + (.matchedVersions | join(" ")) + "] (source: " + .source + ")"] | + @tsv' "$signals" >"$RUNNER_TEMP/signal-lines.tsv" + # Only trust a rolling issue this workflow created itself: it must be + # authored by the Actions bot AND carry the embedded marker. A + # lookalike security-labeled issue must not become the sink (it could + # pre-seed dedupe keys to suppress real signals). + existing="$(gh issue list --repo "$REPO" --label security --state open \ + --author "app/github-actions" \ + --search "\"$title\" in:title" \ + --json number,body | + jq --arg marker "$marker" '[.[] | select(.body | contains($marker))][0] // empty')" + if [ -z "$existing" ]; then + { + echo "$marker" + echo "" + echo "Automated, non-blocking early-warning signals: public GitHub Security" + echo "Advisories that plausibly affect the reviewed npm inventory before or" + echo "beyond what the reviewed npm audit gate currently enforces (#7338)." + echo "Ambiguous matches are informational only and must not block a release." + echo "" + cut -f2 "$RUNNER_TEMP/signal-lines.tsv" + } >"$body_file" + gh issue create --repo "$REPO" --label security --title "$title" \ + --body-file "$body_file" + echo "Created rolling early-warning issue" + exit 0 + fi + issue_number="$(jq -r '.number' <<<"$existing")" + jq -r '.body' <<<"$existing" >"$body_file" + appended=0 + while IFS=$'\t' read -r dedupe_key line; do + [ -n "$dedupe_key" ] || continue + if ! grep -qF "$dedupe_key " "$body_file"; then + printf '%s\n' "$line" >>"$body_file" + appended=1 + fi + done <"$RUNNER_TEMP/signal-lines.tsv" + if [ "$appended" -eq 1 ]; then + gh issue edit "$issue_number" --repo "$REPO" --body-file "$body_file" + echo "Updated rolling early-warning issue #$issue_number" + else + echo "Rolling early-warning issue #$issue_number already lists every signal." + fi diff --git a/docs/security/advisory-early-warning.md b/docs/security/advisory-early-warning.md new file mode 100644 index 00000000000..5bb55f45824 --- /dev/null +++ b/docs/security/advisory-early-warning.md @@ -0,0 +1,101 @@ +# Advisory Early Warning and Audit Provenance + +Status: implemented mechanism, proposed policy (issue #7338; evidence from #7276) + +Public upstream GitHub Security Advisories are often published weeks before the +global reviewed ecosystem record that `npm audit` enforces. For +`fast-uri` (GHSA-4c8g-83qw-93j6) the upstream repository advisory appeared on +June 29 while the reviewed record propagated on July 21, so the same vulnerable +version audited clean at 18:46 UTC and reported High at 20:09 UTC. This page +documents the early-warning path that narrows that gap and the provenance every +audit now records so such timelines are provable from retained artifacts. + +The scheduled scan draws on all three types of the global advisory database, which +contribute differently: + +- reviewed records are the corpus `npm audit` enforces — a match here means + package-level enforcement is imminent or already active, and the signal + confirms the reviewed gate will catch it; +- unreviewed records are NVD-sourced and often appear before curation reaches + the reviewed feed — they usually lack a verified npm mapping, so they flow + through the ambiguous, informational-only path and provide the earlier + heads-up; +- malware records name npm packages published as malware — a match against the + reviewed inventory correlates like any other record and is equally + non-blocking. + +Polling upstream *repository* advisories directly (the earliest public signal, +e.g. `fastify/fast-uri`'s own advisory) needs a package-to-repository map and +is the planned extension; the correlation module already accepts that record +shape unchanged. + +## How the early-warning path works + +- `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}`. +- 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`. +- 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 + and unparseable ranges yield `confidence: "ambiguous"` and + `action: "informational"`. Ambiguous matches never block or mutate a release. +- `.github/workflows/advisory-early-warning.yaml` runs every six hours (and on + manual dispatch): it fetches reviewed, unreviewed, and malware advisories + naming inventory packages (paginated, batched by package), runs + `scripts/advisory-early-warning-scan.mts`, and routes signals into one + rolling GitHub issue labeled `security`, deduplicated by advisory id plus + package. Only an OPEN issue authored by the Actions bot that carries the + workflow's embedded marker is reused; otherwise a fresh issue is created. + Closing the rolling issue while its signals still apply therefore makes the + next run open a fresh issue re-listing them (the dedupe state lives in the + open issue body), so close it only once the listed advisories are resolved + for the inventory. The workflow is non-blocking by design and never fails a + build. +- The reviewed npm audit gate (`scripts/audit-reviewed-npm-graph.mts`, enforced + in CI) remains enabled and authoritative for exact npm package/version-range + decisions. The early-warning path only triggers investigation and rescanning. + +## Provenance recorded per audit + +Each reviewed npm audit report now has a `*.provenance.json` sidecar +(`coverage/reviewed-npm-audit/` artifacts, and `npm-audit.provenance.json` for +the WeChat locked runtime graph audit) recording: + +- scanner identity: `npm audit`, npm version, Node.js version; +- the configured registry plus the derived bulk advisory endpoint npm posts + the dependency graph to (npm >= 7 has no quick-audit fallback: on request + failure npm reports no advisory data, and the note records this); +- run start and finish timestamps (ISO 8601); +- the audited graph label and committed package specs; +- the raw machine-readable report path (`rawReportPath`, by convention + relative to the directory containing the sidecar); +- the GHSA advisory ids extracted from the report; and +- a `failure` marker when the audit attempt itself failed, so the sidecar + still records the attempt. + +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. + +## Proposed policy defaults (pending maintainer confirmation) + +The following defaults answer #7338's open policy questions. They are +proposals only and take effect when product/security owners confirm them. + +- Scope: the reviewed graphs committed in `ci/reviewed-npm-audit.json` + (archive packages and locked graphs). Historical immutable image digests are + out of scope until owners define a supported-image list. +- Rescan ownership: repository maintainers, driven by the rolling + `security`-labeled early-warning issue; the six-hour schedule is the default + rescan trigger for advisory-database changes. +- Alert destination: the rolling GitHub issue created by the early-warning + workflow (one issue, deduplicated by advisory id plus package). +- Response expectation for `action: "investigate"` signals: acknowledge + Critical within 1 business day and resolve or escalate within 3; acknowledge + High within 2 business days and resolve or escalate within 5. While a + reviewed mapping is unavailable, unresolved High/Critical signals escalate to + a maintainer decision rather than automatically blocking a release. diff --git a/scripts/advisory-early-warning-scan.mts b/scripts/advisory-early-warning-scan.mts new file mode 100755 index 00000000000..b91b9bfebc1 --- /dev/null +++ b/scripts/advisory-early-warning-scan.mts @@ -0,0 +1,106 @@ +#!/usr/bin/env -S node --experimental-strip-types +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// CLI entry for the advisory early-warning path (#7338). Correlates public +// GitHub Security Advisory JSON with the reviewed npm inventory derived from +// ci/reviewed-npm-audit.json (committed package specs plus the locked-graph +// package-locks) and prints structured, NON-blocking signals. Signals never +// 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 ] + +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"; + +const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const CONFIG_RELATIVE_PATH = path.join("ci", "reviewed-npm-audit.json"); + +function loadReviewedInventory(): InventoryEntry[] { + const config = JSON.parse( + fs.readFileSync(path.join(REPO_ROOT, CONFIG_RELATIVE_PATH), "utf-8"), + ) as Record; + const inventory = parseInventoryFromAuditConfig(config, CONFIG_RELATIVE_PATH); + const lockedGraphs = Array.isArray(config.lockedGraphs) ? config.lockedGraphs : []; + for (const graph of lockedGraphs) { + const directory = (graph as Record | null)?.directory; + if (typeof directory !== "string" || directory.length === 0) continue; + const lockRelativePath = path.join(directory, "package-lock.json"); + const lockPath = path.join(REPO_ROOT, lockRelativePath); + if (!fs.existsSync(lockPath)) continue; + const lock = JSON.parse(fs.readFileSync(lockPath, "utf-8")) as unknown; + inventory.push(...parseInventoryFromPackageLock(lock, lockRelativePath)); + } + return inventory; +} + +function loadAdvisories(advisoriesPath: string): unknown[] { + const parsed = JSON.parse(fs.readFileSync(advisoriesPath, "utf-8")) as 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 readFlagValue(argv: readonly string[], flag: string): string | undefined { + const index = argv.indexOf(flag); + if (index < 0) return undefined; + const value = argv[index + 1]; + if (value === undefined || value.startsWith("--")) { + throw new Error(`${flag} requires a value`); + } + return value; +} + +function main(argv: readonly string[]): void { + const inventory = loadReviewedInventory(); + if (argv.includes("--list-packages")) { + const names = [...new Set(inventory.map((entry) => entry.name))].sort(); + for (const name of names) console.log(name); + return; + } + const advisoriesPath = readFlagValue(argv, "--advisories"); + if (!advisoriesPath) { + throw new Error( + "usage: advisory-early-warning-scan.mts --list-packages | --advisories [--output ]", + ); + } + const advisories = loadAdvisories(advisoriesPath); + const signals = correlateAdvisories(advisories, inventory); + const outputPath = readFlagValue(argv, "--output"); + if (outputPath) { + fs.writeFileSync(outputPath, `${JSON.stringify(signals, null, 2)}\n`); + } + console.log( + `advisory early warning: ${advisories.length} advisories, ${inventory.length} inventory entries, ${signals.length} signals`, + ); + for (const signal of signals) console.log(describeSignal(signal)); + // Signals are intentionally non-blocking: the process exits 0 either way, + // and the caller routes signals to a tracking issue for investigation. +} + +function isMainModule(): boolean { + return process.argv[1] + ? import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href + : false; +} + +if (isMainModule()) { + try { + main(process.argv.slice(2)); + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + process.exit(1); + } +} diff --git a/scripts/audit-reviewed-npm-graph.mts b/scripts/audit-reviewed-npm-graph.mts index b2c0317e940..34c05671cfe 100755 --- a/scripts/audit-reviewed-npm-graph.mts +++ b/scripts/audit-reviewed-npm-graph.mts @@ -59,10 +59,60 @@ function readConfig(): AuditConfig { return parsed; } -function auditGraph(directory: string, reportPath: string): Record { +type GraphAuditContext = Readonly<{ + label: string; + nodeVersion: string; + npmVersion: string; + packageSpecs: readonly string[]; +}>; + +// Exported for the provenance-ordering regression test; production callers +// stay inside this script's main(). +export function auditGraph( + directory: string, + reportPath: string, + context: GraphAuditContext, +): Record { + const startedAt = new Date().toISOString(); const result = run("npm", ["audit", "--omit=dev", "--json"], directory, true); + const finishedAt = new Date().toISOString(); fs.writeFileSync(reportPath, result.stdout); - return parseAuditReport(result); + // Registry introspection is best-effort provenance and must never mask the + // audit outcome established below. + let registry = ""; + try { + registry = run("npm", ["config", "get", "registry"], directory).stdout.trim(); + } catch { + registry = ""; + } + // The sidecar is written even when the audit failed: a failed attempt is + // exactly the run whose provenance matters when reconstructing detection + // timelines, matching the records-the-attempt semantics of + // .github/actions/ci-wechat-runtime-audit/audit.sh. + let report: Record = {}; + let auditFailure: Error | undefined; + try { + report = parseAuditReport(result); + } catch (error) { + auditFailure = error instanceof Error ? error : new Error(String(error)); + } + const provenance = buildAuditProvenance({ + failure: auditFailure?.message, + finishedAt, + label: context.label, + nodeVersion: context.nodeVersion, + npmVersion: context.npmVersion, + packageSpecs: context.packageSpecs, + // Convention shared with the WeChat audit sidecar: rawReportPath is + // relative to the directory containing the sidecar. + rawReportPath: path.basename(reportPath), + registry, + report, + startedAt, + }); + fs.writeFileSync(provenanceSidecarPath(reportPath), `${JSON.stringify(provenance, null, 2)}\n`); + if (auditFailure) throw auditFailure; + return report; } export function parseAuditReport(result: { @@ -129,6 +179,111 @@ export function exceedsAuditThreshold( ); } +export type AuditEndpoints = Readonly<{ + configuredRegistry: string | null; + bulkAdvisoryEndpoint: string | null; + note: string; +}>; + +// npm (>= 7) derives its audit endpoint from the configured registry the same +// way (see npm/cli arborist audit-report): it posts the dependency graph to +// the bulk advisory endpoint only — there is no quick-audit fallback; on +// request failure npm reports no advisory data. Recording the endpoint plus +// the configured registry pins down which advisory database actually served a +// given report (#7338). +// +// Keep in sync with the inline provenance writer in +// .github/actions/ci-wechat-runtime-audit/audit.sh, which duplicates this +// derivation for the shell-only WeChat audit. +export function deriveAuditEndpoints(configuredRegistry: string): AuditEndpoints { + if (configuredRegistry.trim() === "") { + // An endpoint derived from an unknown registry would be a nonsense claim; + // record the unknown explicitly instead. + return { + configuredRegistry: null, + bulkAdvisoryEndpoint: null, + note: "the configured registry could not be determined for this run, so the audit endpoint is unknown.", + }; + } + const base = configuredRegistry.replace(/\/+$/, ""); + return { + configuredRegistry, + bulkAdvisoryEndpoint: `${base}/-/npm/v1/security/advisories/bulk`, + note: "npm audit posts the dependency graph to the bulk advisory endpoint of the configured registry; on request failure npm reports no advisory data.", + }; +} + +const GHSA_ID_IN_URL = /GHSA(?:-[23456789cfghjmpqrvwx]{4}){3}/gi; + +// Keep in sync with the inline provenance writer in +// .github/actions/ci-wechat-runtime-audit/audit.sh, which duplicates this +// extraction for the shell-only WeChat audit. +export function extractAdvisoryIds(report: Record): readonly string[] { + const ids = new Set(); + const vulnerabilities = report.vulnerabilities; + const findings = + typeof vulnerabilities === "object" && + vulnerabilities !== null && + !Array.isArray(vulnerabilities) + ? Object.values(vulnerabilities) + : []; + for (const finding of findings) { + const via = (finding as Record | null)?.via; + if (!Array.isArray(via)) continue; + for (const cause of via) { + if (typeof cause !== "object" || cause === null) continue; + const url = (cause as Record).url; + if (typeof url !== "string") continue; + for (const match of url.match(GHSA_ID_IN_URL) ?? []) { + ids.add(`GHSA${match.slice(4).toLowerCase()}`); + } + } + } + return [...ids].sort(); +} + +export type AuditProvenance = Readonly<{ + schemaVersion: 1; + scanner: Readonly<{ name: "npm audit"; npmVersion: string; nodeVersion: string }>; + registry: AuditEndpoints; + run: Readonly<{ startedAt: string; finishedAt: string }>; + graph: Readonly<{ label: string; packageSpecs: readonly string[] }>; + rawReportPath: string; + advisoryIds: readonly string[]; + // Present when the audit attempt failed; the sidecar still records the run. + failure?: string; +}>; + +export function buildAuditProvenance( + input: Readonly<{ + failure?: string; + finishedAt: string; + label: string; + nodeVersion: string; + npmVersion: string; + packageSpecs: readonly string[]; + rawReportPath: string; + registry: string; + report: Record; + startedAt: string; + }>, +): AuditProvenance { + return { + schemaVersion: 1, + scanner: { name: "npm audit", npmVersion: input.npmVersion, nodeVersion: input.nodeVersion }, + registry: deriveAuditEndpoints(input.registry), + run: { startedAt: input.startedAt, finishedAt: input.finishedAt }, + graph: { label: input.label, packageSpecs: input.packageSpecs }, + rawReportPath: input.rawReportPath, + advisoryIds: extractAdvisoryIds(input.report), + ...(input.failure === undefined ? {} : { failure: input.failure }), + }; +} + +export function provenanceSidecarPath(reportPath: string): string { + return `${reportPath.replace(/\.json$/, "")}.provenance.json`; +} + function materializeArchiveGraph(packages: readonly ReviewedPackage[], tempRoot: string): string { const graphDirectory = path.join(tempRoot, "reviewed-archive-graph"); fs.mkdirSync(graphDirectory); @@ -191,6 +346,7 @@ function main(): void { const artifactDirectory = path.join(REPO_ROOT, config.artifactDirectory); fs.rmSync(artifactDirectory, { recursive: true, force: true }); fs.mkdirSync(artifactDirectory, { recursive: true }); + const npmVersion = run("npm", ["--version"], REPO_ROOT).stdout.trim(); const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-reviewed-npm-audit-")); try { const reports = [ @@ -199,6 +355,12 @@ function main(): void { report: auditGraph( materializeArchiveGraph(config.archivePackages, tempRoot), path.join(artifactDirectory, "reviewed-archive-graph.json"), + { + label: "reviewed archive graph", + nodeVersion: process.version, + npmVersion, + packageSpecs: config.archivePackages.map((reviewed) => reviewed.packageSpec), + }, ), }, ...config.lockedGraphs.map((graph, index) => ({ @@ -206,6 +368,12 @@ function main(): void { report: auditGraph( materializeLockedGraph(graph, tempRoot), path.join(artifactDirectory, `locked-graph-${index + 1}.json`), + { + label: graph.label, + nodeVersion: process.version, + npmVersion, + packageSpecs: [graph.packageSpec], + }, ), })), ]; diff --git a/scripts/lib/advisory-early-warning.mts b/scripts/lib/advisory-early-warning.mts new file mode 100644 index 00000000000..bd27064c246 --- /dev/null +++ b/scripts/lib/advisory-early-warning.mts @@ -0,0 +1,325 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// Early-warning correlation between public upstream GitHub Security Advisories +// and the reviewed npm package inventory (#7338). Upstream repository advisories +// are often published weeks before the global reviewed ecosystem record that +// `npm audit` enforces, so this module turns the earlier signal into a traceable, +// NON-blocking investigation prompt. It never replaces the reviewed npm audit +// gate: only exact npm package-name plus semver-range matches are marked +// "investigate", and ambiguous CPE-to-npm matches stay "informational". + +export type AdvisoryConfidence = "exact" | "ambiguous"; +export type AdvisoryAction = "investigate" | "informational"; + +export type AdvisorySignal = Readonly<{ + advisoryId: string; + package: string; + vulnerableRange: string; + matchedVersions: readonly string[]; + source: "upstream-ghsa"; + confidence: AdvisoryConfidence; + action: AdvisoryAction; +}>; + +export type InventoryEntry = Readonly<{ + name: string; + version: string; + origin: string; +}>; + +export type ParsedAdvisoryVulnerability = Readonly<{ + ecosystem: string; + packageName: string; + vulnerableRange: string; +}>; + +export type ParsedAdvisory = Readonly<{ + advisoryId: string; + vulnerabilities: readonly ParsedAdvisoryVulnerability[]; +}>; + +const GHSA_ID_PATTERN = /^GHSA(?:-[23456789cfghjmpqrvwx]{4}){3}$/i; +const RELEASE_VERSION_PATTERN = + /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/; +const RANGE_COMPARATOR_PATTERN = /^(<=|>=|<|>|=)?\s*(\S+)$/; + +type ParsedVersion = Readonly<{ + release: readonly [number, number, number]; + prerelease: readonly string[]; +}>; + +function parseVersion(version: string): ParsedVersion | null { + const match = RELEASE_VERSION_PATTERN.exec(version.trim()); + if (!match) return null; + const release = [Number(match[1]), Number(match[2]), Number(match[3])] as const; + if (release.some((part) => !Number.isSafeInteger(part))) return null; + return { release, prerelease: match[4] ? match[4].split(".") : [] }; +} + +function comparePrereleaseIdentifiers(left: string, right: string): number { + const leftNumeric = /^\d+$/.test(left); + const rightNumeric = /^\d+$/.test(right); + if (leftNumeric && rightNumeric) return Math.sign(Number(left) - Number(right)); + if (leftNumeric) return -1; + if (rightNumeric) return 1; + return left < right ? -1 : left > right ? 1 : 0; +} + +function compareParsedVersions(left: ParsedVersion, right: ParsedVersion): number { + for (let index = 0; index < 3; index += 1) { + const difference = Math.sign(left.release[index] - right.release[index]); + if (difference !== 0) return difference; + } + if (left.prerelease.length === 0 && right.prerelease.length === 0) return 0; + if (left.prerelease.length === 0) return 1; + if (right.prerelease.length === 0) return -1; + const shared = Math.min(left.prerelease.length, right.prerelease.length); + for (let index = 0; index < shared; index += 1) { + const difference = comparePrereleaseIdentifiers( + left.prerelease[index], + right.prerelease[index], + ); + if (difference !== 0) return difference; + } + return Math.sign(left.prerelease.length - right.prerelease.length); +} + +/** Compare two versions; null when either is not an exact semver version. */ +export function compareSemver(left: string, right: string): number | null { + const parsedLeft = parseVersion(left); + const parsedRight = parseVersion(right); + if (!parsedLeft || !parsedRight) return null; + return compareParsedVersions(parsedLeft, parsedRight); +} + +/** + * Evaluate the comma-separated comparator subset GitHub Security Advisories use + * for `vulnerable_version_range` (e.g. ">= 3.0.0, < 3.1.3"). Comparators are + * AND-ed: any parseable comparator that evaluates false proves the version is + * outside the range even when a sibling comparator is unparseable. Returns null + * only when the version does not parse or no parseable comparator can decide; + * callers must treat null as ambiguous, never as a confirmed match. + */ +export function satisfiesVulnerableRange(version: string, range: string): boolean | null { + const parsedVersion = parseVersion(version); + if (!parsedVersion) return null; + const comparators = range + .split(",") + .map((comparator) => comparator.trim()) + .filter((comparator) => comparator.length > 0); + if (comparators.length === 0) return null; + let anyUnparseable = false; + for (const comparator of comparators) { + const match = RANGE_COMPARATOR_PATTERN.exec(comparator); + const bound = match ? parseVersion(match[2]) : null; + if (!match || !bound) { + anyUnparseable = true; + continue; + } + const difference = compareParsedVersions(parsedVersion, bound); + const operator = match[1] ?? "="; + const comparatorSatisfied = + (operator === "<" && difference < 0) || + (operator === "<=" && difference <= 0) || + (operator === ">" && difference > 0) || + (operator === ">=" && difference >= 0) || + (operator === "=" && difference === 0); + if (!comparatorSatisfied) return false; + } + return anyUnparseable ? null : true; +} + +/** + * Extract the correlation-relevant fields from one GitHub Security Advisory + * object (repository-level `/repos/{owner}/{repo}/security-advisories` and + * global `/advisories` records share this shape). Malformed input yields null + * instead of throwing so one bad upstream record cannot break a scan. + */ +export function parseAdvisory(input: unknown): ParsedAdvisory | null { + if (typeof input !== "object" || input === null || Array.isArray(input)) return null; + const record = input as Record; + const advisoryId = record.ghsa_id; + if (typeof advisoryId !== "string" || !GHSA_ID_PATTERN.test(advisoryId)) return null; + const rawVulnerabilities = Array.isArray(record.vulnerabilities) ? record.vulnerabilities : []; + const vulnerabilities: ParsedAdvisoryVulnerability[] = []; + for (const entry of rawVulnerabilities) { + if (typeof entry !== "object" || entry === null) continue; + const vulnerability = entry as Record; + const affected = vulnerability.package; + if (typeof affected !== "object" || affected === null) continue; + const packageName = (affected as Record).name; + if (typeof packageName !== "string" || packageName.length === 0) continue; + const ecosystem = (affected as Record).ecosystem; + const vulnerableRange = vulnerability.vulnerable_version_range; + vulnerabilities.push({ + ecosystem: typeof ecosystem === "string" ? ecosystem : "", + packageName, + vulnerableRange: typeof vulnerableRange === "string" ? vulnerableRange : "", + }); + } + return { advisoryId, vulnerabilities }; +} + +/** + * Build the reviewed package inventory from ci/reviewed-npm-audit.json: + * every committed archive package and locked graph package spec. + */ +export function parseInventoryFromAuditConfig(config: unknown, origin: string): InventoryEntry[] { + if (typeof config !== "object" || config === null) return []; + const record = config as Record; + const inventory: InventoryEntry[] = []; + for (const key of ["archivePackages", "lockedGraphs"]) { + const entries = record[key]; + if (!Array.isArray(entries)) continue; + for (const entry of entries) { + if (typeof entry !== "object" || entry === null) continue; + const packageSpec = (entry as Record).packageSpec; + if (typeof packageSpec !== "string") continue; + const separator = packageSpec.lastIndexOf("@"); + if (separator <= 0) continue; + const name = packageSpec.slice(0, separator); + const version = packageSpec.slice(separator + 1); + if (!parseVersion(version)) continue; + inventory.push({ name, version, origin }); + } + } + return inventory; +} + +/** + * Build an installed-package inventory from a lockfile-version-3 package-lock + * subset: every `node_modules/...` entry that records an installed version. + */ +export function parseInventoryFromPackageLock(lock: unknown, origin: string): InventoryEntry[] { + if (typeof lock !== "object" || lock === null) return []; + const packages = (lock as Record).packages; + if (typeof packages !== "object" || packages === null || Array.isArray(packages)) return []; + const inventory: InventoryEntry[] = []; + for (const [location, entry] of Object.entries(packages)) { + const marker = location.lastIndexOf("node_modules/"); + if (marker < 0) continue; + const pathName = location.slice(marker + "node_modules/".length); + if (pathName.length === 0) continue; + if (typeof entry !== "object" || entry === null) continue; + const version = (entry as Record).version; + if (typeof version !== "string" || version.length === 0) continue; + // Aliased installs (`npm install alias@npm:real-name`) live under the alias + // path but record the real package name in `name`; advisories name the + // real package, so prefer it when present. + const recordedName = (entry as Record).name; + const name = + typeof recordedName === "string" && recordedName.length > 0 ? recordedName : pathName; + inventory.push({ name, version, origin }); + } + return inventory; +} + +type SignalEvidence = { + ranges: string[]; + versions: Set; +}; + +type SignalDraft = { + advisoryId: string; + package: string; + exact: SignalEvidence; + ambiguous: SignalEvidence; +}; + +function addEvidence(evidence: SignalEvidence, range: string, versions: Iterable): void { + if (!evidence.ranges.includes(range)) evidence.ranges.push(range); + for (const version of versions) evidence.versions.add(version); +} + +/** + * Correlate upstream advisories with the reviewed inventory. + * + * - exact npm ecosystem + package-name + parseable-range matches emit + * confidence "exact" / action "investigate"; + * - name collisions from non-npm ecosystems (CPE-style records) and + * unparseable ranges emit confidence "ambiguous" / action "informational"; + * - packages absent from the inventory, versions proven outside the range, + * and malformed advisory objects emit nothing. + * + * Exact and ambiguous evidence for the same advisory and package are tracked + * separately: an exact signal carries only the proving range(s) and verified + * matched versions, and ambiguous evidence never upgrades into it. + * + * No output of this function may block or mutate a release; the reviewed + * npm audit gate remains the authoritative package-level enforcement source. + */ +export function correlateAdvisories( + advisories: readonly unknown[], + inventory: readonly InventoryEntry[], +): AdvisorySignal[] { + const versionsByName = new Map>(); + for (const entry of inventory) { + const versions = versionsByName.get(entry.name) ?? new Set(); + versions.add(entry.version); + versionsByName.set(entry.name, versions); + } + const drafts = new Map(); + for (const input of advisories) { + const advisory = parseAdvisory(input); + if (!advisory) continue; + for (const vulnerability of advisory.vulnerabilities) { + const versions = versionsByName.get(vulnerability.packageName); + if (!versions || versions.size === 0) continue; + let confidence: AdvisoryConfidence | null = null; + const matchedVersions = new Set(); + if (vulnerability.ecosystem.toLowerCase() === "npm") { + const unverifiable = new Set(); + for (const version of versions) { + const satisfied = satisfiesVulnerableRange(version, vulnerability.vulnerableRange); + if (satisfied === true) matchedVersions.add(version); + if (satisfied === null) unverifiable.add(version); + } + if (matchedVersions.size > 0) { + confidence = "exact"; + } else if (unverifiable.size > 0) { + confidence = "ambiguous"; + for (const version of unverifiable) matchedVersions.add(version); + } + } else { + // A non-npm (for example CPE-derived) record naming an npm package is + // never a verified npm mapping; surface it for awareness only. + confidence = "ambiguous"; + for (const version of versions) matchedVersions.add(version); + } + if (confidence === null) continue; + const key = `${advisory.advisoryId} ${vulnerability.packageName}`; + const draft = drafts.get(key) ?? { + advisoryId: advisory.advisoryId, + package: vulnerability.packageName, + exact: { ranges: [], versions: new Set() }, + ambiguous: { ranges: [], versions: new Set() }, + }; + addEvidence( + confidence === "exact" ? draft.exact : draft.ambiguous, + vulnerability.vulnerableRange, + matchedVersions, + ); + drafts.set(key, draft); + } + } + return [...drafts.values()] + .map((draft) => { + const confidence: AdvisoryConfidence = draft.exact.versions.size > 0 ? "exact" : "ambiguous"; + const evidence = confidence === "exact" ? draft.exact : draft.ambiguous; + return { + advisoryId: draft.advisoryId, + package: draft.package, + vulnerableRange: evidence.ranges.join("; "), + matchedVersions: [...evidence.versions].sort(), + source: "upstream-ghsa" as const, + confidence, + action: confidence === "exact" ? ("investigate" as const) : ("informational" as const), + }; + }) + .sort((left, right) => + left.advisoryId === right.advisoryId + ? left.package.localeCompare(right.package) + : left.advisoryId.localeCompare(right.advisoryId), + ); +} diff --git a/test/advisory-early-warning.test.ts b/test/advisory-early-warning.test.ts new file mode 100644 index 00000000000..2bd74b0b9ae --- /dev/null +++ b/test/advisory-early-warning.test.ts @@ -0,0 +1,332 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; +import { + compareSemver, + correlateAdvisories, + parseAdvisory, + parseInventoryFromAuditConfig, + parseInventoryFromPackageLock, + satisfiesVulnerableRange, +} from "../scripts/lib/advisory-early-warning.mts"; + +// Upstream repository security advisory (GET /repos/{owner}/{repo}/security-advisories) +// modeled on GHSA-4c8g-83qw-93j6: published upstream on June 29, weeks before its +// global reviewed ecosystem record appeared on July 21 and npm audit began +// reporting it (#7338). This is the "earlier upstream signal" fixture. +const upstreamFastUriAdvisory = { + ghsa_id: "GHSA-4c8g-83qw-93j6", + cve_id: "CVE-2026-13676", + url: "https://api.github.com/repos/fastify/fast-uri/security-advisories/GHSA-4c8g-83qw-93j6", + html_url: "https://github.com/fastify/fast-uri/security/advisories/GHSA-4c8g-83qw-93j6", + summary: "fast-uri URI parsing divergence enables authority spoofing", + severity: "high", + state: "published", + published_at: "2026-06-29T15:02:11Z", + updated_at: "2026-06-29T15:02:11Z", + identifiers: [ + { type: "GHSA", value: "GHSA-4c8g-83qw-93j6" }, + { type: "CVE", value: "CVE-2026-13676" }, + ], + vulnerabilities: [ + { + package: { ecosystem: "npm", name: "fast-uri" }, + vulnerable_version_range: ">= 3.0.0, < 3.1.3", + patched_versions: "3.1.3", + vulnerable_functions: [], + }, + ], +} as const; + +// NVD/CPE-derived record whose product name collides with an npm package but whose +// ecosystem mapping is not a verified npm mapping (GHSA-45rx-2jwx-cxfr shape). +const cpeDerivedAdvisory = { + ghsa_id: "GHSA-45rx-2jwx-cxfr", + cve_id: "CVE-2026-59892", + summary: "Jaeger propagator baggage injection", + severity: "high", + published_at: "2026-07-03T09:00:00Z", + identifiers: [{ type: "CVE", value: "CVE-2026-59892" }], + vulnerabilities: [ + { + package: { ecosystem: "other", name: "fast-uri" }, + vulnerable_version_range: "cpe:2.3:a:fastify:fast-uri:*:*", + }, + ], +} as const; + +const inventory = [ + { + name: "fast-uri", + version: "3.1.2", + origin: "agents/openclaw/mcporter-runtime/package-lock.json", + }, + { name: "tar", version: "7.5.20", origin: "agents/openclaw/mcporter-runtime/package-lock.json" }, + { name: "openclaw", version: "2026.6.10", origin: "ci/reviewed-npm-audit.json" }, +] as const; + +describe("advisory early warning correlation", () => { + it("correlates an upstream advisory with an affected inventory entry", () => { + const signals = correlateAdvisories([upstreamFastUriAdvisory], inventory); + expect(signals).toEqual([ + { + advisoryId: "GHSA-4c8g-83qw-93j6", + package: "fast-uri", + vulnerableRange: ">= 3.0.0, < 3.1.3", + matchedVersions: ["3.1.2"], + source: "upstream-ghsa", + confidence: "exact", + action: "investigate", + }, + ]); + }); + + it("keeps ambiguous CPE-to-npm matches informational instead of blocking", () => { + const signals = correlateAdvisories([cpeDerivedAdvisory], inventory); + expect(signals).toEqual([ + { + advisoryId: "GHSA-45rx-2jwx-cxfr", + package: "fast-uri", + vulnerableRange: "cpe:2.3:a:fastify:fast-uri:*:*", + matchedVersions: ["3.1.2"], + source: "upstream-ghsa", + confidence: "ambiguous", + action: "informational", + }, + ]); + }); + + it("treats an unparseable npm range as ambiguous rather than blocking", () => { + const advisory = { + ghsa_id: "GHSA-23hp-3jrh-7fpw", + vulnerabilities: [ + { + package: { ecosystem: "npm", name: "tar" }, + vulnerable_version_range: "all versions before the July rewrite", + }, + ], + }; + const signals = correlateAdvisories([advisory], inventory); + expect(signals).toEqual([ + { + advisoryId: "GHSA-23hp-3jrh-7fpw", + package: "tar", + vulnerableRange: "all versions before the July rewrite", + matchedVersions: ["7.5.20"], + source: "upstream-ghsa", + confidence: "ambiguous", + action: "informational", + }, + ]); + }); + + it("emits nothing when the advisory package is absent from the inventory", () => { + const advisory = { + ghsa_id: "GHSA-8988-4f7v-96qf", + vulnerabilities: [ + { + package: { ecosystem: "npm", name: "@opentelemetry/core" }, + vulnerable_version_range: "< 1.30.0", + }, + ], + }; + expect(correlateAdvisories([advisory], inventory)).toEqual([]); + }); + + it("emits nothing when the inventory version is outside the vulnerable range", () => { + const advisory = { + ghsa_id: "GHSA-23hp-3jrh-7fpw", + vulnerabilities: [ + { + package: { ecosystem: "npm", name: "tar" }, + vulnerable_version_range: "< 7.5.16", + }, + ], + }; + expect(correlateAdvisories([advisory], inventory)).toEqual([]); + }); + + it("merges duplicate matches for one advisory and package into a single signal", () => { + const duplicatedInventory = [ + ...inventory, + { name: "fast-uri", version: "3.0.1", origin: "ci/reviewed-npm-audit.json" }, + { name: "fast-uri", version: "3.1.2", origin: "another-lock.json" }, + ]; + const signals = correlateAdvisories([upstreamFastUriAdvisory], duplicatedInventory); + expect(signals).toHaveLength(1); + expect(signals[0]?.matchedVersions).toEqual(["3.0.1", "3.1.2"]); + }); + + const garbageRangeVulnerability = { + package: { ecosystem: "npm", name: "tar" }, + vulnerable_version_range: "all versions before the July rewrite", + }; + const exactRangeVulnerability = { + package: { ecosystem: "npm", name: "tar" }, + vulnerable_version_range: "< 9.0.0", + }; + + it.each([ + ["garbage range first", [garbageRangeVulnerability, exactRangeVulnerability]], + ["exact range first", [exactRangeVulnerability, garbageRangeVulnerability]], + ])("keeps an exact signal free of ambiguous evidence for the same package (%s)", (_label, vulnerabilities) => { + const advisory = { ghsa_id: "GHSA-23hp-3jrh-7fpw", vulnerabilities }; + expect(correlateAdvisories([advisory], inventory)).toEqual([ + { + advisoryId: "GHSA-23hp-3jrh-7fpw", + package: "tar", + vulnerableRange: "< 9.0.0", + matchedVersions: ["7.5.20"], + source: "upstream-ghsa", + confidence: "exact", + action: "investigate", + }, + ]); + }); + + it.each([ + ["null", null], + ["a number", 42], + ["an empty object", {}], + ["a missing ghsa id", { vulnerabilities: [] }], + ["a non-array vulnerabilities field", { ghsa_id: "GHSA-4c8g-83qw-93j6", vulnerabilities: 7 }], + [ + "a vulnerability entry without a package", + { ghsa_id: "GHSA-4c8g-83qw-93j6", vulnerabilities: [{ vulnerable_version_range: "< 1" }] }, + ], + ])("does not throw on malformed advisory input: %s", (_label, advisory) => { + expect(() => correlateAdvisories([advisory], inventory)).not.toThrow(); + expect(correlateAdvisories([advisory], inventory)).toEqual([]); + }); + + it("parses a well-formed advisory into its correlation-relevant fields", () => { + expect(parseAdvisory(upstreamFastUriAdvisory)).toEqual({ + advisoryId: "GHSA-4c8g-83qw-93j6", + vulnerabilities: [ + { + ecosystem: "npm", + packageName: "fast-uri", + vulnerableRange: ">= 3.0.0, < 3.1.3", + }, + ], + }); + }); + + it("rejects advisories whose GHSA id does not look like a GHSA id", () => { + expect(parseAdvisory({ ghsa_id: "not-an-id", vulnerabilities: [] })).toBeNull(); + }); +}); + +describe("advisory early warning inventory parsing", () => { + it("parses package specs from the reviewed npm audit config", () => { + const config = { + archivePackages: [ + { packageSpec: "openclaw@2026.6.10" }, + { packageSpec: "@openclaw/slack@2026.6.10" }, + ], + lockedGraphs: [{ packageSpec: "mcporter@0.7.3" }], + }; + expect(parseInventoryFromAuditConfig(config, "ci/reviewed-npm-audit.json")).toEqual([ + { name: "openclaw", version: "2026.6.10", origin: "ci/reviewed-npm-audit.json" }, + { name: "@openclaw/slack", version: "2026.6.10", origin: "ci/reviewed-npm-audit.json" }, + { name: "mcporter", version: "0.7.3", origin: "ci/reviewed-npm-audit.json" }, + ]); + }); + + it("skips malformed audit config entries without throwing", () => { + const config = { + archivePackages: [{ packageSpec: "no-version" }, { packageSpec: 12 }, null], + lockedGraphs: "nope", + }; + expect(parseInventoryFromAuditConfig(config, "ci/reviewed-npm-audit.json")).toEqual([]); + expect(parseInventoryFromAuditConfig(null, "ci/reviewed-npm-audit.json")).toEqual([]); + }); + + it("parses installed packages from a package-lock subset", () => { + const lock = { + lockfileVersion: 3, + packages: { + "": { name: "root" }, + "node_modules/fast-uri": { version: "3.1.2" }, + "node_modules/@scope/pkg": { version: "1.0.0" }, + "node_modules/outer/node_modules/tar": { version: "7.5.20" }, + "node_modules/linked": { link: true }, + }, + }; + expect(parseInventoryFromPackageLock(lock, "fixture-lock.json")).toEqual([ + { name: "fast-uri", version: "3.1.2", origin: "fixture-lock.json" }, + { name: "@scope/pkg", version: "1.0.0", origin: "fixture-lock.json" }, + { name: "tar", version: "7.5.20", origin: "fixture-lock.json" }, + ]); + }); + + it("inventories aliased lock entries under their real package name", () => { + const lock = { + lockfileVersion: 3, + packages: { + "node_modules/my-alias": { name: "fast-uri", version: "3.1.2" }, + }, + }; + expect(parseInventoryFromPackageLock(lock, "fixture-lock.json")).toEqual([ + { name: "fast-uri", version: "3.1.2", origin: "fixture-lock.json" }, + ]); + }); + + it("returns an empty inventory for malformed package-lock input", () => { + expect(parseInventoryFromPackageLock(null, "fixture-lock.json")).toEqual([]); + expect(parseInventoryFromPackageLock({ packages: [] }, "fixture-lock.json")).toEqual([]); + }); +}); + +describe("advisory early warning semver subset", () => { + it.each([ + ["3.1.2", ">= 3.0.0, < 3.1.3", true], + ["3.1.3", ">= 3.0.0, < 3.1.3", false], + ["2.9.9", ">= 3.0.0, < 3.1.3", false], + ["7.5.11", "<= 7.5.15", true], + ["7.5.15", "<= 7.5.15", true], + ["3.0.0", ">= 3.0.0", true], + ["2.9.9", ">= 3.0.0", false], + ["3.0.1", "> 3.0.0", true], + ["3.0.0", "> 3.0.0", false], + ["1.2.3", "1.2.3", true], + ["1.2.3", "= 1.2.4", false], + ["3.1.3-rc.1", "< 3.1.3", true], + // A provably-false parseable comparator decides the AND even when another + // comparator is unparseable. + ["2.0.0", ">= 3.0.0, < 3.1.x", false], + ])("satisfiesVulnerableRange(%s, %s) -> %s", (version, range, expected) => { + expect(satisfiesVulnerableRange(version, range)).toBe(expected); + }); + + it.each([ + ["not-a-version", "< 1.0.0"], + ["1.0.0", "cpe:2.3:a:fastify:fast-uri:*:*"], + ["1.0.0", ""], + ["1.0.0", "^1.0.0 || >= 2"], + ["3.0.5", ">= 3.0.0, < 3.1.x"], + ])("reports unparseable input as null for (%s, %s)", (version, range) => { + expect(satisfiesVulnerableRange(version, range)).toBeNull(); + }); + + it.each([ + ["1.2.3", "1.2.3", 0], + ["1.2.3", "1.2.4", -1], + ["1.10.0", "1.9.0", 1], + ["1.0.0-alpha", "1.0.0", -1], + ["1.0.0-alpha.2", "1.0.0-alpha.10", -1], + ["1.0.0-beta", "1.0.0-alpha", 1], + ["v1.2.3", "1.2.3", 0], + ["1.2.3+build.5", "1.2.3", 0], + ])("compareSemver(%s, %s) -> %i", (left, right, expected) => { + expect(Math.sign(compareSemver(left, right) ?? Number.NaN)).toBe(expected); + }); + + it.each([ + ["1.2", "1.2.3"], + ["1.2.3", "1.2"], + ])("compareSemver(%s, %s) is null for non-semver input", (left, right) => { + expect(compareSemver(left, right)).toBeNull(); + }); +}); diff --git a/test/reviewed-npm-audit.test.ts b/test/reviewed-npm-audit.test.ts index 2fbdee52641..7bd6a974ce7 100644 --- a/test/reviewed-npm-audit.test.ts +++ b/test/reviewed-npm-audit.test.ts @@ -2,11 +2,17 @@ // SPDX-License-Identifier: Apache-2.0 import fs from "node:fs"; +import os from "node:os"; import path from "node:path"; import { describe, expect, it } from "vitest"; import { + auditGraph, + buildAuditProvenance, + deriveAuditEndpoints, exceedsAuditThreshold, + extractAdvisoryIds, parseAuditReport, + provenanceSidecarPath, vulnerabilityCounts, } from "../scripts/audit-reviewed-npm-graph.mts"; @@ -64,3 +70,169 @@ describe("reviewed npm audit gate", () => { ).toThrow(/vulnerability report|vulnerability count/); }); }); + +describe("reviewed npm audit provenance", () => { + const detectionReport = { + metadata: { + vulnerabilities: { info: 0, low: 0, moderate: 0, high: 1, critical: 0 }, + }, + vulnerabilities: { + "fast-uri": { + via: [ + { + source: 1104001, + name: "fast-uri", + url: "https://github.com/advisories/GHSA-4c8g-83qw-93j6", + }, + "ajv", + ], + }, + ajv: { via: ["fast-uri"] }, + tar: { + via: [ + { url: "https://github.com/advisories/GHSA-23hp-3jrh-7fpw" }, + { url: "https://github.com/advisories/GHSA-4c8g-83qw-93j6" }, + ], + }, + }, + }; + + it("extracts sorted unique GHSA ids from a report", () => { + expect(extractAdvisoryIds(detectionReport)).toEqual([ + "GHSA-23hp-3jrh-7fpw", + "GHSA-4c8g-83qw-93j6", + ]); + }); + + it.each([ + ["a clean report", { metadata: { vulnerabilities: {} } }], + ["a report without vulnerabilities", {}], + ["string-only via chains", { vulnerabilities: { ajv: { via: ["fast-uri"] } } }], + ["a malformed vulnerabilities value", { vulnerabilities: [1, 2] }], + ])("extracts no advisory ids from %s", (_label, report) => { + expect(extractAdvisoryIds(report as Record)).toEqual([]); + }); + + it.each([ + "https://registry.npmjs.org/", + "https://registry.npmjs.org", + ])("derives the bulk advisory endpoint npm audit uses from %s", (registry) => { + const endpoints = deriveAuditEndpoints(registry); + expect(endpoints).toEqual({ + configuredRegistry: registry, + bulkAdvisoryEndpoint: "https://registry.npmjs.org/-/npm/v1/security/advisories/bulk", + note: expect.stringMatching(/bulk advisory endpoint.*no advisory data/s), + }); + }); + + it("places the provenance sidecar next to its raw report", () => { + expect(provenanceSidecarPath("/tmp/artifacts/reviewed-archive-graph.json")).toBe( + "/tmp/artifacts/reviewed-archive-graph.provenance.json", + ); + }); + + it("builds a complete provenance record for one audited graph", () => { + const provenance = buildAuditProvenance({ + finishedAt: "2026-07-21T20:09:41.000Z", + label: "reviewed archive graph", + nodeVersion: "v22.22.2", + npmVersion: "10.9.7", + packageSpecs: ["openclaw@2026.6.10", "@openclaw/slack@2026.6.10"], + rawReportPath: "reviewed-archive-graph.json", + registry: "https://registry.npmjs.org/", + report: detectionReport, + startedAt: "2026-07-21T20:09:12.000Z", + }); + expect(provenance).toEqual({ + schemaVersion: 1, + scanner: { name: "npm audit", npmVersion: "10.9.7", nodeVersion: "v22.22.2" }, + registry: deriveAuditEndpoints("https://registry.npmjs.org/"), + run: { startedAt: "2026-07-21T20:09:12.000Z", finishedAt: "2026-07-21T20:09:41.000Z" }, + graph: { + label: "reviewed archive graph", + packageSpecs: ["openclaw@2026.6.10", "@openclaw/slack@2026.6.10"], + }, + rawReportPath: "reviewed-archive-graph.json", + advisoryIds: ["GHSA-23hp-3jrh-7fpw", "GHSA-4c8g-83qw-93j6"], + }); + expect(provenance).not.toHaveProperty("failure"); + }); + + it("records a failure marker so a failed audit attempt still leaves provenance", () => { + const provenance = buildAuditProvenance({ + failure: "npm audit failed without vulnerability findings: ECONNREFUSED", + finishedAt: "2026-07-21T20:09:41.000Z", + label: "reviewed archive graph", + nodeVersion: "v22.22.2", + npmVersion: "10.9.7", + packageSpecs: ["openclaw@2026.6.10"], + rawReportPath: "reviewed-archive-graph.json", + registry: "https://registry.npmjs.org/", + report: {}, + startedAt: "2026-07-21T20:09:12.000Z", + }); + expect(provenance.failure).toBe( + "npm audit failed without vulnerability findings: ECONNREFUSED", + ); + expect(provenance.advisoryIds).toEqual([]); + }); + + it.each([ + "", + " ", + ])("records an unknown registry explicitly instead of deriving a nonsense endpoint (%j)", (registry) => { + expect(deriveAuditEndpoints(registry)).toEqual({ + configuredRegistry: null, + bulkAdvisoryEndpoint: null, + note: expect.stringMatching(/registry could not be determined/), + }); + }); + + it("writes the failure sidecar before rethrowing when npm audit hard-fails", () => { + const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-audit-provenance-")); + const originalPath = process.env.PATH; + try { + const fakeBin = path.join(tempRoot, "bin"); + fs.mkdirSync(fakeBin); + // Fake npm: `npm audit` emits npm's parseable transport-error JSON and + // exits 1; every other subcommand (registry introspection) fails hard. + fs.writeFileSync( + path.join(fakeBin, "npm"), + [ + "#!/bin/sh", + 'test "$1" = "audit" && {', + ' echo \'{"error":{"code":"ECONNREFUSED","summary":"registry unreachable"}}\'', + " exit 1", + "}", + "exit 7", + "", + ].join("\n"), + { mode: 0o755 }, + ); + process.env.PATH = `${fakeBin}${path.delimiter}${originalPath}`; + const reportPath = path.join(tempRoot, "graph.json"); + expect(() => + auditGraph(tempRoot, reportPath, { + label: "fixture graph", + nodeVersion: "v22.22.2", + npmVersion: "10.9.7", + packageSpecs: ["fixture@1.0.0"], + }), + ).toThrow(/ECONNREFUSED/); + const sidecar = JSON.parse( + fs.readFileSync(path.join(tempRoot, "graph.provenance.json"), "utf-8"), + ) as Record; + expect(sidecar.failure).toMatch(/ECONNREFUSED/); + expect(sidecar.advisoryIds).toEqual([]); + expect(sidecar.rawReportPath).toBe("graph.json"); + expect(sidecar.registry).toEqual({ + configuredRegistry: null, + bulkAdvisoryEndpoint: null, + note: expect.stringMatching(/registry could not be determined/), + }); + } finally { + process.env.PATH = originalPath; + fs.rmSync(tempRoot, { recursive: true, force: true }); + } + }); +}); From 1b53bb7e34124e3cddeac8437b803e8b82dff5a9 Mon Sep 17 00:00:00 2001 From: Dongni-Yang Date: Wed, 22 Jul 2026 12:40:59 +0800 Subject: [PATCH 2/8] docs(security): add SPDX header to advisory early-warning doc CodeRabbit: every source file carries the SPDX header; match the sibling docs/security file comment syntax. Refs #7338 Signed-off-by: Dongni-Yang Co-Authored-By: Claude Fable 5 --- docs/security/advisory-early-warning.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/security/advisory-early-warning.md b/docs/security/advisory-early-warning.md index 5bb55f45824..12add0b7c5f 100644 --- a/docs/security/advisory-early-warning.md +++ b/docs/security/advisory-early-warning.md @@ -1,3 +1,6 @@ + + + # Advisory Early Warning and Audit Provenance Status: implemented mechanism, proposed policy (issue #7338; evidence from #7276) From fa46c2d3fba7f8d239c328477397a4ea703cf340 Mon Sep 17 00:00:00 2001 From: Dongni-Yang Date: Wed, 22 Jul 2026 14:11:31 +0800 Subject: [PATCH 3/8] feat(security): reconcile early-warning signals with NVD Follow-up to the #7338 early-warning scan: use NVD as the supplementary reconciliation source the issue calls for, without ever treating NVD or CPE data as an authoritative npm mapping. - scripts/lib/nvd-reconciliation.mts: pure parser for NVD 2.0 records and per-signal reconciliation annotations (corroborated, nvd-missing, nvd-divergent) that are informational only - they never change a signal's action, confidence, or dedupe identity. - Advisory signals now carry the GHSA record's cve_id when present; the scan CLI accepts --nvd-records for offline attachment. - The scheduled workflow queries NVD for up to 20 signal CVE ids per run (7s spacing for the unauthenticated rate limit, cap logged when exceeded) and appends the annotation to the rolling issue lines. NVD being unreachable degrades to an "unavailable" note and never fails the run - deliberately softer than the fail-loud GitHub fetch, since NVD is supplementary. - docs: NVD reconciliation semantics plus the #7276 post-mortem section answering the issue's detection-trigger questions strictly from its own evidence table. Refs #7338 Signed-off-by: Dongni-Yang Co-Authored-By: Claude Fable 5 --- .github/workflows/advisory-early-warning.yaml | 89 ++- docs/security/advisory-early-warning.md | 99 +++- scripts/advisory-early-warning-scan.mts | 35 +- scripts/lib/advisory-early-warning.mts | 15 + scripts/lib/nvd-reconciliation.mts | 186 +++++++ test/advisory-early-warning.test.ts | 2 + test/nvd-reconciliation.test.ts | 526 ++++++++++++++++++ 7 files changed, 939 insertions(+), 13 deletions(-) create mode 100644 scripts/lib/nvd-reconciliation.mts create mode 100644 test/nvd-reconciliation.test.ts diff --git a/.github/workflows/advisory-early-warning.yaml b/.github/workflows/advisory-early-warning.yaml index 9bd17df7218..3a7f833854a 100644 --- a/.github/workflows/advisory-early-warning.yaml +++ b/.github/workflows/advisory-early-warning.yaml @@ -11,8 +11,11 @@ # ambiguous, informational-only path), and "malware" records (npm malware # advisories naming an inventory package). Matches surface as a rolling, # security-labeled tracking issue — a traceable, NON-blocking investigation -# signal. Enforcement stays with the reviewed npm audit gate; this workflow -# never fails a build or mutates a release. +# signal. Signals that carry a CVE id are additionally reconciled against NVD, +# a SUPPLEMENTARY informational source that never overrides the reviewed npm +# mapping and whose outages degrade gracefully. Enforcement stays with the +# reviewed npm audit gate; this workflow never fails a build or mutates a +# release. name: Security / Advisory Early Warning @@ -33,7 +36,9 @@ jobs: early-warning: if: github.repository == 'NVIDIA/NemoClaw' runs-on: ubuntu-latest - timeout-minutes: 15 + # NVD reconciliation worst case adds ~12 minutes (20 requests, 7 s apart, + # 30 s timeout each), on top of the advisory fetch. + timeout-minutes: 30 steps: - name: Checkout uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 @@ -93,6 +98,59 @@ jobs: --advisories "$RUNNER_TEMP/advisories.json" \ --output "$RUNNER_TEMP/signals.json" + - name: Reconcile signals with NVD (supplementary, non-blocking) + run: | + set -euo pipefail + signals="$RUNNER_TEMP/signals.json" + # NVD is a SUPPLEMENTARY reconciliation source (#7338). This is a + # deliberate contrast with the GitHub advisory fetch above, which + # fails loudly because no signals can exist without it: losing NVD + # data only loses an informational annotation, so NVD being down or + # rate-limited degrades gracefully to an "NVD: unavailable" + # annotation and never fails the workflow. + : >"$RUNNER_TEMP/nvd-unavailable.txt" + : >"$RUNNER_TEMP/nvd-skipped.txt" + : >"$RUNNER_TEMP/nvd-records.jsonl" + jq -r '[.[] | .cveId // empty] | unique | .[]' "$signals" \ + >"$RUNNER_TEMP/nvd-cve-ids.txt" + mapfile -t cve_ids <"$RUNNER_TEMP/nvd-cve-ids.txt" + total="${#cve_ids[@]}" + cap=20 + if [ "$total" -gt "$cap" ]; then + # No silent caps: unauthenticated NVD allows ~5 requests per 30 s, + # so one run reconciles at most $cap CVE ids; the rest are listed + # in the rolling issue without an NVD annotation. + echo "NVD reconciliation capped at $cap of $total CVE ids this run (unauthenticated NVD rate limit); $((total - cap)) CVE ids left unannotated." + printf '%s\n' "${cve_ids[@]:$cap}" >"$RUNNER_TEMP/nvd-skipped.txt" + fi + first=1 + for cve_id in "${cve_ids[@]:0:$cap}"; do + # cveId values only reach signals when they match + # ^CVE-\d{4}-\d{4,}$ (scripts/lib/nvd-reconciliation.mts), so they + # are URL-safe as-is. Space requests ~7 s apart to respect the + # ~5-requests-per-30-s unauthenticated NVD rate limit. + [ "$first" -eq 1 ] || sleep 7 + first=0 + # Only a response carrying the NVD envelope (a vulnerabilities + # array — empty for reserved ids) counts as answered; a 200 with a + # JSON error body degrades to "unavailable" like any other outage. + if response="$(curl -sS --fail --max-time 30 \ + "https://services.nvd.nist.gov/rest/json/cves/2.0?cveId=$cve_id")" \ + && record="$(jq -ce 'select(.vulnerabilities | type == "array")' \ + <<<"$response" 2>/dev/null)"; then + printf '%s\n' "$record" >>"$RUNNER_TEMP/nvd-records.jsonl" + echo "Fetched NVD record for $cve_id" + else + echo "NVD unavailable for $cve_id; annotating the signal with 'NVD: unavailable'." + printf '%s\n' "$cve_id" >>"$RUNNER_TEMP/nvd-unavailable.txt" + fi + done + jq -s '.' "$RUNNER_TEMP/nvd-records.jsonl" >"$RUNNER_TEMP/nvd-records.json" + node --experimental-strip-types scripts/advisory-early-warning-scan.mts \ + --advisories "$RUNNER_TEMP/advisories.json" \ + --nvd-records "$RUNNER_TEMP/nvd-records.json" \ + --output "$signals" + - name: Create or update the rolling early-warning issue env: GH_TOKEN: ${{ github.token }} @@ -114,15 +172,34 @@ jobs: # "(no range)"), so existing bodies are checked with a fixed-string # grep for " " — a prefix-sibling package (tar vs tar-stream) # can never falsely dedupe. Advisory free text is sanitized so it - # cannot split lines or corrupt the TSV. - jq -r '.[] | + # cannot split lines or corrupt the TSV. The NVD reconciliation + # extends the line TEXT only, never the dedupe key: a line appended + # before its NVD annotation was available is not re-appended later. + # Fetch-failed CVE ids override the re-scan's "nvd-missing" (which + # would falsely claim NVD answered), and capped-out CVE ids carry no + # NVD note at all. + jq -r --rawfile nvd_unavailable "$RUNNER_TEMP/nvd-unavailable.txt" \ + --rawfile nvd_skipped "$RUNNER_TEMP/nvd-skipped.txt" ' + ($nvd_unavailable | split("\n") | map(select(length > 0))) as $nvdDown | + ($nvd_skipped | split("\n") | map(select(length > 0))) as $nvdSkipped | + .[] | + (.cveId // "") as $cve | (.advisoryId + " " + (.package | gsub("[\\r\\n\\t]"; " "))) as $key | + (if ($nvdDown | index($cve)) != null then " — NVD: unavailable" + elif ($nvdSkipped | index($cve)) != null then "" + elif .nvd then + " — NVD: " + .nvd.agreement + + (if .nvd.nvdPublished != null + then " (published " + (.nvd.nvdPublished | .[0:10]) + ")" + else "" end) + else "" end) as $nvdNote | [$key, "- [ ] " + $key + " " + (if .vulnerableRange == "" then "(no range)" else (.vulnerableRange | gsub("[\\r\\n\\t]"; " ")) end) + " [" + .action + ", " + .confidence + ", matched " + - (.matchedVersions | join(" ")) + "] (source: " + .source + ")"] | + (.matchedVersions | join(" ")) + "] (source: " + .source + ")" + + $nvdNote] | @tsv' "$signals" >"$RUNNER_TEMP/signal-lines.tsv" # Only trust a rolling issue this workflow created itself: it must be # authored by the Actions bot AND carry the embedded marker. A diff --git a/docs/security/advisory-early-warning.md b/docs/security/advisory-early-warning.md index 12add0b7c5f..9361fa17fe8 100644 --- a/docs/security/advisory-early-warning.md +++ b/docs/security/advisory-early-warning.md @@ -37,7 +37,9 @@ 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`. @@ -62,6 +64,37 @@ shape unchanged. in CI) remains enabled and authoritative for exact npm package/version-range decisions. The early-warning path only triggers investigation and rescanning. +## NVD supplementary reconciliation + +Signals that carry a CVE id are additionally 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). CPE criteria surface only as a count in the note, never as package + matches. +- The workflow queries at most 20 CVE ids per run, spaced 7 seconds apart, + to respect the unauthenticated NVD rate limit of roughly five requests per + 30 seconds; when the cap truncates the list it says so in the run log + rather than skipping silently. An NVD outage or rate-limit degrades + gracefully to an `NVD: unavailable` annotation — deliberately unlike the + GitHub advisory fetch, which fails loudly because signals cannot be + computed without it. +- `scripts/advisory-early-warning-scan.mts --nvd-records ` attaches + reconciliations from a file of previously fetched NVD responses; the CLI + itself never performs network requests. +- NVD annotations extend the rolling issue's line text only. The dedupe key + (advisory id plus package) is unchanged, so a line appended before its NVD + annotation was available is not re-appended later. + ## Provenance recorded per audit Each reviewed npm audit report now has a `*.provenance.json` sidecar @@ -84,6 +117,70 @@ 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): + shipped — the six-hourly scan 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. + 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): shipped — the scheduled scan correlates every advisory type + against the full reviewed inventory every six hours, independent of build + execution order. Not yet shipped — rescanning maintained immutable image + digests (an image-scan pipeline) waits on the supported-image scope that + product/security owners must define (see the policy defaults below). +- 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. + ## Proposed policy defaults (pending maintainer confirmation) The following defaults answer #7338's open policy questions. They are diff --git a/scripts/advisory-early-warning-scan.mts b/scripts/advisory-early-warning-scan.mts index b91b9bfebc1..cd7b4585e8e 100755 --- a/scripts/advisory-early-warning-scan.mts +++ b/scripts/advisory-early-warning-scan.mts @@ -10,18 +10,23 @@ // // Usage: // advisory-early-warning-scan.mts --list-packages -// advisory-early-warning-scan.mts --advisories [--output ] +// advisory-early-warning-scan.mts --advisories +// [--nvd-records ] [--output ] +// +// --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 +54,20 @@ 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 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 { @@ -73,11 +90,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 --list-packages | --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..6877572e3d7 --- /dev/null +++ b/scripts/lib/nvd-reconciliation.mts @@ -0,0 +1,186 @@ +// 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; + for (const node of nodes) { + if (typeof node !== "object" || node === null) continue; + const matches = (node as Record).cpeMatch; + if (!Array.isArray(matches)) continue; + 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..47d6f36dea2 --- /dev/null +++ b/test/nvd-reconciliation.test.ts @@ -0,0 +1,526 @@ +// 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:*:*:*:*:*:*:*:*", + ]); + }); +}); + +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 REPO_ROOT = path.join(import.meta.dirname, ".."); + const SCAN_CLI = path.join(REPO_ROOT, "scripts", "advisory-early-warning-scan.mts"); + const AUDIT_CONFIG = JSON.parse( + fs.readFileSync(path.join(REPO_ROOT, "ci", "reviewed-npm-audit.json"), "utf-8"), + ) as { archivePackages: readonly { packageSpec: string }[] }; + const firstPackageSpec = AUDIT_CONFIG.archivePackages[0]?.packageSpec ?? ""; + // ">= 0.0.0" matches whichever version the committed spec currently pins, so + // the test tracks the real inventory without depending on exact versions. + const inventoryPackage = firstPackageSpec.slice(0, firstPackageSpec.lastIndexOf("@")); + const cliAdvisory = { + ghsa_id: "GHSA-4c8g-83qw-93j6", + cve_id: "CVE-2026-13676", + vulnerabilities: [ + { + package: { ecosystem: "npm", name: inventoryPackage }, + vulnerable_version_range: ">= 0.0.0", + }, + ], + }; + + function runScanCli(args: readonly string[]): string { + return execFileSync(process.execPath, ["--experimental-strip-types", SCAN_CLI, ...args], { + cwd: REPO_ROOT, + 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 { + expect(inventoryPackage).not.toBe(""); + const advisoriesPath = path.join(tempRoot, "advisories.json"); + const nvdRecordsPath = path.join(tempRoot, "nvd-records.json"); + const outputPath = path.join(tempRoot, "signals.json"); + fs.writeFileSync(advisoriesPath, JSON.stringify([cliAdvisory])); + fs.writeFileSync(nvdRecordsPath, JSON.stringify([analyzedFastUriResponse])); + const stdout = runScanCli([ + "--advisories", + advisoriesPath, + "--nvd-records", + nvdRecordsPath, + "--output", + outputPath, + ]); + const signals = JSON.parse(fs.readFileSync(outputPath, "utf-8")) as Record[]; + expect(signals).toHaveLength(1); + expect(signals[0]).toMatchObject({ + advisoryId: "GHSA-4c8g-83qw-93j6", + cveId: "CVE-2026-13676", + package: inventoryPackage, + nvd: { + cveId: "CVE-2026-13676", + nvdStatus: "Analyzed", + nvdPublished: "2026-06-29T16:15:09.230", + agreement: "corroborated", + }, + }); + expect(stdout).toContain("NVD: corroborated (published 2026-06-29)"); + } 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 { + expect(inventoryPackage).not.toBe(""); + const advisoriesPath = path.join(tempRoot, "advisories.json"); + const outputPath = path.join(tempRoot, "signals.json"); + fs.writeFileSync(advisoriesPath, JSON.stringify([cliAdvisory])); + const stdout = runScanCli(["--advisories", advisoriesPath, "--output", outputPath]); + const signals = JSON.parse(fs.readFileSync(outputPath, "utf-8")) as Record[]; + expect(signals).toHaveLength(1); + expect(signals[0]).toMatchObject({ cveId: "CVE-2026-13676" }); + expect(signals[0]).not.toHaveProperty("nvd"); + expect(stdout).not.toContain("NVD:"); + } finally { + fs.rmSync(tempRoot, { recursive: true, force: true }); + } + }); +}); From 1abcf3a94c7cab4475d10743afb94a2369427483 Mon Sep 17 00:00:00 2001 From: Dongni-Yang Date: Wed, 22 Jul 2026 15:11:19 +0800 Subject: [PATCH 4/8] test(security): make NVD scan CLI tests hermetic via --inventory The source-shape scanner rightly flags assertions derived from repo config reads; give the scan CLI an explicit --inventory input so the CLI tests run against literal fixtures instead of the live reviewed inventory. The scheduled workflow keeps the repo-derived default. Refs #7338 Signed-off-by: Dongni-Yang Co-Authored-By: Claude Fable 5 --- docs/security/advisory-early-warning.md | 7 ++- scripts/advisory-early-warning-scan.mts | 35 ++++++++++-- test/nvd-reconciliation.test.ts | 76 ++++++++++++++++--------- 3 files changed, 84 insertions(+), 34 deletions(-) diff --git a/docs/security/advisory-early-warning.md b/docs/security/advisory-early-warning.md index 9361fa17fe8..ee26302033c 100644 --- a/docs/security/advisory-early-warning.md +++ b/docs/security/advisory-early-warning.md @@ -42,7 +42,9 @@ shape unchanged. `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`. + `package-lock.json`. The scan CLI's `--inventory ` flag substitutes an + explicit `{name, version}` inventory for hermetic offline runs; the + workflow always uses the repo-derived default. - 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 @@ -79,7 +81,8 @@ purely informational annotation that never changes a signal's `action` or `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). CPE criteria surface only as a count in the note, never as package + `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. - The workflow queries at most 20 CVE ids per run, spaced 7 seconds apart, to respect the unauthenticated NVD rate limit of roughly five requests per diff --git a/scripts/advisory-early-warning-scan.mts b/scripts/advisory-early-warning-scan.mts index cd7b4585e8e..f04a61c8743 100755 --- a/scripts/advisory-early-warning-scan.mts +++ b/scripts/advisory-early-warning-scan.mts @@ -9,10 +9,16 @@ // 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 +// 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. @@ -59,6 +65,26 @@ function loadNvdResponses(nvdRecordsPath: string): unknown[] { return Array.isArray(parsed) ? parsed : [parsed]; } +function loadInventoryOverride(inventoryPath: string): InventoryEntry[] { + const parsed = JSON.parse(fs.readFileSync(inventoryPath, "utf-8")) as unknown; + const entries = Array.isArray(parsed) ? parsed : []; + const inventory: InventoryEntry[] = []; + for (const entry of entries) { + if (typeof entry !== "object" || entry === null) continue; + const name = (entry as Record).name; + const version = (entry as Record).version; + if (typeof name !== "string" || name.length === 0) continue; + if (typeof version !== "string" || version.length === 0) continue; + const origin = (entry as Record).origin; + inventory.push({ + name, + version, + origin: typeof origin === "string" && origin.length > 0 ? origin : inventoryPath, + }); + } + return inventory; +} + function describeNvd(signal: NvdAnnotatedSignal): string { if (!signal.nvd) return ""; const published = @@ -81,7 +107,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); @@ -90,7 +117,7 @@ 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 [--nvd-records ] [--output ]", + "usage: advisory-early-warning-scan.mts [--inventory ] --list-packages | [--inventory ] --advisories [--nvd-records ] [--output ]", ); } const advisories = loadAdvisories(advisoriesPath); diff --git a/test/nvd-reconciliation.test.ts b/test/nvd-reconciliation.test.ts index 47d6f36dea2..3ba7166c840 100644 --- a/test/nvd-reconciliation.test.ts +++ b/test/nvd-reconciliation.test.ts @@ -443,29 +443,39 @@ describe("attaching NVD reconciliations to signals", () => { }); describe("advisory early-warning CLI --nvd-records", () => { - const REPO_ROOT = path.join(import.meta.dirname, ".."); - const SCAN_CLI = path.join(REPO_ROOT, "scripts", "advisory-early-warning-scan.mts"); - const AUDIT_CONFIG = JSON.parse( - fs.readFileSync(path.join(REPO_ROOT, "ci", "reviewed-npm-audit.json"), "utf-8"), - ) as { archivePackages: readonly { packageSpec: string }[] }; - const firstPackageSpec = AUDIT_CONFIG.archivePackages[0]?.packageSpec ?? ""; - // ">= 0.0.0" matches whichever version the committed spec currently pins, so - // the test tracks the real inventory without depending on exact versions. - const inventoryPackage = firstPackageSpec.slice(0, firstPackageSpec.lastIndexOf("@")); + 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: inventoryPackage }, - vulnerable_version_range: ">= 0.0.0", + 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], { - cwd: REPO_ROOT, encoding: "utf-8", }); } @@ -473,13 +483,16 @@ describe("advisory early-warning CLI --nvd-records", () => { it("attaches reconciliations offline from --nvd-records without any network access", () => { const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-nvd-reconciliation-")); try { - expect(inventoryPackage).not.toBe(""); + 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", @@ -488,18 +501,18 @@ describe("advisory early-warning CLI --nvd-records", () => { outputPath, ]); const signals = JSON.parse(fs.readFileSync(outputPath, "utf-8")) as Record[]; - expect(signals).toHaveLength(1); - expect(signals[0]).toMatchObject({ - advisoryId: "GHSA-4c8g-83qw-93j6", - cveId: "CVE-2026-13676", - package: inventoryPackage, - nvd: { - cveId: "CVE-2026-13676", - nvdStatus: "Analyzed", - nvdPublished: "2026-06-29T16:15:09.230", - agreement: "corroborated", + 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 }); @@ -509,14 +522,21 @@ describe("advisory early-warning CLI --nvd-records", () => { it("emits unannotated signals when --nvd-records is not given", () => { const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-nvd-reconciliation-")); try { - expect(inventoryPackage).not.toBe(""); + 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(["--advisories", advisoriesPath, "--output", outputPath]); + const stdout = runScanCli([ + "--inventory", + inventoryPath, + "--advisories", + advisoriesPath, + "--output", + outputPath, + ]); const signals = JSON.parse(fs.readFileSync(outputPath, "utf-8")) as Record[]; - expect(signals).toHaveLength(1); - expect(signals[0]).toMatchObject({ cveId: "CVE-2026-13676" }); + expect(signals).toEqual([expectedCliSignal]); expect(signals[0]).not.toHaveProperty("nvd"); expect(stdout).not.toContain("NVD:"); } finally { From cb4de75ea88678afc6659c858cf7b22c7a6f8354 Mon Sep 17 00:00:00 2001 From: Dongni-Yang Date: Fri, 24 Jul 2026 15:26:29 +0800 Subject: [PATCH 5/8] chore: retrigger checks after the pr title fix Refs #7338 Signed-off-by: Dongni-Yang Co-Authored-By: Claude Fable 5 From 27e6cf567ee57c375d3baad2ed1682ed1f460370 Mon Sep 17 00:00:00 2001 From: Dongni-Yang Date: Fri, 24 Jul 2026 15:31:48 +0800 Subject: [PATCH 6/8] fix(security): fail loudly on malformed --inventory entries and align doc style Review follow-up: a malformed --inventory entry now fails the scan run with an error naming the entry index instead of silently shrinking the inventory (which would under-report advisories with no visible signal), and the added doc sections follow the documentation style guide (one sentence per source line, direct imperatives for the CLI flags). Refs #7338 Signed-off-by: Dongni-Yang Co-Authored-By: Claude Fable 5 --- docs/security/advisory-early-warning.md | 114 +++++++----------------- scripts/advisory-early-warning-scan.mts | 33 ++++--- test/nvd-reconciliation.test.ts | 16 ++++ 3 files changed, 72 insertions(+), 91 deletions(-) diff --git a/docs/security/advisory-early-warning.md b/docs/security/advisory-early-warning.md index 4d6a65c6f86..f1cf40b02c5 100644 --- a/docs/security/advisory-early-warning.md +++ b/docs/security/advisory-early-warning.md @@ -45,8 +45,8 @@ shape unchanged. `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`. The scan CLI's `--inventory ` flag substitutes an - explicit `{name, version}` inventory for hermetic offline runs. + `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 @@ -82,29 +82,14 @@ 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. -- `scripts/advisory-early-warning-scan.mts --nvd-records ` attaches - 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. +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 @@ -131,66 +116,33 @@ 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. +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. +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). +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. + 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 f04a61c8743..27109f7b098 100755 --- a/scripts/advisory-early-warning-scan.mts +++ b/scripts/advisory-early-warning-scan.mts @@ -67,22 +67,35 @@ function loadNvdResponses(nvdRecordsPath: string): unknown[] { function loadInventoryOverride(inventoryPath: string): InventoryEntry[] { const parsed = JSON.parse(fs.readFileSync(inventoryPath, "utf-8")) as unknown; - const entries = Array.isArray(parsed) ? parsed : []; - const inventory: InventoryEntry[] = []; - for (const entry of entries) { - if (typeof entry !== "object" || entry === null) continue; + 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) continue; - if (typeof version !== "string" || version.length === 0) continue; + 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; - inventory.push({ + return { name, version, origin: typeof origin === "string" && origin.length > 0 ? origin : inventoryPath, - }); - } - return inventory; + }; + }); } function describeNvd(signal: NvdAnnotatedSignal): string { diff --git a/test/nvd-reconciliation.test.ts b/test/nvd-reconciliation.test.ts index 3ba7166c840..61b7c3a0703 100644 --- a/test/nvd-reconciliation.test.ts +++ b/test/nvd-reconciliation.test.ts @@ -519,6 +519,22 @@ describe("advisory early-warning CLI --nvd-records", () => { } }); + 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 { From 63efa7f9db92ff93f677bd8c8eacaadf0ae37100 Mon Sep 17 00:00:00 2001 From: Dongni-Yang Date: Fri, 24 Jul 2026 15:47:10 +0800 Subject: [PATCH 7/8] chore: apply biome format to the inventory test fixture Refs #7338 Signed-off-by: Dongni-Yang Co-Authored-By: Claude Fable 5 --- test/nvd-reconciliation.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/nvd-reconciliation.test.ts b/test/nvd-reconciliation.test.ts index 61b7c3a0703..57cd334b5e6 100644 --- a/test/nvd-reconciliation.test.ts +++ b/test/nvd-reconciliation.test.ts @@ -525,7 +525,10 @@ describe("advisory early-warning CLI --nvd-records", () => { const inventoryPath = path.join(tempRoot, "inventory.json"); fs.writeFileSync( inventoryPath, - JSON.stringify([{ name: "fast-uri", version: "3.1.2" }, { name: "", version: "1.0.0" }]), + 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"/, From 389a28293ecd462479385aa503eb9f327f8a2b3f Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Fri, 24 Jul 2026 10:35:47 -0700 Subject: [PATCH 8/8] fix(security): traverse nested NVD configuration nodes Signed-off-by: Apurv Kumaria --- scripts/lib/nvd-reconciliation.mts | 33 +++++++++++++++++++----------- test/nvd-reconciliation.test.ts | 32 +++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 12 deletions(-) diff --git a/scripts/lib/nvd-reconciliation.mts b/scripts/lib/nvd-reconciliation.mts index 6877572e3d7..3c87bb013b0 100644 --- a/scripts/lib/nvd-reconciliation.mts +++ b/scripts/lib/nvd-reconciliation.mts @@ -54,19 +54,28 @@ function collectVulnerableCpeCriteria(cve: Record): string[] { if (typeof configuration !== "object" || configuration === null) continue; const nodes = (configuration as Record).nodes; if (!Array.isArray(nodes)) continue; - for (const node of nodes) { + 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; - const matches = (node as Record).cpeMatch; - if (!Array.isArray(matches)) continue; - 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); + 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); + } } } } diff --git a/test/nvd-reconciliation.test.ts b/test/nvd-reconciliation.test.ts index 57cd334b5e6..89ff851142c 100644 --- a/test/nvd-reconciliation.test.ts +++ b/test/nvd-reconciliation.test.ts @@ -256,6 +256,38 @@ describe("NVD 2.0 record parsing", () => { "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", () => {