vigievuln 1.3.0 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,6 +4,7 @@ const fs = require('node:fs');
4
4
  const path = require('node:path');
5
5
  const crypto = require('node:crypto');
6
6
  const { makeDepRecord } = require('../dep-record');
7
+ const {IMAGE_COMPONENT_SCOPE,imageComponentRole,imageComponentSource} = require('./component-scope');
7
8
  const { openArtifact } = require('./index');
8
9
  const { collectInstalledApplications } = require('./applications');
9
10
  const { collectSystemInventory, assessSystemInventory, syncSystemAdvisories } = require('../system-inventory');
@@ -49,10 +50,11 @@ function systemDep(pkg, targetId, distribution) {
49
50
  async function inventoryTarget(target, options = {}) {
50
51
  const system = await collectSystemInventory(target.root, options);
51
52
  const applications = await collectInstalledApplications(target.root, options);
53
+ const imageJs = options.imageRetire ? await require('./retire').collectImageJs(target.root,options,system.packages.flatMap(p=>p.ownedPaths || [])) : null;
52
54
  const binaries = await require('../codecs/binary.codec').collect(target.root, { ...options, defaultExcludes: false, srcRoot: target.root });
53
55
  const order = (a, b) => JSON.stringify([a.ecosystem, a.manager, a.namespace, a.name, a.version, a.architecture, a.manifestPath, a.manifestPaths]).localeCompare(JSON.stringify([b.ecosystem, b.manager, b.namespace, b.name, b.version, b.architecture, b.manifestPath, b.manifestPaths]));
54
56
  const packages = portable(system.packages, target.root).map(p => ({ ...p, ...(p.ownedPaths ? { ownedPaths: [...p.ownedPaths].sort() } : {}) })).sort(order);
55
- const appDeps = portable([...applications.deps.values(), ...binaries.deps.values()], target.root).sort(order);
57
+ const appDeps = portable([...applications.deps.values(), ...binaries.deps.values(), ...(imageJs?.deps || [])], target.root).sort(order);
56
58
  const id = target.kind === 'rootfs' && target.metadata.format === 'directory'
57
59
  ? `rootfs-inventory:sha256:${sha(JSON.stringify({ distribution: system.distribution, packages, deps: appDeps }))}` : target.id;
58
60
  const owners = new Map();
@@ -78,9 +80,11 @@ async function inventoryTarget(target, options = {}) {
78
80
  const owned = evidence && !aggregate ? owners.get(pathKey(evidence)) : null;
79
81
  return qualify(owned?.length ? { ...d, osPackageOwners: owned } : d, id);
80
82
  })];
