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.
- package/CHANGELOG.md +14 -1052
- package/README.md +36 -69
- package/lib/artifacts/applications.js +6 -2
- package/lib/artifacts/component-scope.js +54 -0
- package/lib/artifacts/enrichment.js +1 -0
- package/lib/artifacts/inventory-scope.js +51 -0
- package/lib/artifacts/report-inventory.js +5 -1
- package/lib/artifacts/report.js +28 -8
- package/lib/artifacts/retire.js +80 -0
- package/lib/artifacts/scan.js +39 -21
- package/lib/charts.js +20 -3
- package/lib/cli-image.js +5 -0
- package/lib/cve-record-coverage.js +109 -0
- package/lib/cve-report.js +111 -29
- package/lib/diagnostics.js +14 -1
- package/lib/diff.js +0 -0
- package/lib/euvd.js +6 -2
- package/lib/finding-enrichment.js +8 -7
- package/lib/finding-summary.js +1 -1
- package/lib/i18n.js +16 -1
- package/lib/image-references.js +21 -1
- package/lib/json-export.js +6 -4
- package/lib/nvd.js +52 -16
- package/lib/providers/index.js +6 -6
- package/lib/report-notices.js +38 -3
- package/lib/retire.js +12 -10
- package/lib/source-health.js +47 -23
- package/lib/source-image-scan.js +1 -0
- package/lib/system-inventory/advisories.js +7 -6
- package/lib/system-inventory/alpine-tracker.js +5 -5
- package/lib/system-inventory/collect.js +1 -1
- package/lib/system-inventory/distribution-sources.js +2 -2
- package/lib/system-inventory/nginx-advisories.js +26 -8
- package/package.json +1 -1
- package/vigievuln.js +32 -16
package/lib/nvd.js
CHANGED
|
@@ -76,7 +76,17 @@ function writeCache(cveId, body, fetchedAt = Date.now(), cacheDir = path.dirname
|
|
|
76
76
|
const bytes=Buffer.from(JSON.stringify(body));
|
|
77
77
|
db.prepare(`INSERT INTO nvd_records(cve,kind,fetched_at,revision_ms,body_deflate,body_bytes,metadata_json) VALUES (?,?,?,?,?,?,?)
|
|
78
78
|
ON CONFLICT(cve,kind) DO UPDATE SET fetched_at=excluded.fetched_at,revision_ms=excluded.revision_ms,
|
|
79
|
-
body_deflate=excluded.body_deflate,body_bytes=excluded.body_bytes,metadata_json=excluded.metadata_json`).run(cveId,'live',fetchedAt,null,require('./advisory-compression').compress(bytes),bytes.length,JSON.stringify({schema:NVD_CACHE_SCHEMA,origin:require('./providers').resourceOrigin(),stale:provenance.stale === true}));
|
|
79
|
+
body_deflate=excluded.body_deflate,body_bytes=excluded.body_bytes,metadata_json=excluded.metadata_json`).run(cveId,'live',fetchedAt,null,require('./advisory-compression').compress(bytes),bytes.length,JSON.stringify({schema:NVD_CACHE_SCHEMA,origin:require('./providers').resourceOrigin(),stale:provenance.stale === true,...(provenance.refreshFailed ? {refreshFailed:true,reason:provenance.reason || 'refresh failed'} : {})}));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function responseEvidence(response, status) {
|
|
83
|
+
const headers = response.headers;
|
|
84
|
+
const stale = headers.get('x-fad-proxy') === 'stale';
|
|
85
|
+
const cause = headers.get('x-fad-proxy-reason') || headers.get('x-fad-proxy-stale-reason');
|
|
86
|
+
const refreshFailed = stale && cause === 'refresh-failed';
|
|
87
|
+
const code = Number(headers.get('x-fad-proxy-refresh-status'));
|
|
88
|
+
const reason = refreshFailed ? (Number.isInteger(code) && code >= 400 && code <= 599 ? `HTTP ${code}` : 'refresh failed') : 'stale proxy response';
|
|
89
|
+
return { status, stale, ...(stale ? {reason} : {}), ...(refreshFailed ? {refreshFailed:true} : {}) };
|
|
80
90
|
}
|
|
81
91
|
|
|
82
92
|
// A cached JSON null is an answered lookup with no NVD record, not a missing
|
|
@@ -89,6 +99,21 @@ function hasCachedAbsence(cveId, options = {}) {
|
|
|
89
99
|
} catch { return false; }
|
|
90
100
|
}
|
|
91
101
|
|
|
102
|
+
// Describe the same cached row readCache/hasCachedAbsence would use, without
|
|
103
|
+
// changing whether that row is eligible for enrichment.
|
|
104
|
+
function cachedEvidence(cveId, status, opts = {}) {
|
|
105
|
+
try {
|
|
106
|
+
const db = require('./cache-db').getCacheDb(opts.cacheDir || path.dirname(NVD_CACHE_DIR));
|
|
107
|
+
const row = db.prepare(`SELECT fetched_at,body_deflate,body_bytes,metadata_json FROM nvd_records WHERE cve=? ${opts.offline ? 'ORDER BY fetched_at DESC LIMIT 1' : "AND kind='live' LIMIT 1"}`).get(cveId);
|
|
108
|
+
if (!row) return { status, stale: false };
|
|
109
|
+
const metadata = JSON.parse(row.metadata_json);
|
|
110
|
+
const body = JSON.parse(require('./advisory-compression').decompress(row.body_deflate, row.body_bytes).toString('utf8'));
|
|
111
|
+
const ageFresh = row.fetched_at > 0 && row.fetched_at <= Date.now() && Date.now() - row.fetched_at < NVD_CACHE_TTL_MS;
|
|
112
|
+
const stale = metadata.stale === true || (!ageFresh && !require('./record-freshness').stableRecord('nvd', body, opts));
|
|
113
|
+
return { status, stale, ...(stale ? { reason: metadata.reason || (opts.offline ? 'offline' : 'stale cached response') } : {}), ...(metadata.refreshFailed === true ? { refreshFailed: true } : {}) };
|
|
114
|
+
} catch { return { status, stale: false }; }
|
|
115
|
+
}
|
|
116
|
+
|
|
92
117
|
function bestMetric(metrics) {
|
|
93
118
|
// NVD 2.0 returns metrics organised by version: cvssMetricV40, V31, V30, V2
|
|
94
119
|
const order = ["cvssMetricV40", "cvssMetricV31", "cvssMetricV30", "cvssMetricV2"];
|
|
@@ -220,8 +245,9 @@ async function fetchFromMirror(cveId, opts = {}) {
|
|
|
220
245
|
const extracted = extractFromNvdRecord(record);
|
|
221
246
|
if (!extracted) return { failed: true };
|
|
222
247
|
extracted.via = MIRROR_NAME;
|
|
223
|
-
|
|
224
|
-
|
|
248
|
+
const evidence = responseEvidence(m, 'available');
|
|
249
|
+
writeCache(cveId, extracted, require('./providers/common').responseFetchedAt(m), opts.cacheDir, evidence);
|
|
250
|
+
return { record: extracted, evidence };
|
|
225
251
|
} catch { return { failed: true }; }
|
|
226
252
|
}
|
|
227
253
|
|
|
@@ -243,10 +269,11 @@ async function fetchFromMirror(cveId, opts = {}) {
|
|
|
243
269
|
*/
|
|
244
270
|
async function fetchOne(cveId, opts = {}) {
|
|
245
271
|
const { fetcher = globalThis.fetch, verbose, offline, mirror = true } = opts;
|
|
272
|
+
const note = evidence => opts.onRecordEvidence?.(cveId, evidence);
|
|
246
273
|
const cached = readCache(cveId, offline, opts.cacheDir, opts);
|
|
247
|
-
if (cached !== null && cached !== undefined) return cached;
|
|
248
|
-
if (offline && hasCachedAbsence(cveId,{cacheDir:opts.cacheDir,offline:true})) {opts.onAbsent?.(cveId);return null;}
|
|
249
|
-
if (offline) return null;
|
|
274
|
+
if (cached !== null && cached !== undefined) { note(cachedEvidence(cveId, 'available', opts)); return cached; }
|
|
275
|
+
if (offline && hasCachedAbsence(cveId,{cacheDir:opts.cacheDir,offline:true})) {opts.onAbsent?.(cveId);note(cachedEvidence(cveId, 'no-match', opts));return null;}
|
|
276
|
+
if (offline) { note({ status: 'unavailable', reason: 'offline', stale: false }); return null; }
|
|
250
277
|
const headers = { "User-Agent": "vigievuln-nvd-enrich" };
|
|
251
278
|
const key = getNvdApiKey();
|
|
252
279
|
if (key) headers["apiKey"] = key;
|
|
@@ -258,14 +285,16 @@ async function fetchOne(cveId, opts = {}) {
|
|
|
258
285
|
let nvdReason;
|
|
259
286
|
try {
|
|
260
287
|
const r = await providers.getResource("nvd", "cve", { id: cveId }, { fetcher, headers, forceRefresh:opts.forceUpdate || require("./cache-policy").shouldForceUpdate(), ...deadline() });
|
|
261
|
-
if (r.status === 404) { writeCache(cveId, null, require('./providers/common').responseFetchedAt(r), opts.cacheDir,
|
|
288
|
+
if (r.status === 404) { const evidence = responseEvidence(r,'no-match'); writeCache(cveId, null, require('./providers/common').responseFetchedAt(r), opts.cacheDir, evidence); opts.onAbsent?.(cveId); note(evidence); return null; }
|
|
262
289
|
if (r.ok) {
|
|
263
290
|
let data;try { data=await r.json(); } catch { throw Object.assign(new Error('malformed NVD response'),{code:'NVD_INVALID_RESPONSE'}); }
|
|
264
|
-
if (Array.isArray(data?.vulnerabilities) && data.vulnerabilities.length===0 && data.totalResults===0) {writeCache(cveId,null,require('./providers/common').responseFetchedAt(r),opts.cacheDir);opts.onAbsent?.(cveId);return null;}
|
|
291
|
+
if (Array.isArray(data?.vulnerabilities) && data.vulnerabilities.length===0 && data.totalResults===0) {const evidence=responseEvidence(r,'no-match');writeCache(cveId,null,require('./providers/common').responseFetchedAt(r),opts.cacheDir,evidence);opts.onAbsent?.(cveId);note(evidence);return null;}
|
|
265
292
|
const record=Array.isArray(data?.vulnerabilities) && data.vulnerabilities.length===1 ? data.vulnerabilities[0]?.cve : null;
|
|
266
293
|
if (!record || String(record.id||'').toUpperCase()!==String(cveId).toUpperCase() || (data.totalResults!==undefined && data.totalResults!==1)) throw Object.assign(new Error('malformed NVD response'),{code:'NVD_INVALID_RESPONSE'});
|
|
267
294
|
let extracted;try { extracted=extractFromNvdRecord(record); } catch { throw Object.assign(new Error('malformed NVD response'),{code:'NVD_INVALID_RESPONSE'}); }
|
|
268
|
-
|
|
295
|
+
const evidence = responseEvidence(r,'available');
|
|
296
|
+
writeCache(cveId, extracted, require('./providers/common').responseFetchedAt(r), opts.cacheDir, evidence);
|
|
297
|
+
note(evidence);
|
|
269
298
|
return extracted;
|
|
270
299
|
}
|
|
271
300
|
nvdReason = `HTTP ${r.status}`;
|
|
@@ -275,19 +304,21 @@ async function fetchOne(cveId, opts = {}) {
|
|
|
275
304
|
if (verbose) require('./ui').networkNotice(` NVD ${nvdReason} for ${cveId}`);
|
|
276
305
|
opts.onFailure?.(cveId,nvdReason);
|
|
277
306
|
// A 4xx we caused (bad request…) is an answer, not an outage: nothing to fall back for.
|
|
278
|
-
if (health.classifyMissReason(nvdReason) === "answered") return null;
|
|
307
|
+
if (health.classifyMissReason(nvdReason) === "answered") { note({status:'unavailable',reason:nvdReason,stale:false}); return null; }
|
|
279
308
|
|
|
280
309
|
if (mirror) {
|
|
281
310
|
const got = await fetchFromMirror(cveId, { ...opts, fetcher });
|
|
282
311
|
if (got.record) {
|
|
283
312
|
if (verbose) require('./ui').networkNotice(` ${cveId} served by the NVD mirror (${MIRROR_NAME})`);
|
|
313
|
+
note(got.evidence);
|
|
284
314
|
return got.record;
|
|
285
315
|
}
|
|
286
316
|
}
|
|
287
317
|
const stale = require("./providers").hasHostedProxy() ? null : readCache(cveId, true, opts.cacheDir);
|
|
288
|
-
if (stale) return stale;
|
|
318
|
+
if (stale) { note({status:'available',stale:true,refreshFailed:true,reason:nvdReason}); return stale; }
|
|
289
319
|
// Neither NVD nor its mirror produced this record: a coverage hole, reported under NVD.
|
|
290
|
-
health.noteFanoutExhausted(url, [nvdReason]);
|
|
320
|
+
health.noteFanoutExhausted(url, [nvdReason], {requestKey:require('./providers/common').failureKey('nvd','cve',{id:cveId})});
|
|
321
|
+
note({status:'unavailable',reason:nvdReason,stale:false});
|
|
291
322
|
return null;
|
|
292
323
|
}
|
|
293
324
|
|
|
@@ -311,15 +342,18 @@ async function enrichMatches(matches, opts = {}) {
|
|
|
311
342
|
// actual work to do (the user's "stuck at OSV" complaint was caused by
|
|
312
343
|
// silent serial fetching with no progress output).
|
|
313
344
|
const byId = new Map();
|
|
345
|
+
const evidenceById = new Map();
|
|
346
|
+
const note = (id, evidence) => { evidenceById.set(id, evidence); opts.onRecordEvidence?.(id, evidence); };
|
|
314
347
|
const liveIds = [];
|
|
315
348
|
for (const cveId of uniqueCves) {
|
|
316
349
|
const cached = readCache(cveId, offline, opts.cacheDir, opts);
|
|
317
350
|
if (cached !== null && cached !== undefined) {
|
|
318
351
|
byId.set(cveId, cached);
|
|
352
|
+
note(cveId, cachedEvidence(cveId, 'available', opts));
|
|
319
353
|
continue;
|
|
320
354
|
}
|
|
321
|
-
if (offline && hasCachedAbsence(cveId,{cacheDir:opts.cacheDir,offline:true})) {opts.onAbsent?.(cveId);byId.set(cveId,null);continue;}
|
|
322
|
-
if (offline) { byId.set(cveId, null); continue; }
|
|
355
|
+
if (offline && hasCachedAbsence(cveId,{cacheDir:opts.cacheDir,offline:true})) {opts.onAbsent?.(cveId);byId.set(cveId,null);note(cveId,cachedEvidence(cveId,'no-match',opts));continue;}
|
|
356
|
+
if (offline) { byId.set(cveId, null); note(cveId,{status:'unavailable',reason:'offline',stale:false}); continue; }
|
|
323
357
|
liveIds.push(cveId);
|
|
324
358
|
}
|
|
325
359
|
|
|
@@ -339,7 +373,7 @@ async function enrichMatches(matches, opts = {}) {
|
|
|
339
373
|
while (pending.length) {
|
|
340
374
|
const id = pending.shift();
|
|
341
375
|
const got = await fetchFromMirror(id, opts);
|
|
342
|
-
if (got.record) { byId.set(id, got.record); mirrored++; }
|
|
376
|
+
if (got.record) { byId.set(id, got.record); note(id,got.evidence); mirrored++; }
|
|
343
377
|
else notMirrored.push(id);
|
|
344
378
|
if (onProgress) onProgress(mirrored, liveIds.length);
|
|
345
379
|
}
|
|
@@ -351,7 +385,7 @@ async function enrichMatches(matches, opts = {}) {
|
|
|
351
385
|
}
|
|
352
386
|
// NVD for whatever is left. When the mirror was already asked, NVD-only with the guard's
|
|
353
387
|
// retry schedule — it is the last source, it has to answer.
|
|
354
|
-
const nvdOpts = mirrorFirst ? {
|
|
388
|
+
const nvdOpts = { ...opts, ...(mirrorFirst ? { mirror: false } : {}), onRecordEvidence: note };
|
|
355
389
|
|
|
356
390
|
if (liveIds.length && !onProgress) {
|
|
357
391
|
const etaSec = Math.ceil((liveIds.length / burst) * (NVD_WINDOW_MS / 1000));
|
|
@@ -396,6 +430,8 @@ async function enrichMatches(matches, opts = {}) {
|
|
|
396
430
|
if (liveIds.length) printProgress(true);
|
|
397
431
|
|
|
398
432
|
for (const m of matches) {
|
|
433
|
+
const evidence = evidenceById.get(m.cve?.id);
|
|
434
|
+
if (evidence) m.cve.nvdRecordEvidence = { ...evidence };
|
|
399
435
|
const data = byId.get(m.cve?.id);
|
|
400
436
|
if (!data) continue;
|
|
401
437
|
// Merge: prefer NVD's official text + CVSS but keep what vigievuln/OSV already has
|
package/lib/providers/index.js
CHANGED
|
@@ -39,10 +39,10 @@ function providerKey(id, type, params, headers = {}) {
|
|
|
39
39
|
const scope = credentialScope(headers);
|
|
40
40
|
return provider.key ? provider.key(type, params, scope) : requestKey(id, type, params, scope);
|
|
41
41
|
}
|
|
42
|
-
function cachedResponse(entry, tag = "hit", store) {
|
|
42
|
+
function cachedResponse(entry, tag = "hit", store, refreshStatus) {
|
|
43
43
|
return new Response(store.readBody(entry), { status: 200,
|
|
44
44
|
headers: { ...responseHeaders(new Headers(entry.responseHeaders || {})), "content-type": entry.contentType || "application/octet-stream", "x-fad-proxy": tag,
|
|
45
|
-
"x-fad-proxy-fetched-at": new Date(entry.fetchedAt).toISOString() } });
|
|
45
|
+
"x-fad-proxy-fetched-at": new Date(entry.fetchedAt).toISOString(), ...(refreshStatus ? {"x-fad-proxy-reason":"refresh-failed", ...(Number.isInteger(refreshStatus) ? {"x-fad-proxy-refresh-status":String(refreshStatus)} : {})} : {}) } });
|
|
46
46
|
}
|
|
47
47
|
function persist(store, key, response, body, ttlMs) {
|
|
48
48
|
if (!store || !response.ok || body.byteLength > route.maxBodyBytes) return;
|
|
@@ -106,7 +106,7 @@ async function getResource(id, type, params, options = {}) {
|
|
|
106
106
|
if(entry.responseHeaders?.etag){directHeaders['if-none-match']=entry.responseHeaders.etag;conditional=true;}
|
|
107
107
|
else if(entry.responseHeaders?.['last-modified']){directHeaders['if-modified-since']=entry.responseHeaders['last-modified'];conditional=true;}
|
|
108
108
|
}
|
|
109
|
-
response = await fetcher(target, { ...request.init, headers: directHeaders,
|
|
109
|
+
response = await fetcher(target, { ...request.init, headers: directHeaders, [require('../source-health').REQUEST_KEY]: failureKey,
|
|
110
110
|
...(options.signal ? { signal: options.signal } : {}) });
|
|
111
111
|
}
|
|
112
112
|
if(response.status===304 && conditional) {
|
|
@@ -124,7 +124,7 @@ async function getResource(id, type, params, options = {}) {
|
|
|
124
124
|
}
|
|
125
125
|
if (entry && (response.status === 403 || response.status === 429 || response.status >= 500)) {
|
|
126
126
|
route.health?.markStale?.(id, new Date(entry.fetchedAt).toISOString(),{reason:'refresh-failed',requestKey:failureKey});
|
|
127
|
-
return cachedResponse(entry, "stale",store);
|
|
127
|
+
return cachedResponse(entry, "stale",store,response.status);
|
|
128
128
|
}
|
|
129
129
|
if (!response.ok || !store || options.noStore) return response;
|
|
130
130
|
if (response.headers.get('x-fad-proxy') === 'stale') return response;
|
|
@@ -136,8 +136,8 @@ async function getResource(id, type, params, options = {}) {
|
|
|
136
136
|
try { persist(store, key, response, body, Math.min(provider.ttlMs || policy.DEFAULT_TTL_MS, policy.DEFAULT_TTL_MS)); } catch { /* source result remains usable */ }
|
|
137
137
|
return response;
|
|
138
138
|
} catch (error) {
|
|
139
|
-
if (entry) { route.health?.markStale?.(id, new Date(entry.fetchedAt).toISOString(),{reason:'refresh-failed',requestKey:failureKey}); return cachedResponse(entry, "stale",store); }
|
|
140
|
-
if (route.health && !options.noSourceRetry && !options.urlOverride
|
|
139
|
+
if (entry) { route.health?.markStale?.(id, new Date(entry.fetchedAt).toISOString(),{reason:'refresh-failed',requestKey:failureKey}); return cachedResponse(entry, "stale",store,true); }
|
|
140
|
+
if (route.health && !options.noSourceRetry && !options.urlOverride) {
|
|
141
141
|
const { sourceForUrl } = require("../source-health");
|
|
142
142
|
const source = sourceForUrl(request.url);
|
|
143
143
|
if (source) route.health.markOutage(source.id, { url: request.url, code: error.code || error.message, requestKey: failureKey });
|
package/lib/report-notices.js
CHANGED
|
@@ -18,16 +18,51 @@ function partitionReportNotices(values=[]){
|
|
|
18
18
|
}
|
|
19
19
|
return {warnings,notices,freshness};
|
|
20
20
|
}
|
|
21
|
+
// The CVE-record enrichment summary is shared across scans, even when its
|
|
22
|
+
// underlying records include image findings. All other image diagnostics are
|
|
23
|
+
// identified by their explicit image identity or image-specific type.
|
|
24
|
+
function warningScope(item) {
|
|
25
|
+
if(item?.type==='cve-enrichment-summary')return 'global';
|
|
26
|
+
if(item?.artifactTargetId || item?.artifactTargetIds?.length || item?.type==='image-unpinned' || item?.type==='image-source-unavailable' || item?.type==='image-scan-failed')return 'image';
|
|
27
|
+
return 'project';
|
|
28
|
+
}
|
|
21
29
|
// Group causes for presentation, retaining every distinct location and detail.
|
|
22
30
|
// Raw diagnostics remain available in JSON; unrelated causes never collapse
|
|
23
31
|
// merely because they share a broad warning type.
|
|
24
32
|
function groupReportWarnings(values=[]) {
|
|
33
|
+
const imageIssues=[],other=[];
|
|
34
|
+
for(const w of values) {
|
|
35
|
+
if(w.type==='image-source-unavailable')imageIssues.push(...(w.diagnostics||[w]));
|
|
36
|
+
else if(w.type==='image-scan-failed' || (warningScope(w)==='image' && ['source-unavailable','source-stale','osv-coverage'].includes(w.type)))imageIssues.push(w);
|
|
37
|
+
else other.push(w);
|
|
38
|
+
}
|
|
39
|
+
if(imageIssues.length){
|
|
40
|
+
const byImage=new Map();
|
|
41
|
+
for(const w of imageIssues){
|
|
42
|
+
const entries=w.items?.length?w.items:w.artifactTargetIds?.length?w.artifactTargetIds.map(id=>({id,artifactTargetId:id})):[{id:w.artifactTargetId||w.manifestPath||w.source||'',...(w.artifactTargetId?{artifactTargetId:w.artifactTargetId}:{}),...(w.manifestPath&&!w.artifactTargetId?{pathItem:true}:{})}];
|
|
43
|
+
for(const entry of entries){
|
|
44
|
+
const item={...(typeof entry==='string'?{id:entry}:entry)};
|
|
45
|
+
if(w.artifactTargetId)item.artifactTargetId ||= w.artifactTargetId;
|
|
46
|
+
const key=item.artifactTargetId||item.id;
|
|
47
|
+
if(!byImage.has(key))byImage.set(key,{...item,id:key,details:new Set(),paths:new Set(),resources:new Set()});
|
|
48
|
+
const image=byImage.get(key);
|
|
49
|
+
image.details.add([w.source,item.detail||w.message].filter(Boolean).join(': '));
|
|
50
|
+
for(const path of item.manifestPaths||[])image.paths.add(path);
|
|
51
|
+
if(item.artifactTargetId && item.id!==key)image.resources.add(item.id);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const items=[...byImage.values()].map(({details,paths,resources,...item})=>({...item,detail:[...details].join('; '),manifestPaths:[...paths],resources:[...resources]}));
|
|
55
|
+
other.push({type:'image-source-unavailable',count:items.length,items,diagnostics:imageIssues,artifactTargetIds:[...new Set(items.map(x=>x.artifactTargetId).filter(Boolean))],
|
|
56
|
+
affectsCompleteness:imageIssues.some(w=>w.affectsCompleteness!==false),
|
|
57
|
+
message:'Some images or their advisory data are unavailable from public sources. See the affected images and reasons below.',_groupedDiagnostics:true});
|
|
58
|
+
}
|
|
59
|
+
values=other;
|
|
25
60
|
const groups=new Map(),out=[];
|
|
26
61
|
for(const item of values) {
|
|
27
62
|
if(item._groupedDiagnostics){out.push(item);continue;}
|
|
28
63
|
const perManifest=item.type==='no-lockfile'||item.type==='parse-error';
|
|
29
64
|
const cause=perManifest ? null : item.reason||item.code||item.message;
|
|
30
|
-
const key=JSON.stringify([item.type,item.severity,item.source||item.sourceId,item.capability,item.applicationId,cause,item.cause,item.status,item.refreshFailure]);
|
|
65
|
+
const key=JSON.stringify([warningScope(item),item.type,item.severity,item.source||item.sourceId,item.capability,item.applicationId,cause,item.cause,item.status,item.refreshFailure]);
|
|
31
66
|
if(!groups.has(key)){const group=[];groups.set(key,group);out.push(group);}
|
|
32
67
|
groups.get(key).push(item);
|
|
33
68
|
}
|
|
@@ -41,7 +76,7 @@ function groupReportWarnings(values=[]) {
|
|
|
41
76
|
for(const entry of entries){const key=JSON.stringify(entry);if(!seen.has(key)){seen.add(key);items.push(entry);}}
|
|
42
77
|
}
|
|
43
78
|
const {manifestPath,path,artifactTargetId,...first}=group[0];
|
|
44
|
-
return {...first,artifactTargetIds:[...new Set(group.
|
|
79
|
+
return {...first,artifactTargetIds:[...new Set(group.flatMap(w=>[w.artifactTargetId,...(w.artifactTargetIds||[])]).filter(Boolean))],message:messages.size===1?first.message:'',count:group.reduce((n,w)=>n+(w.count||1),0),items,_groupedDiagnostics:true};
|
|
45
80
|
});
|
|
46
81
|
}
|
|
47
|
-
module.exports={legacyFreshness,partitionReportNotices,groupReportWarnings};
|
|
82
|
+
module.exports={legacyFreshness,partitionReportNotices,groupReportWarnings,warningScope};
|
package/lib/retire.js
CHANGED
|
@@ -77,11 +77,11 @@ function writeCache(srcDir, body) {
|
|
|
77
77
|
{ _schema: RETIRE_CACHE_SCHEMA, _fetchedAt: Date.now(), body });
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
-
function cachedSignatureEntry(){
|
|
81
|
-
try{return require('./cache-repository').createCacheRepository(path.dirname(RETIRE_SIG_DIR)).get('auxiliary','retire-signatures')||null}
|
|
80
|
+
function cachedSignatureEntry(cacheDir){
|
|
81
|
+
try{return require('./cache-repository').createCacheRepository(cacheDir || path.dirname(RETIRE_SIG_DIR)).get('auxiliary','retire-signatures')||null}
|
|
82
82
|
catch{return null}
|
|
83
83
|
}
|
|
84
|
-
function cachedSignatures(){return cachedSignatureEntry()?.value || null}
|
|
84
|
+
function cachedSignatures(cacheDir){return cachedSignatureEntry(cacheDir)?.value || null}
|
|
85
85
|
|
|
86
86
|
function findRetireBin() {
|
|
87
87
|
const local = path.join(__dirname, "..", "node_modules", ".bin", "retire");
|
|
@@ -134,11 +134,11 @@ function findRetireLauncher() {
|
|
|
134
134
|
*/
|
|
135
135
|
async function warmRetireSignatures(opts = {}) {
|
|
136
136
|
const { verbose, force, offline } = opts;
|
|
137
|
-
const present = !!cachedSignatures();
|
|
137
|
+
const present = !!cachedSignatures(opts.cacheDir);
|
|
138
138
|
if (offline) return present ? { ok: true, cached: true }
|
|
139
139
|
: { ok: false, error: "offline: no local retire signatures" };
|
|
140
140
|
const hostedOnline = require("./providers").hasHostedProxy();
|
|
141
|
-
if (!force && !hostedOnline && present && require('./cache-policy').fresh(cachedSignatureEntry()?.fetchedAt)) {
|
|
141
|
+
if (!force && !hostedOnline && present && require('./cache-policy').fresh(cachedSignatureEntry(opts.cacheDir)?.fetchedAt)) {
|
|
142
142
|
if (verbose) console.log(`retire: signatures already present (${RETIRE_SIG_FILE})`);
|
|
143
143
|
return { ok: true, cached: true };
|
|
144
144
|
}
|
|
@@ -149,7 +149,7 @@ async function warmRetireSignatures(opts = {}) {
|
|
|
149
149
|
const text = await res.text();
|
|
150
150
|
const repo = JSON.parse(text);
|
|
151
151
|
if (!repo || typeof repo !== "object" || Array.isArray(repo)) throw new Error("invalid retire signatures");
|
|
152
|
-
require('./cache-repository').createCacheRepository(path.dirname(RETIRE_SIG_DIR)).put('auxiliary','retire-signatures',text);
|
|
152
|
+
require('./cache-repository').createCacheRepository(opts.cacheDir || path.dirname(RETIRE_SIG_DIR)).put('auxiliary','retire-signatures',text);
|
|
153
153
|
if (verbose) console.log('retire: signatures warmed into SQLite cache');
|
|
154
154
|
return { ok: true };
|
|
155
155
|
} catch (e) {
|
|
@@ -160,10 +160,11 @@ async function warmRetireSignatures(opts = {}) {
|
|
|
160
160
|
|
|
161
161
|
// Hosted online: always consult the proxy (including its stale/source-health signal).
|
|
162
162
|
// Offline: only report local availability, even with --force and a configured proxy.
|
|
163
|
-
async function ensureSignatures(
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
163
|
+
async function ensureSignatures(opts = {}) {
|
|
164
|
+
const { offline } = opts;
|
|
165
|
+
if (offline) return !!cachedSignatures(opts.cacheDir);
|
|
166
|
+
const r = await warmRetireSignatures(opts);
|
|
167
|
+
return !!r.ok || (!require('./providers').hasHostedProxy() && !!cachedSignatures(opts.cacheDir));
|
|
167
168
|
}
|
|
168
169
|
|
|
169
170
|
// Directories retire never needs to walk. Mirrors the per-walker default SKIP sets
|
|
@@ -524,6 +525,7 @@ module.exports = {
|
|
|
524
525
|
findRetireLauncher,
|
|
525
526
|
chooseRetireLauncher,
|
|
526
527
|
warmRetireSignatures,
|
|
528
|
+
cachedSignatureEntry,
|
|
527
529
|
ensureSignatures,
|
|
528
530
|
buildRetireArgs,
|
|
529
531
|
buildRetireIgnorePatterns,
|
package/lib/source-health.js
CHANGED
|
@@ -52,6 +52,8 @@ const SOURCES = {
|
|
|
52
52
|
|
|
53
53
|
/** Default retries before a source that does not answer stops the run (`--retries <n>`). */
|
|
54
54
|
const RETRY_ATTEMPTS = 5;
|
|
55
|
+
// Internal request metadata, consumed by guardedFetch and never sent as a header.
|
|
56
|
+
const REQUEST_KEY = Symbol('source-health-request-key');
|
|
55
57
|
let retryAttempts = RETRY_ATTEMPTS;
|
|
56
58
|
|
|
57
59
|
/**
|
|
@@ -117,11 +119,23 @@ function errCode(res, err) {
|
|
|
117
119
|
/** Per-run ledger of sources that went dark. */
|
|
118
120
|
function createSourceHealth() {
|
|
119
121
|
const down = new Map();
|
|
122
|
+
const outageEvents = new Map();
|
|
120
123
|
const stale = new Map();
|
|
121
|
-
const
|
|
124
|
+
const staleEvents = new Map();
|
|
125
|
+
const summarizeStale = (id, events) => {
|
|
126
|
+
let result;
|
|
127
|
+
for (const e of events) {
|
|
128
|
+
const oldest = !result || (Number.isFinite(e.at) && (!result.at || e.at < result.at)) ? (Number.isFinite(e.at) ? e.at : null) : result.at;
|
|
129
|
+
result = { id, at: oldest, ...((e.blocking || result?.blocking) ? { blocking: true } : {}), ...((e.refreshFailure || result?.refreshFailure) ? { refreshFailure: e.refreshFailure || result.refreshFailure } : {}) };
|
|
130
|
+
}
|
|
131
|
+
return result;
|
|
132
|
+
};
|
|
122
133
|
return {
|
|
123
134
|
isDown: id => down.has(id),
|
|
124
135
|
markOutage(id, { url, code, requestKey }) {
|
|
136
|
+
const events = outageEvents.get(id) || [];
|
|
137
|
+
events.push({ url, code, requestKey });
|
|
138
|
+
outageEvents.set(id, events);
|
|
125
139
|
let e = down.get(id);
|
|
126
140
|
if (!e) { e = { id, url, codes: [], attempts: 0, requestKeys: [], unkeyed: false }; down.set(id, e); }
|
|
127
141
|
e.attempts += 1;
|
|
@@ -130,21 +144,27 @@ function createSourceHealth() {
|
|
|
130
144
|
return e;
|
|
131
145
|
},
|
|
132
146
|
degraded: () => [...down.values()],
|
|
133
|
-
unreportedOutages: keys => {
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
const
|
|
137
|
-
if(
|
|
138
|
-
|
|
147
|
+
unreportedOutages: keys => {
|
|
148
|
+
const described = new Set(keys || []), result = [];
|
|
149
|
+
for (const [id, all] of outageEvents) {
|
|
150
|
+
const events = all.filter(e => !e.requestKey || !described.has(e.requestKey));
|
|
151
|
+
if (!events.length) continue;
|
|
152
|
+
result.push({ id, url:events[0].url, codes:[...new Set(events.map(e=>e.code).filter(Boolean))], attempts:events.length,
|
|
153
|
+
requestKeys:[...new Set(events.map(e=>e.requestKey).filter(Boolean))], unkeyed:events.some(e=>!e.requestKey) });
|
|
139
154
|
}
|
|
140
|
-
|
|
141
|
-
|
|
155
|
+
return result;
|
|
156
|
+
},
|
|
157
|
+
markStale(id, fetchedAt, { reason, requestKey, refreshStatus, refreshCause, retryAfter } = {}) {
|
|
158
|
+
const at = Date.parse(fetchedAt || "");
|
|
142
159
|
const status=Number(refreshStatus),validCause=['rate-limit','admission','upstream-http'].includes(refreshCause),retry=Number(retryAfter);
|
|
143
|
-
const refreshFailure=validCause && Number.isInteger(status) && status>=400 && status<=599 ? {status,cause:refreshCause,...(retryAfter!=null && Number.isSafeInteger(retry)&&retry>=0&&retry<=604800?{retryAfterSeconds:retry}:{})} :
|
|
144
|
-
|
|
160
|
+
const refreshFailure=validCause && Number.isInteger(status) && status>=400 && status<=599 ? {status,cause:refreshCause,...(retryAfter!=null && Number.isSafeInteger(retry)&&retry>=0&&retry<=604800?{retryAfterSeconds:retry}:{})} : null;
|
|
161
|
+
const events = staleEvents.get(id) || [];
|
|
162
|
+
events.push({requestKey, at, blocking:reason==='refresh-failed', refreshFailure});
|
|
163
|
+
staleEvents.set(id, events);
|
|
164
|
+
stale.set(id, summarizeStale(id, events));
|
|
145
165
|
},
|
|
146
166
|
stale: () => [...stale.values()],
|
|
147
|
-
unreportedStale: keys => {const described=new Set(keys||[]);return [...
|
|
167
|
+
unreportedStale: keys => {const described=new Set(keys||[]);return [...staleEvents].map(([id,events])=>summarizeStale(id,events.filter(e=>!e.requestKey || !described.has(e.requestKey)))).filter(Boolean);},
|
|
148
168
|
};
|
|
149
169
|
}
|
|
150
170
|
|
|
@@ -195,7 +215,7 @@ function guardedFetch({ health, fetch: baseFetch = globalThis.fetch, sleep = ms
|
|
|
195
215
|
* (so the first retry notice carries the real code, not a placeholder).
|
|
196
216
|
* → { alive: true, res } as soon as the host answers, or { alive: false } once exhausted.
|
|
197
217
|
*/
|
|
198
|
-
async function recover(src, url, init, first) {
|
|
218
|
+
async function recover(src, url, init, first, key) {
|
|
199
219
|
let res = first.res, err = first.err;
|
|
200
220
|
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
201
221
|
if (onRetry) onRetry({ source: src.id, label: src.label, attempt: attempt + 1, of: attempts, code: errCode(res, err), delayMs: delays[attempt], url: String(url) });
|
|
@@ -205,11 +225,13 @@ function guardedFetch({ health, fetch: baseFetch = globalThis.fetch, sleep = ms
|
|
|
205
225
|
catch (e) { err = e; }
|
|
206
226
|
if (classifyResponse(res, err) === "answered") return { alive: true, res };
|
|
207
227
|
}
|
|
208
|
-
health.markOutage(src.id, { url: String(url), code: errCode(res, err), requestKey });
|
|
228
|
+
health.markOutage(src.id, { url: String(url), code: errCode(res, err), requestKey:key });
|
|
209
229
|
return { alive: false };
|
|
210
230
|
}
|
|
211
231
|
|
|
212
232
|
return async function guarded(url, init) {
|
|
233
|
+
const key = init?.[REQUEST_KEY] || requestKey;
|
|
234
|
+
if (init && Object.hasOwn(init, REQUEST_KEY)) { init = { ...init }; delete init[REQUEST_KEY]; }
|
|
213
235
|
const src = sourceForUrl(typeof url === "string" ? url : url?.url);
|
|
214
236
|
if (!src) return baseFetch(url, init);
|
|
215
237
|
// A caller that supplied an AbortSignal owns the deadline — and in fad every such
|
|
@@ -220,26 +242,28 @@ function guardedFetch({ health, fetch: baseFetch = globalThis.fetch, sleep = ms
|
|
|
220
242
|
// and let the rotation do its job; exhaustion is reported by the caller, not here.
|
|
221
243
|
if (init && init.signal) return baseFetch(url, init);
|
|
222
244
|
if (health.isDown(src.id)) {
|
|
223
|
-
health.
|
|
224
|
-
|
|
245
|
+
const original = health.degraded().find(e => e.id === src.id)?.codes?.[0];
|
|
246
|
+
health.markOutage(src.id, { url: String(url), code: 'source already unreachable', requestKey:key });
|
|
247
|
+
throw new Error(`${src.label} already unreachable this run${original ? ` (${original})` : ''} (${src.flag} to scan without it)`);
|
|
225
248
|
}
|
|
226
249
|
let res = null, err = null;
|
|
227
250
|
try { res = await baseFetch(url, init); }
|
|
228
251
|
catch (e) { err = e; }
|
|
229
252
|
if (classifyResponse(res, err) === "answered") return res;
|
|
230
253
|
if (handledRateLimit && res && (res.status === 429 || res.status === 503 && res.headers?.get?.('x-fad-proxy') === 'denied')) {
|
|
231
|
-
health.markOutage(src.id, {url:String(url),code:errCode(res,err),requestKey});
|
|
254
|
+
health.markOutage(src.id, {url:String(url),code:errCode(res,err),requestKey:key});
|
|
232
255
|
return res;
|
|
233
256
|
}
|
|
234
257
|
|
|
235
258
|
let probe = probes.get(src.id);
|
|
236
259
|
const owner = !probe;
|
|
237
260
|
if (owner) {
|
|
238
|
-
probe = recover(src, url, init, { res, err }).finally(() => probes.delete(src.id));
|
|
261
|
+
probe = recover(src, url, init, { res, err }, key).finally(() => probes.delete(src.id));
|
|
239
262
|
probes.set(src.id, probe);
|
|
240
263
|
}
|
|
241
264
|
const verdict = await probe;
|
|
242
265
|
if (!verdict.alive) {
|
|
266
|
+
if (!owner) health.markOutage(src.id, {url:String(url),code:errCode(res,err),requestKey:key});
|
|
243
267
|
if (err) throw err;
|
|
244
268
|
return res;
|
|
245
269
|
}
|
|
@@ -252,7 +276,7 @@ function guardedFetch({ health, fetch: baseFetch = globalThis.fetch, sleep = ms
|
|
|
252
276
|
try { r2 = await baseFetch(url, init); }
|
|
253
277
|
catch (e) { e2 = e; }
|
|
254
278
|
if (classifyResponse(r2, e2) !== "answered") {
|
|
255
|
-
health.markOutage(src.id, { url: String(url), code: errCode(r2, e2), requestKey });
|
|
279
|
+
health.markOutage(src.id, { url: String(url), code: errCode(r2, e2), requestKey:key });
|
|
256
280
|
if (e2) throw e2;
|
|
257
281
|
}
|
|
258
282
|
return r2;
|
|
@@ -277,17 +301,17 @@ let activeLedger = null;
|
|
|
277
301
|
function setActiveLedger(h) { activeLedger = h || null; }
|
|
278
302
|
|
|
279
303
|
/** Called by a fan-out loop that exhausted every host without a usable answer. */
|
|
280
|
-
function noteFanoutExhausted(url, reasons) {
|
|
304
|
+
function noteFanoutExhausted(url, reasons, { requestKey } = {}) {
|
|
281
305
|
if (!activeLedger) return;
|
|
282
306
|
const list = reasons || [];
|
|
283
307
|
if (!list.length || list.some(r => classifyMissReason(r) === "answered")) return;
|
|
284
308
|
const src = sourceForUrl(url);
|
|
285
|
-
if (!src
|
|
286
|
-
activeLedger.markOutage(src.id, { url: String(url), code: String(list[0] || "no answer") });
|
|
309
|
+
if (!src) return;
|
|
310
|
+
activeLedger.markOutage(src.id, { url: String(url), code: String(list[0] || "no answer"), requestKey });
|
|
287
311
|
}
|
|
288
312
|
|
|
289
313
|
module.exports = {
|
|
290
|
-
SOURCES, sourceForUrl, classifyResponse, errCode,
|
|
314
|
+
SOURCES, sourceForUrl, classifyResponse, errCode, REQUEST_KEY,
|
|
291
315
|
RETRY_ATTEMPTS, retryDelaysMs, setRetryAttempts, getRetryAttempts, describeSchedule,
|
|
292
316
|
createSourceHealth, formatAbort, guardedFetch,
|
|
293
317
|
classifyMissReason, noteFanoutExhausted, setActiveLedger,
|
package/lib/source-image-scan.js
CHANGED
|
@@ -13,6 +13,7 @@ function eligible(ref){return ref?.scanEligible!==false && (!ref?.classification
|
|
|
13
13
|
async function scanSourceImages(input,options={}){
|
|
14
14
|
const references=(input||[]).map(ref=>({...ref,boundArtifactIds:[]})),warnings=[],notices=[],empty={artifacts:[],matches:[],resolvedDeps:new Map(),warnings,notices,references};
|
|
15
15
|
if(options.images===false)return empty;
|
|
16
|
+
warnings.push(...require('./image-references').unpinnedImageWarnings(references));
|
|
16
17
|
const groups=new Map();
|
|
17
18
|
for(const ref of references){
|
|
18
19
|
if(!eligible(ref)){ref.scanStatus='not-scannable';ref.imageScan={status:'not-scannable',reasonCode:ref.classification||'unresolved',message:ref.blockReason||'The image declaration cannot be resolved to a registry image.',artifactIds:[]};continue;}
|
|
@@ -137,20 +137,21 @@ async function assessSystemInventory(inventory,opts={}) {
|
|
|
137
137
|
if(!s)return {matches,coverage:[{source:'system-osv',status:'unknown',reason:'unsupported or missing distribution identity'}],warnings};
|
|
138
138
|
const cache=opts.records?null:repo(opts),ns=namespace(s),snapshot=opts.records?{complete:opts.complete===true,fetchedAt:opts.fetchedAt}:cache.getSnapshot(ns);
|
|
139
139
|
if(!snapshot)return {matches,coverage:[{source:'system-osv',status:'missing',ecosystem:s.ecosystem}],warnings:['No offline system advisory snapshot for '+s.ecosystem]};
|
|
140
|
-
let uncertain=0;
|
|
140
|
+
let uncertain=0; const uncertainItems=[];
|
|
141
|
+
const unknown=(dep,reason,id)=>{uncertain++;uncertainItems.push({id,package:dep.name,version:dep.version,reason});};
|
|
141
142
|
for(const dep of inventory.packages||[]) {
|
|
142
143
|
const names=[...new Set([dep.sourceName,dep.name].filter(Boolean))];
|
|
143
|
-
if(!dep.sourceName)
|
|
144
|
+
if(!dep.sourceName)unknown(dep,'Source package identity is not declared in the installed metadata.');
|
|
144
145
|
const records=opts.records ? opts.records.filter(r=>r.affected?.some(a=>a.package?.ecosystem===s.ecosystem && names.includes(a.package?.name))) : names.flatMap(name=>{const entry=cache.get(ns,name);return entry && entry.fetchedAt===snapshot.fetchedAt ? entry.value : [];});
|
|
145
146
|
for(const record of records)for(const a of record.affected||[]) {
|
|
146
147
|
if(a.package?.ecosystem!==s.ecosystem || !names.includes(a.package?.name))continue;
|
|
147
148
|
const purl=a.package.purl||'', arch=(purl.match(/[?&]arch=([^&]+)/)||[])[1];
|
|
148
149
|
const sourceArch=arch==='source' || (a.package.name===dep.sourceName && dep.sourceName!==dep.name);
|
|
149
150
|
if(arch && arch!=='source' && dep.architecture && arch!==dep.architecture)continue;
|
|
150
|
-
if(arch && arch!=='source' && !dep.architecture){
|
|
151
|
+
if(arch && arch!=='source' && !dep.architecture){unknown(dep,'Installed architecture is not declared.',record.id);continue;}
|
|
151
152
|
const ver=sourceArch ? dep.sourceVersion : dep.version;
|
|
152
153
|
const result=verdict(ver,a,s.compare);
|
|
153
|
-
if(result===null){
|
|
154
|
+
if(result===null){unknown(dep,'The available version range or installed source version does not establish applicability.',record.id);continue;}if(!result)continue;
|
|
154
155
|
const severity=severityFromOsv(record), id=(record.aliases||[]).find(x=>/^CVE-/.test(x))||record.id;
|
|
155
156
|
const fixes=(a.ranges||[]).flatMap(r=>r.events||[]).map(e=>e.fixed).filter(v=>typeof v==='string' && s.compare(v,ver)>0).sort((x,y)=>s.compare(x,y));
|
|
156
157
|
matches.push({dep,cve:{id,summary:record.summary||'',description:record.details||record.summary||'',severity:severity.severity,score:severity.score,
|
|
@@ -162,8 +163,8 @@ async function assessSystemInventory(inventory,opts={}) {
|
|
|
162
163
|
osvRefs:Array.isArray(record.references)?record.references:[],fixVersion:fixes[0]||null},source:'osv',advisoryId:record.id});
|
|
163
164
|
}
|
|
164
165
|
}
|
|
165
|
-
coverage.push({source:'system-osv',ecosystem:s.ecosystem,status:snapshot.complete && !uncertain?'complete':'incomplete',result:snapshot.complete && !uncertain?(matches.length?'affected':'no-match'):'indeterminate',complete:!!snapshot.complete,fetchedAt:snapshot.fetchedAt||null,unknown:uncertain});
|
|
166
|
-
if(uncertain)warnings.push(
|
|
166
|
+
coverage.push({source:'system-osv',ecosystem:s.ecosystem,status:snapshot.complete && !uncertain?'complete':'incomplete',result:snapshot.complete && !uncertain?(matches.length?'affected':'no-match'):'indeterminate',complete:!!snapshot.complete,...(snapshot.complete?{affectsCompleteness:false}:{}),affectsAssessment:uncertain>0,fetchedAt:snapshot.fetchedAt||null,unknown:uncertain});
|
|
167
|
+
if(uncertain)warnings.push({...require('../diagnostics').advisoryEvidenceDiagnostic(uncertainItems),source:'system-osv'});
|
|
167
168
|
return {matches,coverage,warnings};
|
|
168
169
|
}
|
|
169
170
|
module.exports={scope,defaultAdapters,recordsFrom,verdict,importSystemAdvisories,syncSystemAdvisories,assessSystemInventory};
|
|
@@ -24,24 +24,24 @@ async function assessAlpineTracker(packages,distribution,options={}){
|
|
|
24
24
|
const signal=options.signal?AbortSignal.any([options.signal,AbortSignal.timeout(options.timeoutMs??30000)]):AbortSignal.timeout(options.timeoutMs??30000);
|
|
25
25
|
const type=kind==='package'?'package':'vulnerability',params=kind==='package'?{name:id}:{id};
|
|
26
26
|
const response=await require('../providers').getResource('alpine',type,params,{fetcher:options.fetcher,signal,streaming:true,noStore:true});
|
|
27
|
-
if(!response.ok){await response.body?.cancel();throw Error(`Alpine tracker HTTP ${response.status}`);}
|
|
27
|
+
if(!response.ok){await response.body?.cancel();throw Object.assign(Error(`Alpine tracker HTTP ${response.status}`),{status:response.status});}
|
|
28
28
|
const document=await boundedJson(response,maxBytes);
|
|
29
29
|
if(document?.id!==url||!Array.isArray(kind==='package'?document.cpeMatch:document.state))throw Error('invalid Alpine tracker response');
|
|
30
30
|
const proxy=require('../providers').hasProxyRoute(),stamp=Date.parse(response.headers?.get?.('x-fad-proxy-fetched-at')||''),valid=Number.isFinite(stamp)&&stamp>0&&stamp<=Date.now()+300000;
|
|
31
31
|
const entry={document,fetchedAt:proxy?(valid?stamp:Date.now()):Date.now(),stale:proxy&&(!valid||response.headers?.get?.('x-fad-proxy')==='stale'),url};repo.put('catalogue',k,entry);return entry;
|
|
32
32
|
});memo.set(memoKey,promise);return promise;
|
|
33
33
|
}
|
|
34
|
-
const indexes=await Promise.all([...groups.values()].map(async group=>{const sourceUrl=`${ORIGIN}/srcpkg/${encodeURIComponent(group.name)}`;try{const index=await get('package',group.name,sourceUrl);if(index.document?.id!==sourceUrl||!Array.isArray(index.document.cpeMatch))throw Error('invalid Alpine package index');return {group,sourceUrl,index};}catch(error){diagnostics.push({source:'alpine-tracker',code:options.offline?'cache-missing':'source-request-failed',reason:error.message,resources:[sourceUrl]});return null;}}));
|
|
34
|
+
const indexes=await Promise.all([...groups.values()].map(async group=>{const sourceUrl=`${ORIGIN}/srcpkg/${encodeURIComponent(group.name)}`;try{const index=await get('package',group.name,sourceUrl);if(index.document?.id!==sourceUrl||!Array.isArray(index.document.cpeMatch))throw Error('invalid Alpine package index');return {group,sourceUrl,index};}catch(error){diagnostics.push({source:'alpine-tracker',code:error.status===404?'record-not-listed':options.offline?'cache-missing':'source-request-failed',reason:error.status===404?'No entry published by the Alpine tracker (HTTP 404); this does not establish absence of vulnerabilities.':error.message,resources:[sourceUrl]});return null;}}));
|
|
35
35
|
const work=[];let truncated=false;
|
|
36
36
|
for(const index of indexes.filter(Boolean)){const {group,sourceUrl}=index,ids=[...new Set(index.index.document.cpeMatch.filter(m=>m.package===sourceUrl).map(m=>cveId(m.vuln)).filter(Boolean))];for(const id of ids){if(work.length>=maxCves){truncated=true;break;}work.push({...index,id});}}
|
|
37
|
-
await Promise.all(work.map(async({group,sourceUrl,index,id})=>{const url=`${ORIGIN}/vuln/${id}`;let entry;try{entry=await get('vulnerability',id,url);if(entry.document?.id!==url||!Array.isArray(entry.document.state))throw Error('invalid Alpine vulnerability record');}catch(error){diagnostics.push({source:'alpine-tracker',code:options.offline?'cache-missing':'source-request-failed',reason:error.message,resources:[url]});return;}
|
|
37
|
+
await Promise.all(work.map(async({group,sourceUrl,index,id})=>{const url=`${ORIGIN}/vuln/${id}`;let entry;try{entry=await get('vulnerability',id,url);if(entry.document?.id!==url||!Array.isArray(entry.document.state))throw Error('invalid Alpine vulnerability record');}catch(error){diagnostics.push({source:'alpine-tracker',code:error.status===404?'record-not-listed':options.offline?'cache-missing':'source-request-failed',reason:error.status===404?'No entry published by the Alpine tracker (HTTP 404); this does not establish absence of vulnerabilities.':error.message,resources:[url]});return;}
|
|
38
38
|
const expectedVersion=packageUrl(group.name,group.version),states=entry.document.state.filter(s=>s.packageVersion===expectedVersion&&typeof s.repo==='string'&&s.repo.startsWith(`${release}-`)&&typeof s.fixed==='boolean');
|
|
39
39
|
const scoped=options.alpineRepository?states.filter(s=>s.repo===`${release}-${options.alpineRepository}`):states,statuses=new Set(scoped.map(s=>s.fixed?'fixed':'possible')),status=statuses.size===1?[...statuses][0]:'unknown';
|
|
40
40
|
observations.push({id,source:'alpine-tracker',status,sourceName:group.name,sourceVersion:group.version,distribution:{id:'alpine',versionId:distribution.versionId,branch:release},repository:options.alpineRepository||null,repositoryVerified:!!options.alpineRepository,packages:[...new Set(group.packages)],sourceUrl:url,packageUrl:sourceUrl,observedAt:new Date(entry.fetchedAt).toISOString(),stale:!!entry.stale||!!index.stale,states:scoped.map(s=>({repo:s.repo,fixed:s.fixed,sourceUrl:s.id||null})),scope:'source-package',advisoryVerdict:false});
|
|
41
41
|
}));
|
|
42
42
|
observations.sort((a,b)=>a.sourceName.localeCompare(b.sourceName)||a.id.localeCompare(b.id));
|
|
43
43
|
if(truncated)diagnostics.push({source:'alpine-tracker',code:'request-limit',reason:`Alpine tracker candidate limit ${maxCves} reached.`,resources:[]});
|
|
44
|
-
const
|
|
45
|
-
return {observations,coverage:{source:'alpine-tracker',execution:incomplete?'partial':'completed',result:incomplete?'indeterminate':'consulted',scope:'cpe-candidates',packages:groups.size,candidates:work.length,missing,unscoped,stale,reason:incomplete?'Some Alpine tracker observations were unavailable or incomplete.':'Consulted only CVEs discoverable from tracker CPE rules; this does not establish complete package coverage.'},diagnostics};
|
|
44
|
+
const notListed=diagnostics.filter(d=>d.code==='record-not-listed').length,missing=diagnostics.filter(d=>!['request-limit','record-not-listed'].includes(d.code)).length,stale=observations.filter(o=>o.stale).length,incomplete=!!(missing||truncated||unscoped||stale);
|
|
45
|
+
return {observations,coverage:{source:'alpine-tracker',execution:incomplete?'partial':'completed',result:incomplete?'indeterminate':'consulted',scope:'cpe-candidates',...(!missing&&!truncated&&!stale?{affectsCompleteness:false}:{}),notListed,packages:groups.size,candidates:work.length,missing,unscoped,stale,reason:incomplete?'Some Alpine tracker observations were unavailable or incomplete.':'Consulted only CVEs discoverable from tracker CPE rules; this does not establish complete package coverage.'},diagnostics};
|
|
46
46
|
}
|
|
47
47
|
module.exports={assessAlpineTracker};
|
|
@@ -53,7 +53,7 @@ const apk={id:'apk', async collect(root,opts={}) {
|
|
|
53
53
|
if(!stanza.trim())continue;const f=fields(stanza); if(!f.P || !f.V){warnings.push('Malformed APK installed record');continue;}
|
|
54
54
|
let dir='';const ownedPaths=[];
|
|
55
55
|
for(const line of stanza.split(/\r?\n/)){if(line.startsWith('F:'))dir=line.slice(2);else if(line.startsWith('R:')){const name=line.slice(2),fp='/'+[dir,name].filter(Boolean).join('/');if(!fp.split('/').includes('..'))ownedPaths.push(fp);}}
|
|
56
|
-
packages.push(base(f.P,f.V,f.A,'apk',p,{sourceName:f.o || f.P,sourceVersion:f.V,ownedPaths}));
|
|
56
|
+
packages.push(base(f.P,f.V,f.A,'apk',p,{sourceName:f.o || f.P,sourceVersion:f.V,ownedPaths,packageMetadata:{maintainer:f.m||null,homepage:f.U||null}}));
|
|
57
57
|
}
|
|
58
58
|
return {packages,coverage:{collector:'apk',status:warnings.length?'incomplete':'complete',count:packages.length},warnings};
|
|
59
59
|
}};
|
|
@@ -3,7 +3,7 @@ const {createCacheRepository}=require('../cache-repository');
|
|
|
3
3
|
// Each adapter owns its scope, comparisons and evidence. Failed consultations
|
|
4
4
|
// never prevent the independent adapters or OSV from returning their results.
|
|
5
5
|
const adapters=[
|
|
6
|
-
{id:'nginx-vendor-advisories',supports:(d,inventory)=>inventory?.packages?.some(
|
|
6
|
+
{id:'nginx-vendor-advisories',supports:(d,inventory)=>inventory?.packages?.some(require('./nginx-advisories').isNginxPackage),identifyPackageOrigin:(pkg,options)=>require('./nginx-advisories').nginxPackageOrigin(pkg,options),async assess(inventory,options){return require('./nginx-advisories').assessNginxAdvisories(inventory.packages,options);}},
|
|
7
7
|
{id:'debian-security-tracker-history',supports:d=>d?.id==='debian',async assess(inventory,options){
|
|
8
8
|
const source=require('./historical-debian');
|
|
9
9
|
try{source.checkDistribution(inventory.distribution);}catch{return {matches:[],observations:[],warnings:[],coverage:[{source:this.id,execution:'not-applicable',result:'indeterminate',reason:'Exact Debian release codename is unavailable.'}]};}
|
|
@@ -25,7 +25,7 @@ const adapters=[
|
|
|
25
25
|
{id:'debian-security-tracker-current-candidates',supports:d=>d?.id==='debian',async assess(inventory,options){return require('./current-debian').assessCurrentDebianCandidates(inventory,options);}},
|
|
26
26
|
{id:'alpine-tracker',supports:d=>d?.id==='alpine',async assess(inventory,options){
|
|
27
27
|
const result=await require('./alpine-tracker').assessAlpineTracker(inventory.packages,inventory.distribution,options);
|
|
28
|
-
return {matches:[],observations:result.observations,coverage:[result.coverage],warnings:result.diagnostics.map(d=>({type:'source-unavailable',source:this.id,message:d.reason}))};
|
|
28
|
+
return {matches:[],observations:result.observations,coverage:[result.coverage],warnings:result.diagnostics.map(d=>({type:'source-unavailable',source:this.id,code:d.code,...(d.code==='record-not-listed'?{affectsCompleteness:false}:{}),items:(d.resources||[]).map(id=>({id})),message:d.reason}))};
|
|
29
29
|
}},
|
|
30
30
|
];
|
|
31
31
|
async function assessDistributionSources(inventory,options={}){
|