81
- const warnings = portable(normalizeWarnings([...(system.warnings || []), ...applications.warnings, ...binaries.warnings,
83
+ for(const dep of deps){dep.imageRole=imageComponentRole(dep);dep.imageSource=imageComponentSource(dep);dep.scope=dep.imageRole==='transitive'?'transitive':'runtime';}
84
+ const warnings = portable(normalizeWarnings([...(system.warnings || []), ...applications.warnings, ...binaries.warnings, ...(imageJs?.warnings || []),
82
85
  ...(target.metadata.warnings || [])]), target.root);
83
86
  const coverage = coverageRecords(system.coverage, id, 'inventory');
87
+ if(imageJs)coverage.push({...imageJs.coverage,artifactTargetId:id});
84
88
  coverage.push({ artifactTargetId: id, capability: 'inventory', collector: 'installed-applications',
85
89
  execution: applications.warnings.length ? 'partial' : 'completed', result: 'indeterminate', count: applications.deps.size });
86
90
  coverage.push({ artifactTargetId: id, capability: 'inventory', collector: 'native-binaries',
@@ -90,7 +94,7 @@ async function inventoryTarget(target, options = {}) {
90
94
  const acquisition = options.registry ? { kind: 'registry', reference: source } : {
91
95
  kind: target.metadata.format === 'directory' ? 'rootfs-directory' : target.metadata.format === 'oci-layout' && target.metadata.source && fs.statSync(target.metadata.source).isDirectory() ? 'oci-layout' : 'archive', source,
92
96
  };
93
- return { id, kind: target.kind, metadata: { ...target.metadata, source, acquisition, definitions: [], definitionDiscovery: {status:'not-supplied'} },
97
+ return { id, kind: target.kind, metadata: { ...target.metadata, componentScope:IMAGE_COMPONENT_SCOPE, source, acquisition, definitions: [], definitionDiscovery: {status:'not-supplied'} },
94
98
  evidence: 'content-inventory', inventoryAt: new Date().toISOString(), distribution: system.distribution,
95
99
  packages, deps, coverage, warnings, componentCount: deps.length };
96
100
  }
@@ -134,7 +138,7 @@ function validateSnapshot(doc) {
134
138
  }
135
139
  function readSnapshot(file, options = {}) {
136
140
  if (fs.statSync(file).size > (options.maxSnapshotBytes ?? 128 * 1024 * 1024)) throw Error('artifact inventory exceeds configured size limit');
137
- return validateSnapshot(JSON.parse(fs.readFileSync(file, 'utf8'))).map(t => ({ ...t, evidence: 'cached-inventory', originalEvidence: t.evidence }));
141
+ return validateSnapshot(JSON.parse(fs.readFileSync(file, 'utf8'))).map(t => ({ ...require('./inventory-scope').applyComponentScope(t), evidence: 'cached-inventory', originalEvidence: t.originalEvidence || t.evidence }));
138
142
  }
139
143
  async function writeSnapshot(file, targets) {
140
144
  const absolute = path.resolve(file);
@@ -154,16 +158,17 @@ async function acquireInventories(input, options = {}) {
154
158
  if (options.registry && options.offline) {
155
159
  const saved = cache.get('image-inventory', cacheKey) || cache.get('image-inventory', legacyCacheKey);
156
160
  if (!saved?.value || saved.value.schema !== SNAPSHOT_SCHEMA) throw Error('image inventory is not cached; import an inventory/archive or prepare this reference online');
157
- const targets = validateSnapshot(saved.value);
158
- return targets.map(target => ({ ...target, evidence: 'cached-inventory', originalEvidence: target.evidence,
161
+ const targets = validateSnapshot(saved.value).map(require('./inventory-scope').applyComponentScope);
162
+ return targets.map(target => ({ ...target, evidence: 'cached-inventory', originalEvidence: target.originalEvidence || target.evidence,
159
163
  warnings: [...target.warnings, { type: 'cached-image-resolution', severity:'info', capability: 'sources', message: 'Using the prepared image digest and inventory offline; the registry tag is not re-resolved in this mode.' }] }));
160
164
  }
161
165
  const persist = targets => {
166
+ targets = targets.map(require('./inventory-scope').applyComponentScope);
162
167
  validateSnapshot(createSnapshot(targets));
163
168
  if (cache) cache.put('image-inventory', cacheKey, createSnapshot(targets));
164
169
  return targets;
165
170
  };
166
- if (cache && !options.forceUpdate && !require('../cache-policy').shouldForceUpdate()) {
171
+ if (cache && !options.imageRetire && !options.forceUpdate && !require('../cache-policy').shouldForceUpdate()) {
167
172
  let targets;
168
173
  try {
169
174
  const saved = cache.get('image-inventory', cacheKey) || cache.get('image-inventory', legacyCacheKey);
@@ -171,16 +176,19 @@ async function acquireInventories(input, options = {}) {
171
176
  } catch { /* Invalid snapshots must be rebuilt from verified content online. */ }
172
177
  const digest = targets?.[0]?.metadata?.acquisition?.indexDigest;
173
178
  // Publisher SBOMs can be updated independently of the image digest.
174
- if (digest && targets.every(t => t.evidence === 'content-inventory' && t.metadata?.acquisition?.indexDigest === digest)) {
179
+ const scoped = targets?.map(require('./inventory-scope').applyComponentScope);
180
+ // Older APK inventories discarded the maintainer needed to identify vendor NGINX.
181
+ const vendorMetadataComplete=scoped?.every(t=>(t.packages||[]).every(p=>p.manager!=='apk'||p.sourceName!=='nginx'||p.packageMetadata));
182
+ if (digest && vendorMetadataComplete && scoped.every(t => t.evidence === 'content-inventory' && t.metadata?.componentScope === require('./component-scope').IMAGE_COMPONENT_SCOPE && !t.warnings.some(w => w.reason === require('./inventory-scope').SCOPE_REASON) && t.metadata?.acquisition?.indexDigest === digest)) {
175
183
  const current = ref.reference.includes(':') ? ref.reference : await require('../image-registry').fetchRegistryDigest(input,
176
184
  {...options, fetcher:options.registryFetcher || options.fetcher, limits:options.registryLimits});
177
- if (current === digest) return targets.map(target => ({...target, evidence:'cached-inventory', originalEvidence:target.evidence}));
185
+ if (current === digest) return scoped.map(target => ({...target, evidence:'cached-inventory', originalEvidence:target.originalEvidence || target.evidence}));
178
186
  }
179
187
  }
180
188
  let registry = null, opened = null, sbomAttempt = null;
181
189
  try {
182
190
  if (options.registry) {
183
- if (options.preferSbom) {
191
+ if (options.preferSbom && !options.imageRetire) {
184
192
  try {
185
193
  const discovered = await require('../image-registry').fetchRegistrySboms(input, { ...options, fetcher: options.registryFetcher || options.fetcher, limits: options.registryLimits });
186
194
  // Never drop image platforms when only a subset has publisher metadata.
@@ -224,18 +232,18 @@ async function acquireInventories(input, options = {}) {
224
232
 
225
233
  async function assessInventories(targets, options = {}) {
226
234
  options.onArtifactProgress?.({stage:'Component identities'});
227
- targets=targets.map(target=>JSON.parse(JSON.stringify(target)));
235
+ targets=targets.map(target=>require('./inventory-scope').applyComponentScope(target,{checkPolicy:false}));
228
236
  for(const target of targets){
229
237
  for(const pkg of target.packages){const origin=require('../system-inventory/distribution-sources').identifyPackageOrigin(pkg,options);if(origin)pkg.packageOrigin=origin;}
230
238
  for(const dep of target.deps){const origin=require('../system-inventory/distribution-sources').identifyPackageOrigin(dep,options);if(origin)dep.packageOrigin=origin;}
231
239
  const identity=await require('./go-main-identity').resolveGoMainIdentities(target,options);
232
- for(const dep of identity.deps){const qualified=qualify(dep,target.id);if(!target.deps.some(d=>d.coordKey===qualified.coordKey))target.deps.push(qualified);}
240
+ for(const dep of identity.deps){const qualified=qualify({...dep,imageRole:'direct',scope:'runtime'},target.id);if(!target.deps.some(d=>d.coordKey===qualified.coordKey))target.deps.push(qualified);}
233
241
  target.coverage.push({...identity.coverage,artifactTargetId:target.id,capability:'inventory'});
234
242
  target.warnings.push(...identity.warnings);
235
243
  }
236
244
  const resolvedDeps = new Map(), cveMatches = [], warnings = [], artifacts = [], warmed = new Set();
237
245
  const nativeDeps=new Map();
238
- for(const target of targets)for(const dep of target.deps||[])if(dep.ecosystem!=='binary' && (!dep.osPackageOwners?.length || dep.binaryEvidence))nativeDeps.set(dep.coordKey,dep);
246
+ for(const target of targets)for(const dep of target.deps||[])if(dep.ecosystem!=='binary' && dep.installEvidence?.source!=='retire' && (!dep.osPackageOwners?.length || dep.binaryEvidence))nativeDeps.set(dep.coordKey,dep);
239
247
  let native={matches:[],unknown:[],coverage:{status:'not-applicable'}},nativePreparation={sources:[],coverage:[],warnings:[]};
240
248
  if(nativeDeps.size){
241
249
  const nativeOptions={...options};
@@ -274,7 +282,7 @@ async function assessInventories(targets, options = {}) {
274
282
  }
275
283
  for(const warning of nativePreparation.warnings)targetWarnings.push(typeof warning==='string'?{type:'source-unavailable',capability:'sources',message:warning}:{capability:'sources',...warning});
276
284
  const nativeUnknown=native.unknown.filter(item=>!item.artifactTargetId||item.artifactTargetId===target.id);
277
- if(nativeUnknown.length){coverage.push({artifactTargetId:target.id,capability:'sources',collector:'native-comparisons',execution:'partial',result:'indeterminate',count:nativeUnknown.length});targetWarnings.push({type:'source-unavailable',severity:'info',capability:'sources',message:`${nativeUnknown.length} native advisory package/version comparison(s) are undecidable.`});}
285
+ if(nativeUnknown.length){coverage.push({artifactTargetId:target.id,capability:'sources',collector:'native-comparisons',execution:'completed',result:'indeterminate',affectsCompleteness:false,affectsAssessment:true,count:nativeUnknown.length});targetWarnings.push({...require('../diagnostics').advisoryEvidenceDiagnostic(nativeUnknown),capability:'sources'});}
278
286
  if (target.packages.length && options.osv === false) {
279
287
  coverage.push({ artifactTargetId: target.id, capability: 'advisories', collector: 'system-osv', execution: 'not-applicable', result: 'not-consulted', expected:false, reason: 'OSV is excluded by source configuration.' });
280
288
  } else if (target.packages.length) {
@@ -310,8 +318,12 @@ async function assessInventories(targets, options = {}) {
310
318
  coverage.push(...coverageRecords(distribution.coverage,target.id,'advisories'));
311
319
  targetWarnings.push(...normalizeWarnings(distribution.warnings,'advisories'));
312
320
  for(const match of distribution.matches){const dep=systemDep(match.dep,target.id,target.distribution);cveMatches.push({...match,dep:resolvedDeps.get(dep.coordKey)||dep});}
321
+ const imageJsAssessment=await require('./retire').assessImageJs(target,options);
322
+ cveMatches.push(...imageJsAssessment.matches);
323
+ coverage.push(imageJsAssessment.coverage);
324
+ targetWarnings.push(...imageJsAssessment.warnings);
313
325
  options.onArtifactProgress?.({stage:'Application advisories'});
314
- const appDeps = new Map(target.deps.filter(d => d.ecosystem !== 'system' && d.ecosystem !== 'binary' && (!d.osPackageOwners?.length || !!d.binaryEvidence)).map(d => [d.coordKey, d]));
326
+ const appDeps = new Map(target.deps.filter(d => d.ecosystem !== 'system' && d.ecosystem !== 'binary' && d.installEvidence?.source !== 'retire' && (!d.osPackageOwners?.length || !!d.binaryEvidence)).map(d => [d.coordKey, d]));
315
327
  if (appDeps.size && options.osv === false) {
316
328
  coverage.push({ artifactTargetId: target.id, capability:'advisories',collector:'osv-application',execution:'not-applicable',result:'not-consulted',expected:false,reason:'OSV is excluded by source configuration.' });
317
329
  } else if (appDeps.size) {
@@ -351,7 +363,7 @@ async function assessInventories(targets, options = {}) {
351
363
  message:`${path} is covered by its installed OS package ${owner.name}@${owner.version}; no independent Maven identity is declared.`})));
352
364
  }
353
365
  for (const check of coverage) {
354
- if (['completed', 'not-applicable'].includes(check.execution)) continue;
366
+ if (check.affectsCompleteness === false || ['completed', 'not-applicable'].includes(check.execution)) continue;
355
367
  if (check.collector==='native-binaries' || check.collector==='native-comparisons' || check.collector==='go-main-identity' || check.collector==='system-osv-vendor-scope' || check.issue==='missing-source') continue;
356
368
  if (targetWarnings.some(w => w.capability === check.capability && !require('../diagnostics').isInformational(w))) continue;
357
369
  targetWarnings.push({ type: check.capability === 'inventory' ? 'dependency-coverage' : 'source-unavailable',
@@ -362,7 +374,7 @@ async function assessInventories(targets, options = {}) {
362
374
  originalEvidence: target.originalEvidence, distribution: target.distribution, inventoryAt: target.inventoryAt,
363
375
  componentCount: target.deps.length, coverage, advisoryObservations:distribution.observations, components: target.deps.map(d => ({ ecosystem: d.ecosystem, packageType: d.packageType,
364
376
  namespace: d.namespace, name: d.name, version: d.version, sourceName:d.sourceName || null, sourceVersion:d.sourceVersion || null, packageOrigin:d.packageOrigin || null, architecture: d.architecture, artifactPath: d.artifactPath,
365
- provenance: d.provenance, coordKey: d.coordKey, binaryEvidence:d.binaryEvidence, osPackageOwners: d.osPackageOwners || [],
377
+ provenance: d.provenance, imageRole:d.imageRole || null, imageSource:d.imageSource || imageComponentSource(d), installEvidence:d.installEvidence, manager:d.manager, coordKey: d.coordKey, binaryEvidence:d.binaryEvidence, osPackageOwners: d.osPackageOwners || [],
366
378
  purl: require('../purl').purlFor(d) })) });
367
379
  }
368
380
  const combined=require('../merge-sources').mergeBySource(cveMatches,native.matches);
@@ -374,9 +386,15 @@ async function assessInventories(targets, options = {}) {
374
386
  const matches = cveMatches.filter(m => m.dep?.artifactTargetId === artifact.id);
375
387
  options.onArtifactProgress?.({stage:'CVE enrichment'});
376
388
  const enrichment = await require('./enrichment').enrichArtifactFindings(matches, options);
377
- artifact.coverage.push(...enrichment.coverage.map(c => ({ ...c, artifactTargetId: artifact.id })));
378
- warnings.push(...enrichment.warnings.map(w => ({ ...w, artifactTargetId: artifact.id })));
389
+ const recordSources = new Set(['nvd', 'euvd', 'euvd-details']);
390
+ artifact.coverage.push(...enrichment.coverage.map(c => ({ ...c, artifactTargetId: artifact.id,
391
+ ...(recordSources.has(c.collector) ? { affectsCompleteness:false,
392
+ diagnostics:enrichment.warnings.filter(w => w.source === c.collector) } : {}) })));
393
+ warnings.push(...enrichment.warnings.filter(w => !recordSources.has(w.source)).map(w => ({ ...w, artifactTargetId: artifact.id })));
379
394
  }
395
+ const recordSummary = require('../cve-record-coverage').summarizeCveRecords(cveMatches,
396
+ { ...options, coverage: artifacts.flatMap(a => a.coverage) });
397
+ if (recordSummary.warning) warnings.push(recordSummary.warning);
380
398
  require('../priority').attachPriority(cveMatches);
381
399
  const diagnostics=require('../diagnostics').partitionDiagnostics(warnings);
382
400
  return { resolvedDeps, cveMatches: require('../finding-summary').uniqueFindings(cveMatches), ...diagnostics, artifacts };
@@ -387,10 +405,10 @@ function incompleteCapabilities(result, required = ['inventory', 'advisories', '
387
405
  for (const target of result.artifacts) {
388
406
  for (const capability of required) {
389
407
  if (capability === 'sources') {
390
- if (result.warnings.some(w => w.artifactTargetId === target.id && /source|osv/.test(w.type))) gaps.push({ target: target.id, capability });
408
+ if (result.warnings.some(w => w.affectsCompleteness !== false && w.artifactTargetId === target.id && /source|osv/.test(w.type))) gaps.push({ target: target.id, capability });
391
409
  } else {
392
410
  const records = target.coverage.filter(c => c.capability === capability);
393
- if (!records.length || records.some(c => !['completed', 'not-applicable'].includes(c.execution))) gaps.push({ target: target.id, capability });
411
+ if (!records.length || records.some(c => c.affectsCompleteness !== false && !['completed', 'not-applicable'].includes(c.execution))) gaps.push({ target: target.id, capability });
394
412
  }
395
413
  }
396
414
  }
package/lib/charts.js CHANGED
@@ -484,14 +484,14 @@ function emptyCard(id, title, note) {
484
484
  /**
485
485
  * Build the four-chart "Overview" row. Returns "" when there is nothing to plot.
486
486
  */
487
- function renderCharts(payload = {}, opts = {}) {
487
+ function renderChartsGroup(payload = {}, opts = {}) {
488
488
  // Injected by the report so this module needs no i18n dependency of its own; identity
489
489
  // by default, which keeps every existing caller and test rendering English.
490
490
  const t = typeof opts.t === "function" ? opts.t : EN_T;
491
491
  const prod = payload.prodMatches || [];
492
492
  const imageMatches = prod.filter(m => !!m.dep?.artifactTargetId);
493
493
  const sourceMatches = prod.filter(m => !m.dep?.artifactTargetId);
494
- const hasImages = imageMatches.length > 0 || (payload.artifacts || []).length > 0;
494
+ const hasImages = !!payload.hasImages || imageMatches.length > 0 || (payload.artifacts || []).length > 0;
495
495
  const imageOnly = hasImages && !sourceMatches.length;
496
496
  const cweTitle = typeof opts.cweName === "function" ? opts.cweName : cweName;
497
497
  // Include direct application and source findings, plus image findings, in the
@@ -515,7 +515,7 @@ function renderCharts(payload = {}, opts = {}) {
515
515
  // themes and extensions count as the direct lane, their dependencies as indirect.
516
516
  const appChart = appScan ? mostVulnerableApplications(sourceMatches, applications, payload.coverage || [], { t }) : null;
517
517
 
518
- if (!(cwe.length || subs.length || scope.length || prio.length || unattr || components.length || (appChart && appChart.rows.length))) return "";
518
+ if (!hasImages && !payload.showEmpty && !(cwe.length || subs.length || scope.length || prio.length || unattr || components.length || (appChart && appChart.rows.length))) return "";
519
519
 
520
520
  const interactive = opts.interactive !== false; // copy button only in the interactive HTML
521
521
 
@@ -569,6 +569,23 @@ function renderCharts(payload = {}, opts = {}) {
569
569
  return `<section class="charts-row" aria-label="${esc(t("Overview charts"))}">${card1}${card2}${card3}${card4}</section>`;
570
570
  }
571
571
 
572
+ // Source and image occurrences must stay in separate overview rows, even when
573
+ // the same package and advisory occur in both inventories.
574
+ function renderCharts(payload = {}, opts = {}) {
575
+ const matches = payload.prodMatches || [];
576
+ const source = matches.filter(m => !m.dep?.artifactTargetId);
577
+ const images = matches.filter(m => !!m.dep?.artifactTargetId);
578
+ const hasImages = !!payload.hasImages || images.length > 0 || (payload.artifacts || []).length > 0;
579
+ const sourceRow = payload.hasSourceProject === false ? "" : renderChartsGroup({...payload, prodMatches:source, artifacts:[], hasImages:false, showEmpty:hasImages && payload.hasSourceProject === true}, opts);
580
+ const translate = typeof opts.t === 'function' ? opts.t : EN_T;
581
+ const labelledSource = sourceRow ? `<h2 class="charts-heading">${esc(translate('Project overview'))}</h2>${sourceRow}` : '';
582
+ if (!hasImages) return labelledSource;
583
+ const imageRow = renderChartsGroup({...payload, prodMatches:images, applications:[], moduleNames:new Map(), descriptorCount:0, hasImages:true}, opts)
584
+ .replace(/id="chart-/g, 'id="image-chart-')
585
+ .replace(`aria-label="${esc(translate("Overview charts"))}"`, `aria-label="${esc(translate("Image overview charts"))}"`);
586
+ return labelledSource + `<h2 class="charts-heading">${esc(translate('Image overview'))}</h2>` + imageRow;
587
+ }
588
+
572
589
  module.exports = {
573
590
  cweByCriticality,
574
591
  findingsByImage,
package/lib/cli-image.js CHANGED
@@ -62,6 +62,8 @@ function makeCommand() {
62
62
  .option('--allow-insecure-http', 'allow HTTP to the configured advisory proxy for this invocation')
63
63
  .option('--registry', 'obtain input directly from an OCI registry; offline uses a prepared cached inventory')
64
64
  .option('--platform <os/arch[/variant]>', 'select an image platform; otherwise inspect all available platforms')
65
+ .option('--no-image-retire', 'disable RetireJS inspection of image contents')
66
+ .option('--image-retire', 'scan bundled JavaScript in image contents with RetireJS (excludes package stores)', false)
65
67
  .option('--prefer-sbom', 'prefer publisher SBOMs when associated with the selected images; signatures remain unverified')
66
68
  .option('--registry-auth <file>', 'JSON credentials {username,password,token,authOrigins}; never invokes credential helpers')
67
69
  .option('--insecure', 'allow HTTP registry endpoints explicitly')
@@ -156,6 +158,9 @@ async function run(args, injected = {}) {
156
158
  }
157
159
  if (opts.exportInventory) await writeSnapshot(opts.exportInventory, targets);
158
160
  const result = await assessInventories(targets, options);
161
+ result.warnings.push(...require('./image-references').unpinnedImageWarnings([
162
+ ...imageReferences,...(options.registry?[{reference:input}]:[]),
163
+ ]));
159
164
  if (opts.prepareCache) {
160
165
  const gaps = incompleteCapabilities(result, ['advisories', 'sources']);
161
166
  if (gaps.length) console.warn('⚠ Prepared cache has incomplete advisory or source coverage; review the scan notices.');
@@ -0,0 +1,109 @@
1
+ 'use strict';
2
+ // Record retrieval is distinct from dependency/advisory discovery. These facts
3
+ // describe already identified CVEs and must not invalidate inventory coverage.
4
+ const {failureKey}=require('./providers/common');
5
+ const recordSources=new Set(['nvd','euvd','euvd-details']);
6
+ const cveIds=cve=>[...new Set([cve?.id,...(cve?.aliases||[]),...(cve?.upstream||[])]
7
+ .filter(id=>typeof id==='string' && /^CVE-\d{4}-\d{4,}$/i.test(id)).map(id=>id.toUpperCase()))];
8
+ function reasonOf(value,fallback='unavailable') {
9
+ const text=String(value?.reason||value?.failure?.reason||value||'');
10
+ const status=value?.failure?.status || value?.statusCode || (typeof value?.status==='number'?value.status:null);
11
+ if(status===429 || /429|rate.limit/i.test(text))return 'rate limit';
12
+ if(/offline/i.test(text))return 'offline';
13
+ if(/disabled|excluded/i.test(text))return 'disabled';
14
+ if(/not.consulted/i.test(text))return 'not consulted';
15
+ if(/no.match|not.listed|not.found|404/i.test(text))return 'not listed';
16
+ if(/timeout|timed.out|ETIMEDOUT/i.test(text))return 'timeout';
17
+ if(status===403 || /403|forbidden/i.test(text))return 'access denied';
18
+ if(/invalid|malformed|mismatch/i.test(text))return 'invalid response';
19
+ if(/budget|request.limit/i.test(text))return 'request limit';
20
+ if(/stale|freshness|timestamp/i.test(text))return 'freshness unconfirmed';
21
+ const http=/HTTP\s*(\d{3})/i.exec(text);if(http)return `HTTP ${http[1]}`;
22
+ if(/network|unreachable|ENOTFOUND|ECONN/i.test(text))return 'network error';
23
+ return fallback;
24
+ }
25
+ function summarizeCveRecords(matches=[],opts={}) {
26
+ const selected=opts.enrich;
27
+ const enabled=name=>opts[name]!==false && (!Array.isArray(selected)||selected.includes(name));
28
+ const active={nvd:enabled('nvd'),euvd:enabled('euvd')};
29
+ const byId=new Map(),keys=new Set();
30
+ const consultations=opts.coverage||[];
31
+ for(const check of consultations)if(recordSources.has(check.collector))for(const key of check.requestKeys||[])keys.add(key);
32
+ function store(id,source,state){
33
+ if(!byId.has(id))byId.set(id,{id});
34
+ const record=byId.get(id),old=record[source];
35
+ // Different components can reference the same CVE: one usable record covers it.
36
+ const rank=s=>s.status==='available'?(s.stale?3:4):s.status==='no-match'?2:1;
37
+ const failures=[...new Set([...(old?.refreshFailureReasons||[]),...(state.refreshFailed?[state.reason||'unavailable']:[])])].sort();
38
+ const best=!old || rank(state)>rank(old)?state:old;
39
+ record[source]={...best,...(failures.length?{refreshFailed:true,refreshFailureReasons:failures}:{})};
40
+ }
41
+ for(const match of matches){const cve=match.cve||{},ids=cveIds(cve);
42
+ for(const id of ids){
43
+ const evidence=(cve.cveEvidence||[]).find(e=>String(e.id).toUpperCase()===id)||{};
44
+ const nvd=evidence.nvdRecordEvidence || (String(cve.id).toUpperCase()===id?cve.nvdRecordEvidence:null);
45
+ const nvdRecord=cve.nvdEvidence?.records?.some(r=>String(r.id).toUpperCase()===id);
46
+ const euvdEvidence=evidence.euvdDetailsEvidence || (ids.length===1?cve.euvdDetailsEvidence:null)||{};
47
+ const mapping=evidence.euvdEvidence || (ids.length===1?cve.euvdEvidence:null)||{};
48
+ const detail=evidence.euvdDetails || (ids.length===1?cve.euvdDetails:null);
49
+ const hasDetail=!!detail && /^EUVD-\d{4}-\d+$/.test(detail.id||'');
50
+ const sourceFailure=consultations.find(c=>['euvd','euvd-details'].includes(c.collector)&&['failed','partial'].includes(c.execution));
51
+ const euvdReason=euvdEvidence.failure || euvdEvidence.reason || mapping.reason || (mapping.status==='no-match'?'not listed':null) || (opts.offline?'offline':sourceFailure?.reason);
52
+ const states={nvd:nvd || (nvdRecord?{status:'available'}:{status:'unavailable',reason:opts.offline?'offline':'not consulted'}),
53
+ euvd:{status:hasDetail?'available':mapping.status==='no-match'?'no-match':'unavailable',stale:!!euvdEvidence.stale,
54
+ refreshFailed:!!mapping.refreshFailed || (hasDetail && !!euvdEvidence.failure),...((!hasDetail || euvdEvidence.stale || mapping.refreshFailed)?{reason:reasonOf(euvdReason)}:{})}};
55
+ for(const source of ['nvd','euvd']){const state=states[source];store(id,source,active[source]?{...state,...((state.reason || state.status!=='available')?{reason:reasonOf(state.reason,state.status==='no-match'?'not listed':'unavailable')}:{})}:{status:'disabled',reason:'disabled'});}
56
+ if(active.nvd){keys.add(failureKey('nvd','cve',{id}));keys.add(failureKey('nvd','cve-mirror',{id}));}
57
+ const euvdId=detail?.id || evidence.euvd?.id || (ids.length===1?cve.euvd?.id:null);
58
+ if(active.euvd && euvdId)keys.add(failureKey('euvd','vulnerability',{id:euvdId}));
59
+ }
60
+ }
61
+ const records=[...byId.values()].sort((a,b)=>a.id.localeCompare(b.id));
62
+ const groups={neither:[],nvdOnly:[],euvdOnly:[],refreshFailed:[],stale:[]};
63
+ for(const r of records){const n=r.nvd.status==='available',e=r.euvd.status==='available';
64
+ if(!n&&!e)groups.neither.push(r);else if(n&&!e)groups.nvdOnly.push(r);else if(e&&!n)groups.euvdOnly.push(r);
65
+ if(r.nvd.refreshFailed||r.euvd.refreshFailed)groups.refreshFailed.push(r);
66
+ if(r.nvd.stale||r.euvd.stale)groups.stale.push(r);
67
+ }
68
+ const counts=Object.fromEntries(Object.entries(groups).map(([key,rows])=>[key,rows.length]));
69
+ const reasons=(rows,sources)=>{const tally=new Map();for(const r of rows){const values=new Set(sources.filter(s=>active[s]&&r[s].status!=='available').map(s=>`${s.toUpperCase()}: ${r[s].reason}`));for(const v of values)tally.set(v,(tally.get(v)||0)+1);}return [...tally].sort().map(([k,n])=>`${k} ${n}`).join(', ');};
70
+ const problem=(active.nvd||active.euvd) && (counts.neither || (active.euvd&&counts.nvdOnly) || (active.nvd&&counts.euvdOnly) || counts.refreshFailed || counts.stale);
71
+ const parts=[];
72
+ if(counts.neither)parts.push(`${counts.neither} CVE record(s) obtained from neither NVD nor EUVD (${reasons(groups.neither,['nvd','euvd'])})`);
73
+ if(active.euvd && counts.nvdOnly)parts.push(`${counts.nvdOnly} obtained from NVD only (${reasons(groups.nvdOnly,['euvd'])})`);
74
+ if(active.nvd && counts.euvdOnly)parts.push(`${counts.euvdOnly} obtained from EUVD only (${reasons(groups.euvdOnly,['nvd'])})`);
75
+ if(counts.refreshFailed){const why=[...new Set(groups.refreshFailed.flatMap(r=>['nvd','euvd'].flatMap(source=>(r[source].refreshFailureReasons||[]).map(reason=>`${source.toUpperCase()}: ${reason}`))))].sort();parts.push(`${counts.refreshFailed} CVE record update(s) failed (${why.join(', ')})`);}
76
+ if(counts.stale)parts.push(`${counts.stale} CVE(s) use cached records with unconfirmed freshness`);
77
+ const affected=new Set([...groups.neither,...(active.euvd?groups.nvdOnly:[]),...(active.nvd?groups.euvdOnly:[]),...groups.refreshFailed,...groups.stale].map(r=>r.id));
78
+ const warning=problem?{type:'cve-enrichment-summary',severity:'warning',affectsCompleteness:false,count:affected.size,consultedCount:records.length,
79
+ counts,records,requestKeys:[...keys],message:`CVE records: ${parts.join('; ')}. Existing findings are retained; this describes enrichment only.`}:null;
80
+ return {warning,records,requestKeys:[...keys],coverage:{capability:'enrichment',collector:'cve-records',affectsCompleteness:false,
81
+ execution:!active.nvd&&!active.euvd?'not-applicable':counts.neither?'partial':'completed',...(!active.nvd&&!active.euvd?{expected:false}:{}),count:records.length,available:records.length-counts.neither,missing:counts.neither}};
82
+ }
83
+ // Report-owned wording only: never translate or reproduce upstream text.
84
+ function formatCveRecordWarning(warning, locale='en') {
85
+ if(!String(locale).toLowerCase().startsWith('fr'))return warning.message || '';
86
+ const records=warning.records || [],counts=warning.counts || {};
87
+ const active=source=>records.some(r=>r[source] && r[source].status!=='disabled');
88
+ const names={ 'rate limit':'limite de débit',offline:'hors ligne',disabled:'désactivé','not consulted':'non consulté','not listed':'non répertorié',timeout:'délai dépassé','access denied':'accès refusé','invalid response':'réponse invalide','request limit':'limite de requêtes','freshness unconfirmed':'actualisation non confirmée','network error':'erreur réseau',unavailable:'indisponible' };
89
+ const label=reason=>names[reason] || (/^HTTP \d{3}$/.test(reason||'')?reason:'indisponible');
90
+ const reasons=(rows,sources)=>{
91
+ const tally=new Map();
92
+ for(const r of rows)for(const source of sources)if(active(source)&&r[source]?.status!=='available'){
93
+ const text=`${source.toUpperCase()} : ${label(r[source]?.reason)}`;tally.set(text,(tally.get(text)||0)+1);
94
+ }
95
+ return [...tally].sort().map(([text,n])=>`${text} ${n}`).join(', ');
96
+ };
97
+ const groups={neither:records.filter(r=>r.nvd?.status!=='available'&&r.euvd?.status!=='available'),nvdOnly:records.filter(r=>r.nvd?.status==='available'&&r.euvd?.status!=='available'),euvdOnly:records.filter(r=>r.euvd?.status==='available'&&r.nvd?.status!=='available')};
98
+ const parts=[];
99
+ if(counts.neither)parts.push(`${counts.neither} fiche(s) CVE obtenue(s) ni auprès de NVD ni auprès d’EUVD (${reasons(groups.neither,['nvd','euvd'])})`);
100
+ if(active('euvd')&&counts.nvdOnly)parts.push(`${counts.nvdOnly} obtenue(s) uniquement auprès de NVD (${reasons(groups.nvdOnly,['euvd'])})`);
101
+ if(active('nvd')&&counts.euvdOnly)parts.push(`${counts.euvdOnly} obtenue(s) uniquement auprès d’EUVD (${reasons(groups.euvdOnly,['nvd'])})`);
102
+ if(counts.refreshFailed){
103
+ const why=[...new Set(records.flatMap(r=>['nvd','euvd'].flatMap(source=>(r[source]?.refreshFailureReasons||[]).map(reason=>`${source.toUpperCase()} : ${label(reason)}`))))].sort();
104
+ parts.push(`${counts.refreshFailed} actualisation(s) de fiche CVE échouée(s) (${why.join(', ')})`);
105
+ }
106
+ if(counts.stale)parts.push(`${counts.stale} CVE utilisent des fiches en cache dont l’actualisation n’est pas confirmée`);
107
+ return `Fiches CVE : ${parts.join(' ; ')}. Les résultats existants sont conservés ; cet avertissement concerne uniquement l’enrichissement.`;
108
+ }
109
+ module.exports={summarizeCveRecords,formatCveRecordWarning,cveIds,recordSources};