vigievuln 1.2.0 → 1.3.0
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 +23 -2
- package/README.md +13 -7
- package/lib/advisory-freshness.js +2 -0
- package/lib/airgap-project.js +35 -7
- package/lib/applicability-evidence.js +12 -0
- package/lib/artifacts/applications.js +54 -0
- package/lib/artifacts/cve-view.js +108 -0
- package/lib/artifacts/enrichment.js +86 -0
- package/lib/artifacts/go-main-identity.js +45 -0
- package/lib/artifacts/go-publisher-advisories.js +24 -0
- package/lib/artifacts/index.js +272 -0
- package/lib/artifacts/publisher-advisories.js +12 -0
- package/lib/artifacts/remediation-report.js +48 -0
- package/lib/artifacts/report-inventory.js +26 -0
- package/lib/artifacts/report.js +191 -0
- package/lib/artifacts/risk-report.js +120 -0
- package/lib/artifacts/sbom.js +68 -0
- package/lib/artifacts/scan.js +401 -0
- package/lib/cache-archive-sqlite.js +41 -25
- package/lib/certs/analyze.js +49 -13
- package/lib/charts.js +124 -32
- package/lib/cli-command-routing.js +20 -6
- package/lib/cli-groups.js +2 -1
- package/lib/cli-image.js +206 -0
- package/lib/codecs/binary/elf-metadata.js +42 -0
- package/lib/codecs/binary/go-buildinfo.js +37 -0
- package/lib/codecs/binary/metadata.js +7 -0
- package/lib/codecs/binary/pe-metadata.js +27 -1
- package/lib/codecs/binary/scan.js +44 -26
- package/lib/codecs/binary/sniff.js +16 -15
- package/lib/codecs/binary.codec.js +27 -4
- package/lib/codecs/go/parse.js +10 -4
- package/lib/codecs/go.codec.js +23 -6
- package/lib/codecs/gradle/parse.js +63 -2
- package/lib/codecs/gradle/versionless.js +175 -0
- package/lib/codecs/gradle.codec.js +20 -3
- package/lib/codecs/index.js +2 -2
- package/lib/codecs/maven.codec.js +9 -4
- package/lib/codecs/npm/collect.js +6 -11
- package/lib/codecs/nuget/parse.js +16 -5
- package/lib/codecs/nuget.codec.js +2 -1
- package/lib/codecs/pypi/parse.js +56 -15
- package/lib/codecs/pypi.codec.js +2 -0
- package/lib/csaf-export.js +46 -11
- package/lib/cve-download.js +33 -29
- package/lib/cve-match.js +10 -0
- package/lib/cve-packages-proxy.js +19 -0
- package/lib/cve-report.js +273 -165
- package/lib/deps-descriptor.js +25 -3
- package/lib/diagnostics.js +12 -0
- package/lib/diff.js +0 -0
- package/lib/epss.js +6 -6
- package/lib/euvd.js +34 -4
- package/lib/finding-enrichment.js +165 -0
- package/lib/finding-summary.js +4 -3
- package/lib/i18n.js +35 -9
- package/lib/image-network.js +54 -0
- package/lib/image-references.js +203 -0
- package/lib/image-registry.js +385 -0
- package/lib/image-update.js +39 -0
- package/lib/json-export.js +100 -10
- package/lib/kev.js +6 -6
- package/lib/maven-bom.js +2 -1
- package/lib/merge-sources.js +3 -0
- package/lib/native-advisories.js +9 -7
- package/lib/native-cna-identities.js +12 -0
- package/lib/native-package-match.js +159 -0
- package/lib/native-source-prepare.js +60 -0
- package/lib/nvd.js +34 -23
- package/lib/osv.js +33 -14
- package/lib/project-descriptor.js +3 -2
- package/lib/provenance.js +8 -2
- package/lib/providers/alpine.js +8 -0
- package/lib/providers/common.js +11 -3
- package/lib/providers/debian.js +11 -0
- package/lib/providers/euvd.js +2 -1
- package/lib/providers/freexian.js +13 -0
- package/lib/providers/github.js +1 -0
- package/lib/providers/go.js +2 -1
- package/lib/providers/index.js +18 -14
- package/lib/providers/nginx.js +5 -0
- package/lib/providers/nvd.js +1 -1
- package/lib/providers/osv.js +1 -1
- package/lib/providers/osvdb.js +2 -2
- package/lib/proxy-throttle.js +89 -29
- package/lib/purl.js +10 -2
- package/lib/record-freshness.js +22 -0
- package/lib/report-notices.js +47 -0
- package/lib/report-time.js +45 -0
- package/lib/request-failure.js +22 -0
- package/lib/resource-cache/engine.js +130 -26
- package/lib/resource-cache/snapshot-projection.js +33 -0
- package/lib/resource-cache/validate.js +22 -5
- package/lib/risk-evidence.js +18 -0
- package/lib/sarif-export.js +17 -9
- package/lib/sbom-export.js +38 -12
- package/lib/source-health.js +25 -8
- package/lib/source-image-scan.js +57 -0
- package/lib/source-profile.js +6 -3
- package/lib/sqlite-driver.js +15 -1
- package/lib/suppress.js +34 -13
- package/lib/system-inventory/advisories.js +169 -0
- package/lib/system-inventory/alpine-tracker.js +47 -0
- package/lib/system-inventory/collect.js +118 -0
- package/lib/system-inventory/current-debian.js +99 -0
- package/lib/system-inventory/distribution-sources.js +132 -0
- package/lib/system-inventory/freexian-ela.js +32 -0
- package/lib/system-inventory/freexian-release-evidence.js +35 -0
- package/lib/system-inventory/freexian-tracker.js +72 -0
- package/lib/system-inventory/historical-debian.js +196 -0
- package/lib/system-inventory/index.js +2 -0
- package/lib/system-inventory/nginx-advisories.js +39 -0
- package/lib/system-inventory/rpm-storage.js +86 -0
- package/lib/system-inventory/targeted.js +70 -0
- package/lib/system-inventory/versions.js +59 -0
- package/lib/transitive.js +11 -2
- package/lib/ui.js +8 -5
- package/lib/unmanaged.js +1 -1
- package/lib/xlsx-export.js +8 -2
- package/package.json +12 -3
- package/vigievuln.js +279 -127
|
@@ -64,15 +64,16 @@ const FAILURE_RETRY_MS = 30 * 1000;
|
|
|
64
64
|
|
|
65
65
|
// Format follows the typed operation, never an upstream Content-Type (an HTML
|
|
66
66
|
// error page may claim application/json, and raw JSON mirrors use text/plain).
|
|
67
|
-
const JSON_PROVIDERS = new Set(["nvd", "osv", "packagist", "kev", "eol", "npm", "pypi", "ruby", "go", "nuget",
|
|
67
|
+
const JSON_PROVIDERS = new Set(["nvd", "osv", "packagist", "kev", "eol", "npm", "pypi", "ruby", "go", "nuget", "alpine",
|
|
68
68
|
"wordfence", "wordpress", "drupal", "hashid", "retire", "certfr"]);
|
|
69
69
|
function expectsJson(resource) {
|
|
70
70
|
if (!resource) return false;
|
|
71
71
|
const { provider, type } = resource;
|
|
72
72
|
return JSON_PROVIDERS.has(provider) ||
|
|
73
|
+
(provider === "debian" && ['history','source-version'].includes(type)) ||
|
|
73
74
|
(provider === "github" && type !== "cve-archive") ||
|
|
74
75
|
(provider === "epss" && type !== "current-csv") ||
|
|
75
|
-
(provider === "euvd" && type === "exploited") ||
|
|
76
|
+
(provider === "euvd" && (type === "exploited" || type === "vulnerability")) ||
|
|
76
77
|
(provider === "maven" && type === "latest");
|
|
77
78
|
}
|
|
78
79
|
function parseUpstreamJson(buffer) {
|
|
@@ -195,6 +196,11 @@ function sendJson(res, code, obj, headers = {}) {
|
|
|
195
196
|
res.writeHead(code, { "content-type": "application/json", ...headers });
|
|
196
197
|
res.end(body);
|
|
197
198
|
}
|
|
199
|
+
function retryAfterSeconds(value) {
|
|
200
|
+
if (typeof value !== 'string') return 10;
|
|
201
|
+
if (/^\d{1,7}$/.test(value)) return Number(value);
|
|
202
|
+
const at=Date.parse(value);return Number.isFinite(at) ? Math.max(0,Math.min(604800,Math.ceil((at-Date.now())/1000))) : 10;
|
|
203
|
+
}
|
|
198
204
|
|
|
199
205
|
/**
|
|
200
206
|
* Build an engine over a store. Returns:
|
|
@@ -210,6 +216,8 @@ function createResourceEngine(opts = {}) {
|
|
|
210
216
|
fetcher = globalThis.fetch,
|
|
211
217
|
defaultTtlMs = DEFAULT_TTL_MS,
|
|
212
218
|
overrideTtlMs = null,
|
|
219
|
+
// Optional per-record policy. null delegates to the normal resource TTL.
|
|
220
|
+
resourceFreshness = null,
|
|
213
221
|
maxBodyBytes = DEFAULT_MAX_BODY_BYTES,
|
|
214
222
|
maxTransferBytes = DEFAULT_MAX_TRANSFER_BYTES,
|
|
215
223
|
upstreamTimeoutMs = DEFAULT_UPSTREAM_TIMEOUT_MS,
|
|
@@ -301,7 +309,7 @@ function createResourceEngine(opts = {}) {
|
|
|
301
309
|
};
|
|
302
310
|
const ttlFor = url => ttlForUrl(url, { defaultTtlMs, overrideTtlMs });
|
|
303
311
|
|
|
304
|
-
function serveEntry(res, entry, tag) {
|
|
312
|
+
function serveEntry(res, entry, tag, reason = null, failure = null) {
|
|
305
313
|
const release = entry.body ? () => {} : store.acquire(entry); // an in-memory body pins nothing
|
|
306
314
|
res.writeHead(200, {
|
|
307
315
|
...responseHeaders(new Headers(entry.responseHeaders || {})),
|
|
@@ -310,6 +318,8 @@ function createResourceEngine(opts = {}) {
|
|
|
310
318
|
"content-type": entry.contentType || "application/octet-stream",
|
|
311
319
|
"content-length": entry.bytes,
|
|
312
320
|
"x-fad-proxy": tag,
|
|
321
|
+
...(reason ? {"x-fad-proxy-reason":reason} : {}),
|
|
322
|
+
...(failure ? {'x-fad-proxy-refresh-status':String(failure.status),'x-fad-proxy-refresh-cause':failure.cause, ...(failure.retryAfterS!=null?{'retry-after':String(failure.retryAfterS)}:{})} : {}),
|
|
313
323
|
"x-fad-proxy-fetched-at": new Date(entry.fetchedAt).toISOString(),
|
|
314
324
|
});
|
|
315
325
|
// An entry that carries its body (a projection just built) is served from that buffer.
|
|
@@ -359,12 +369,14 @@ function createResourceEngine(opts = {}) {
|
|
|
359
369
|
if (up.status !== 200 || !up.body) {
|
|
360
370
|
if (allowStale && stale && (up.status === 403 || up.status === 429 || up.status >= 500)) {
|
|
361
371
|
stats.stale++;
|
|
362
|
-
|
|
372
|
+
const seconds=retryAfterSeconds(up.headers.get('retry-after'));
|
|
373
|
+
const failure=up.status===429?{status:429,cause:'rate-limit',retryAfterS:seconds}:{status:up.status,cause:'upstream-http'};
|
|
374
|
+
if (res && !res.destroyed) serveEntry(res, stale, "stale", 'refresh-failed',failure);
|
|
363
375
|
await up.body?.cancel();
|
|
364
|
-
return { stored: false, status: up.status, staleServed: true };
|
|
376
|
+
return { stored: false, status: up.status, staleServed: true, failure };
|
|
365
377
|
}
|
|
366
378
|
if (res && !res.destroyed) {
|
|
367
|
-
res.writeHead(up.status, { "content-type": contentType, "x-fad-proxy": "pass", "x-fad-proxy-fetched-at": new Date(fetchedAt).toISOString() });
|
|
379
|
+
res.writeHead(up.status, { "content-type": contentType, "x-fad-proxy": "pass", "x-fad-proxy-fetched-at": new Date(fetchedAt).toISOString(), ...(up.status===429?{'retry-after':String(retryAfterSeconds(up.headers.get('retry-after')))}:{}) });
|
|
368
380
|
if (up.body) await pipeline(Readable.fromWeb(up.body), byteLimit(maxTransferBytes), res, { signal });
|
|
369
381
|
else res.end();
|
|
370
382
|
} else await up.body?.cancel();
|
|
@@ -428,7 +440,7 @@ function createResourceEngine(opts = {}) {
|
|
|
428
440
|
const release = old ? store.acquire(old) : () => {};
|
|
429
441
|
try {
|
|
430
442
|
const result = await runFetch(target, { ...runOpts, cacheKey });
|
|
431
|
-
if (result.status === 403 || result.status
|
|
443
|
+
if (result.status === 403 || result.status >= 500) rememberFailure(cacheKey);
|
|
432
444
|
else failureUntil.delete(cacheKey);
|
|
433
445
|
return result;
|
|
434
446
|
} catch (err) {
|
|
@@ -441,30 +453,40 @@ function createResourceEngine(opts = {}) {
|
|
|
441
453
|
return p;
|
|
442
454
|
}
|
|
443
455
|
|
|
456
|
+
async function entryIsFresh(entry, resource) {
|
|
457
|
+
if (!entry) return false;
|
|
458
|
+
const now = Date.now();
|
|
459
|
+
if (!Number.isFinite(entry.fetchedAt) || entry.fetchedAt <= 0 || entry.fetchedAt > now) return false;
|
|
460
|
+
if (resourceFreshness && resource) {
|
|
461
|
+
const fresh = await resourceFreshness({resource, entry, now, readBody: () => store.readBody(entry)});
|
|
462
|
+
if (typeof fresh === 'boolean') return fresh;
|
|
463
|
+
}
|
|
464
|
+
return now - entry.fetchedAt < Math.min(entry.ttlMs, overrideTtlMs || entry.ttlMs);
|
|
465
|
+
}
|
|
444
466
|
async function handleCached(res, { target, cacheKey, reqHeaders = {}, method = "GET", body = undefined,
|
|
445
|
-
ttlMs = ttlFor(target), cacheLimitBytes = maxBodyBytes, resource = null, ctx = null }) {
|
|
467
|
+
ttlMs = ttlFor(target), cacheLimitBytes = maxBodyBytes, resource = null, ctx = null, revalidate = false }) {
|
|
446
468
|
let entry = await store.get(cacheKey);
|
|
447
469
|
// Older cached GitHub pages lack pagination metadata and cannot prove completeness.
|
|
448
470
|
if (entry && target.includes("api.github.com/repos/") && target.includes("/security-advisories") && !entry.responseHeaders) entry = null;
|
|
449
|
-
const fresh =
|
|
450
|
-
if (fresh) {
|
|
471
|
+
const fresh = !revalidate && await entryIsFresh(entry, resource);
|
|
472
|
+
if (fresh && !revalidate) {
|
|
451
473
|
stats.hits++;
|
|
452
474
|
return serveEntry(res, entry, "hit");
|
|
453
475
|
}
|
|
454
|
-
const missing = !entry && knownMissing(cacheKey);
|
|
476
|
+
const missing = !revalidate && !entry && knownMissing(cacheKey);
|
|
455
477
|
if (missing) {
|
|
456
478
|
stats.hits++;
|
|
457
479
|
return sendJson(res, missing.status, { error: "not found upstream (remembered)" }, { "x-fad-proxy": "negative" });
|
|
458
480
|
}
|
|
459
481
|
if ((failureUntil.get(cacheKey) || 0) > Date.now()) {
|
|
460
|
-
if (entry && allowStale) { stats.stale++; return serveEntry(res, entry, "stale"); }
|
|
482
|
+
if (entry && allowStale) { stats.stale++; return serveEntry(res, entry, "stale", 'refresh-failed'); }
|
|
461
483
|
return sendJson(res, 502, { error: "upstream unavailable and no cached response" }, { "x-fad-proxy": "error" });
|
|
462
484
|
}
|
|
463
|
-
if (swr && entry && allowStale) {
|
|
485
|
+
if (swr && entry && allowStale && !revalidate) {
|
|
464
486
|
// Serve the stale copy now, refresh in the background — instances get
|
|
465
487
|
// the shared base immediately and the next reader sees the fresh one.
|
|
466
488
|
stats.stale++;
|
|
467
|
-
serveEntry(res, entry, "stale");
|
|
489
|
+
serveEntry(res, entry, "stale", 'revalidating');
|
|
468
490
|
viaInflight(cacheKey, target, { reqHeaders, stale:entry, method, body, ttlMs, cacheLimitBytes, resource, ctx }).catch(() => {});
|
|
469
491
|
return;
|
|
470
492
|
}
|
|
@@ -475,12 +497,13 @@ function createResourceEngine(opts = {}) {
|
|
|
475
497
|
try { completed = await inflight.get(cacheKey); }
|
|
476
498
|
catch (err) {
|
|
477
499
|
stats.errors++;
|
|
478
|
-
if (entry && allowStale) { stats.stale++; return serveEntry(res, entry, "stale"); }
|
|
500
|
+
if (entry && allowStale) { stats.stale++; return serveEntry(res, entry, "stale", 'refresh-failed',err instanceof UpstreamDenied?{status:503,cause:'admission',retryAfterS:err.retryAfterS}:null); }
|
|
479
501
|
return sendJson(res, 502, { error: String(err.message || err) }, { "x-fad-proxy": "error" });
|
|
480
502
|
}
|
|
481
503
|
const e2 = await store.get(cacheKey);
|
|
504
|
+
if (completed.staleServed && e2 && allowStale) { stats.stale++; return serveEntry(res, e2, 'stale', 'refresh-failed',completed.failure); }
|
|
482
505
|
if (e2 && ![404, 410].includes(completed.status)) {
|
|
483
|
-
const e2Fresh =
|
|
506
|
+
const e2Fresh = await entryIsFresh(e2, resource);
|
|
484
507
|
if (e2Fresh || allowStale) { stats[e2Fresh ? "hits" : "stale"]++; return serveEntry(res, e2, e2Fresh ? "hit" : "stale"); }
|
|
485
508
|
}
|
|
486
509
|
if (completed.transient) { stats.coalesced++; return serveEntry(res, completed.transient, "coalesced"); }
|
|
@@ -494,7 +517,7 @@ function createResourceEngine(opts = {}) {
|
|
|
494
517
|
} catch (err) {
|
|
495
518
|
stats.errors++;
|
|
496
519
|
// Stale-if-error: a dead upstream must not become a dead shared cache.
|
|
497
|
-
if (entry && allowStale && !res.headersSent) { stats.stale++; return serveEntry(res, entry, "stale"); }
|
|
520
|
+
if (entry && allowStale && !res.headersSent) { stats.stale++; return serveEntry(res, entry, "stale", 'refresh-failed',err instanceof UpstreamDenied?{status:503,cause:'admission',retryAfterS:err.retryAfterS}:null); }
|
|
498
521
|
if (err instanceof UpstreamDenied && !res.headersSent)
|
|
499
522
|
return sendJson(res, 503, { error: err.message }, { "x-fad-proxy": "denied", "retry-after": String(err.retryAfterS) });
|
|
500
523
|
if (!res.headersSent) return sendJson(res, 502, { error: String(err.message || err) }, { "x-fad-proxy": "error" });
|
|
@@ -524,11 +547,11 @@ function createResourceEngine(opts = {}) {
|
|
|
524
547
|
const results = new Array(items.length);
|
|
525
548
|
const waits = [];
|
|
526
549
|
const reserved = [];
|
|
527
|
-
let awaitedBytes = 0, oldestStale = null;
|
|
550
|
+
let awaitedBytes = 0, oldestStale = null, staleFailure = false, quotaFailure = null;
|
|
528
551
|
// A batched response is only as fresh as its oldest member. Missing items
|
|
529
552
|
// are fetched during this request, so its start is a conservative timestamp.
|
|
530
553
|
const oldestFetchedAt = entries.reduce((oldest, entry) => entry ? Math.min(oldest, entry.fetchedAt) : oldest, Date.now());
|
|
531
|
-
const markStale = entry => { oldestStale = Math.min(oldestStale ?? entry.fetchedAt, entry.fetchedAt); };
|
|
554
|
+
const markStale = (entry, failed = false, error = null) => { oldestStale = Math.min(oldestStale ?? entry.fetchedAt, entry.fetchedAt); staleFailure ||= failed; const detail=error instanceof UpstreamDenied?{status:503,cause:'admission',retryAfterS:error.retryAfterS}:error?.status===429?{status:429,cause:'rate-limit',retryAfterS:error.retryAfterS}:error?.status>=400&&error?.status<=599?{status:error.status,cause:'upstream-http'}:null; if(detail && (!quotaFailure || (detail.retryAfterS||0)>(quotaFailure.retryAfterS||0)))quotaFailure=detail; };
|
|
532
555
|
const assignResult = (i, body) => {
|
|
533
556
|
awaitedBytes += Buffer.byteLength(JSON.stringify(body));
|
|
534
557
|
if (awaitedBytes > Math.min(maxTransferBytes, DEFAULT_MAX_BODY_BYTES)) throw new Error("proxy batch response limit exceeded");
|
|
@@ -545,7 +568,7 @@ function createResourceEngine(opts = {}) {
|
|
|
545
568
|
if (fresh) continue;
|
|
546
569
|
}
|
|
547
570
|
if ((failureUntil.get(key) || 0) > Date.now()) {
|
|
548
|
-
if (entry && allowStale) { markStale(entry); results[i] ??= cachedBodies[i]; continue; }
|
|
571
|
+
if (entry && allowStale) { markStale(entry, true); results[i] ??= cachedBodies[i]; continue; }
|
|
549
572
|
return sendJson(res, 502, { error: "upstream unavailable and no cached response" }, { "x-fad-proxy": "error" });
|
|
550
573
|
}
|
|
551
574
|
let promise = itemInflight.get(key);
|
|
@@ -559,7 +582,7 @@ function createResourceEngine(opts = {}) {
|
|
|
559
582
|
stats.misses++;
|
|
560
583
|
}
|
|
561
584
|
if (results[i] === undefined) waits.push(promise.then(body => { assignResult(i, body); }, error => {
|
|
562
|
-
if (entry && allowStale) { stats.stale++; markStale(entry); assignResult(i, cachedBodies[i]); }
|
|
585
|
+
if (entry && allowStale) { stats.stale++; markStale(entry, true, error); assignResult(i, cachedBodies[i]); }
|
|
563
586
|
else throw error;
|
|
564
587
|
}));
|
|
565
588
|
}
|
|
@@ -574,7 +597,7 @@ function createResourceEngine(opts = {}) {
|
|
|
574
597
|
stats.upstream++;
|
|
575
598
|
const bodies = await withUpstream(async signal => {
|
|
576
599
|
const up = await fetcher(request.url, { ...request.init, headers, signal, redirect: "follow" });
|
|
577
|
-
if (!up.ok) {
|
|
600
|
+
if (!up.ok) { const error=Object.assign(new Error(`upstream returned ${up.status}`),{status:up.status,retryAfterS:retryAfterSeconds(up.headers.get('retry-after'))}); await up.body?.cancel(); throw error; }
|
|
578
601
|
return subset.split(await boundedJson(up, signal));
|
|
579
602
|
});
|
|
580
603
|
if (bodies.length !== reserved.length) throw new Error("incomplete provider batch response");
|
|
@@ -590,7 +613,7 @@ function createResourceEngine(opts = {}) {
|
|
|
590
613
|
}
|
|
591
614
|
} catch (error) {
|
|
592
615
|
stats.errors++;
|
|
593
|
-
for (const row of reserved) { if (!(error instanceof UpstreamDenied)) rememberFailure(row.key); row.reject(error); }
|
|
616
|
+
for (const row of reserved) { if (!(error instanceof UpstreamDenied) && error.status!==429) rememberFailure(row.key); row.reject(error); }
|
|
594
617
|
} finally {
|
|
595
618
|
for (const row of reserved) { row.release(); itemInflight.delete(row.key); }
|
|
596
619
|
}
|
|
@@ -601,7 +624,7 @@ function createResourceEngine(opts = {}) {
|
|
|
601
624
|
if (error instanceof UpstreamDenied) return sendJson(res, 503, { error: error.message }, { "x-fad-proxy": "denied", "retry-after": String(error.retryAfterS) });
|
|
602
625
|
return sendJson(res, 502, { error: error.message }, { "x-fad-proxy": "error" });
|
|
603
626
|
}
|
|
604
|
-
return sendJson(res, 200, batch.merge(results), { "x-fad-proxy": oldestStale != null ? "stale" : reserved.length ? "miss" : "hit",
|
|
627
|
+
return sendJson(res, 200, batch.merge(results), { "x-fad-proxy": oldestStale != null ? "stale" : reserved.length ? "miss" : "hit",...(oldestStale != null ? {'x-fad-proxy-reason':staleFailure?'refresh-failed':'revalidating'} : {}),...(quotaFailure?{'x-fad-proxy-refresh-status':String(quotaFailure.status),'x-fad-proxy-refresh-cause':quotaFailure.cause,...(quotaFailure.retryAfterS!=null?{'retry-after':String(quotaFailure.retryAfterS)}:{})}:{}),
|
|
605
628
|
"x-fad-proxy-fetched-at": new Date(oldestStale ?? oldestFetchedAt).toISOString() });
|
|
606
629
|
}
|
|
607
630
|
|
|
@@ -620,6 +643,64 @@ function createResourceEngine(opts = {}) {
|
|
|
620
643
|
},
|
|
621
644
|
});
|
|
622
645
|
|
|
646
|
+
// Providers declare bounded snapshot projections; the relay owns acquisition,
|
|
647
|
+
// credential isolation and retries, and never sends the complete catalogue.
|
|
648
|
+
const snapshotProjections = new Map();
|
|
649
|
+
function snapshotProjection(provider, spec) {
|
|
650
|
+
if (!spec || typeof spec.id !== 'string' || typeof spec.validate !== 'function' || typeof spec.project !== 'function'
|
|
651
|
+
|| !Number.isSafeInteger(spec.maxSourceBytes) || spec.maxSourceBytes < 1
|
|
652
|
+
|| !Number.isSafeInteger(spec.ttlMs) || spec.ttlMs < 1) throw Error('Invalid provider snapshot projection');
|
|
653
|
+
const id = `${provider.id}:${spec.id}`;
|
|
654
|
+
if (!snapshotProjections.has(id)) snapshotProjections.set(id, require('./snapshot-projection').createSnapshotProjection({
|
|
655
|
+
store, ttlMs: overrideTtlMs || spec.ttlMs, allowStale, stats, maxEntries,
|
|
656
|
+
maxSourceBytes: Math.min(maxTransferBytes, spec.maxSourceBytes), maxResponseBytes: maxBodyBytes,
|
|
657
|
+
validate: spec.validate, project: spec.project,
|
|
658
|
+
load: async ({request, reqHeaders, ctx}, limit) => {
|
|
659
|
+
admitOrThrow(request.url, ctx);
|
|
660
|
+
return withUpstream(async signal => {
|
|
661
|
+
stats.upstream++;
|
|
662
|
+
const response=await fetcher(request.url,{headers:upstreamHeadersFor(request.url,reqHeaders,keys),signal,redirect:'error'});
|
|
663
|
+
if(!response.ok || !response.body){await response.body?.cancel();throw Object.assign(Error(`Source snapshot HTTP ${response.status}`),{status:response.status,retryAfterS:retryAfterSeconds(response.headers.get('retry-after'))});}
|
|
664
|
+
const rawLength=response.headers.get('content-length');
|
|
665
|
+
const encoding=response.headers.get('content-encoding');
|
|
666
|
+
const declared=rawLength && (!encoding || encoding.toLowerCase()==='identity') && /^\d+$/.test(rawLength) ? Number(rawLength) : null;
|
|
667
|
+
if(declared!==null && (!Number.isSafeInteger(declared)||declared>limit)){await response.body.cancel();throw Error('Source snapshot exceeds byte limit');}
|
|
668
|
+
// When the origin provides a valid length, avoid retaining every chunk and
|
|
669
|
+
// then allocating a second full copy during concatenation.
|
|
670
|
+
const buffer=declared!==null?Buffer.allocUnsafe(declared):null,chunks=[];let size=0;
|
|
671
|
+
for await(const chunk of response.body){const next=size+chunk.length;if(next>limit || buffer && next>declared)throw Error('Source snapshot exceeds byte limit');if(buffer)buffer.set(chunk,size);else chunks.push(Buffer.from(chunk));size=next;}
|
|
672
|
+
if(buffer && size!==declared)throw Error('Source snapshot length mismatch');
|
|
673
|
+
return buffer||Buffer.concat(chunks,size);
|
|
674
|
+
});
|
|
675
|
+
},
|
|
676
|
+
}));
|
|
677
|
+
return snapshotProjections.get(id);
|
|
678
|
+
}
|
|
679
|
+
function snapshotFailureHeaders(error) {
|
|
680
|
+
if (!error) return {};
|
|
681
|
+
const cause=error instanceof UpstreamDenied?'admission':error.status===429?'rate-limit':'upstream-http';
|
|
682
|
+
return {...(error.status>=400&&error.status<=599?{'x-fad-proxy-refresh-status':String(error.status),'x-fad-proxy-refresh-cause':cause}:{}),
|
|
683
|
+
...(Number.isFinite(error.retryAfterS)?{'retry-after':String(error.retryAfterS)}:{})};
|
|
684
|
+
}
|
|
685
|
+
const debianProjection = require('./snapshot-projection').createSnapshotProjection({
|
|
686
|
+
store, ttlMs: overrideTtlMs || 4 * 3600000, allowStale, stats, maxEntries,
|
|
687
|
+
maxResponseBytes: maxBodyBytes,
|
|
688
|
+
validate: (body, {list}) => {
|
|
689
|
+
const text=new TextDecoder('utf-8',{fatal:true}).decode(body);
|
|
690
|
+
const valid=list==='CVE' ? /^CVE-\d{4}-\d{4,}/m.test(text) : new RegExp('^\\[[^\\]]+\\] '+list+'-\\d+-\\d+','m').test(text);
|
|
691
|
+
if(!valid || /^\s*</.test(text))throw Error('Invalid Debian tracker source list');
|
|
692
|
+
},
|
|
693
|
+
project: (body,params) => require('../system-inventory/historical-debian').projectDebianList(body,params),
|
|
694
|
+
load: async ({request,reqHeaders,ctx},limit) => {
|
|
695
|
+
admitOrThrow(request.url,ctx);
|
|
696
|
+
return withUpstream(async signal => {
|
|
697
|
+
stats.upstream++;const response=await fetcher(request.url,{headers:upstreamHeadersFor(request.url,reqHeaders,keys),signal,redirect:'error'});
|
|
698
|
+
if(!response.ok || !response.body){await response.body?.cancel();throw Error(`Debian tracker HTTP ${response.status}`);}
|
|
699
|
+
if(Number(response.headers.get('content-length'))>limit){await response.body.cancel();throw Error('Debian tracker source exceeds limit');}
|
|
700
|
+
const chunks=[];let size=0;for await(const chunk of response.body){size+=chunk.length;if(size>limit)throw Error('Debian tracker source exceeds limit');chunks.push(Buffer.from(chunk));}return Buffer.concat(chunks,size);
|
|
701
|
+
});
|
|
702
|
+
},
|
|
703
|
+
});
|
|
623
704
|
/**
|
|
624
705
|
* One typed resource request → an answer on `res`. An invalid request is a 400; a
|
|
625
706
|
* failure once the request is under way rejects, and the transport answers 502.
|
|
@@ -641,6 +722,21 @@ function createResourceEngine(opts = {}) {
|
|
|
641
722
|
// An unrelated client apiKey must not split its catalogue or in-flight downloads.
|
|
642
723
|
const cacheHeaders = provider.id === "wordfence"
|
|
643
724
|
? { authorization: effectiveHeaders.authorization } : effectiveHeaders;
|
|
725
|
+
const projectionSpec=provider.snapshotProjection?.(payload.type,payload.params);
|
|
726
|
+
if(projectionSpec){
|
|
727
|
+
try {
|
|
728
|
+
const project=snapshotProjection(provider,projectionSpec);
|
|
729
|
+
const key=providerKey(provider.id,`private-snapshot:${projectionSpec.id}`,projectionSpec.sourceParams||{},cacheHeaders);
|
|
730
|
+
const result=await project(key,{request,reqHeaders,ctx},payload.params);
|
|
731
|
+
res.writeHead(200,{'content-type':projectionSpec.contentType||'application/json','content-length':result.body.length,
|
|
732
|
+
'x-fad-proxy':result.stale?'stale':'projection','x-fad-proxy-fetched-at':new Date(result.fetchedAt).toISOString(),
|
|
733
|
+
'x-vigievuln-source-sha256':result.sha256,...(result.stale?{'x-fad-proxy-reason':'refresh-failed',...snapshotFailureHeaders(result.failure)}:{})});
|
|
734
|
+
return res.end(result.body);
|
|
735
|
+
} catch(error) {
|
|
736
|
+
const status=error instanceof UpstreamDenied?503:error.status>=400&&error.status<=599?error.status:502;
|
|
737
|
+
return sendJson(res,status,{error:error.message},{'x-fad-proxy':error instanceof UpstreamDenied?'denied':'error',...snapshotFailureHeaders(error)});
|
|
738
|
+
}
|
|
739
|
+
}
|
|
644
740
|
if (payload.provider === "wordfence" && payload.type === "software") {
|
|
645
741
|
// Internal cache key: never exposed as a downloadable resource operation.
|
|
646
742
|
const key = providerKey("wordfence", "projection-feed-v1", {}, cacheHeaders);
|
|
@@ -650,13 +746,21 @@ function createResourceEngine(opts = {}) {
|
|
|
650
746
|
"x-fad-proxy-fetched-at": new Date(result.fetchedAt).toISOString() });
|
|
651
747
|
return res.end(result.body);
|
|
652
748
|
}
|
|
749
|
+
if(payload.provider==='debian' && payload.type==='list'){
|
|
750
|
+
const {commit,list}=payload.params;
|
|
751
|
+
const key=require('../providers/common').requestKey('debian','private-list-v1',{commit,list},'');
|
|
752
|
+
const result=await debianProjection(key,{request,reqHeaders,ctx,list},payload.params);
|
|
753
|
+
res.writeHead(200,{'content-type':'text/plain; charset=utf-8','content-length':result.body.length,'x-fad-proxy':result.stale?'stale':'projection','x-fad-proxy-fetched-at':new Date(result.fetchedAt).toISOString(),'x-vigievuln-source-sha256':result.sha256});
|
|
754
|
+
return res.end(result.body);
|
|
755
|
+
}
|
|
653
756
|
const cacheKey = providerKey(payload.provider, payload.type, payload.params, cacheHeaders);
|
|
654
|
-
return handleCached(res, { target: request.url, cacheKey, reqHeaders,
|
|
757
|
+
return handleCached(res, { target: request.url, cacheKey, reqHeaders, revalidate:payload.revalidate === true,
|
|
655
758
|
resource: { provider: payload.provider, type: payload.type, params: payload.params }, ctx,
|
|
656
759
|
method: request.init?.method || "GET", body: request.init?.body,
|
|
657
760
|
ttlMs: overrideTtlMs || provider.ttlMs || defaultTtlMs,
|
|
658
761
|
cacheLimitBytes: payload.provider === "github" && payload.type === "cve-archive"
|
|
659
|
-
? 1024 * 1024 * 1024 :
|
|
762
|
+
? 1024 * 1024 * 1024 : payload.provider === "osvdb" && payload.type === "ecosystem-archive"
|
|
763
|
+
? Math.min(maxTransferBytes, 512 * 1024 * 1024) : maxBodyBytes });
|
|
660
764
|
}
|
|
661
765
|
|
|
662
766
|
return {
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Shared bounded source snapshots stay on the relay. Each caller receives only
|
|
3
|
+
// its projection, with the original observation time and full source hash.
|
|
4
|
+
const {gzipSync,gunzipSync}=require('node:zlib');
|
|
5
|
+
const {createHash}=require('node:crypto');
|
|
6
|
+
function createSnapshotProjection({store,load,validate,project,ttlMs,allowStale,stats,maxEntries=1000,maxSourceBytes=128*1024*1024,maxResponseBytes=32*1024*1024,now=Date.now}){
|
|
7
|
+
const flights=new Map(),failures=new Map();let memo=null;
|
|
8
|
+
async function source(key,request){
|
|
9
|
+
if(flights.has(key)){stats.coalesced++;return flights.get(key);}
|
|
10
|
+
const work=(async()=>{
|
|
11
|
+
let previous=null;const entry=await store.get(key);
|
|
12
|
+
if(entry && entry.fetchedAt>0 && entry.fetchedAt<=now() && entry.bytes<=maxSourceBytes){
|
|
13
|
+
const release=store.acquire(entry);try{
|
|
14
|
+
if(memo?.key===key && memo.fetchedAt===entry.fetchedAt && memo.bytes===entry.bytes)previous=memo;
|
|
15
|
+
else{const body=gunzipSync(await store.readBody(entry),{maxOutputLength:maxSourceBytes});await validate(body,request);previous=memo={key,body,fetchedAt:entry.fetchedAt,bytes:entry.bytes,sha256:createHash('sha256').update(body).digest('hex')};}
|
|
16
|
+
}catch{/* corrupt cached snapshots are never projected */}finally{release();}
|
|
17
|
+
}
|
|
18
|
+
if(previous && now()-previous.fetchedAt<Math.min(ttlMs,entry.ttlMs)){stats.hits++;return {...previous,stale:false};}
|
|
19
|
+
const failed=failures.get(key);
|
|
20
|
+
if(failed?.until>now()){if(previous&&allowStale){stats.stale++;return {...previous,stale:true,failure:failed.error};}throw failed.error;}
|
|
21
|
+
try{
|
|
22
|
+
stats.misses++;const body=await load(request,maxSourceBytes);
|
|
23
|
+
if(!Buffer.isBuffer(body)||!body.length||body.length>maxSourceBytes)throw Error('Invalid source snapshot size');
|
|
24
|
+
await validate(body,request);const compressed=gzipSync(body),fetchedAt=now();
|
|
25
|
+
if(compressed.length>Math.min(store.maxEntryBytes||maxSourceBytes,maxSourceBytes))throw Error('Source snapshot exceeds cache storage limit');
|
|
26
|
+
await store.put(key,compressed,{fetchedAt,ttlMs,contentType:'application/gzip',bytes:compressed.length});
|
|
27
|
+
memo={key,body,fetchedAt,bytes:compressed.length,sha256:createHash('sha256').update(body).digest('hex')};failures.delete(key);return {...memo,stale:false};
|
|
28
|
+
}catch(error){stats.errors++;for(const [k,v] of failures)if(v.until<=now())failures.delete(k);if(failures.size>=maxEntries)failures.delete(failures.keys().next().value);const delay=Number.isFinite(error.retryAfterS)?Math.max(1000,Math.min(604800000,error.retryAfterS*1000)):30000;failures.set(key,{until:now()+delay,error});if(previous&&allowStale){stats.stale++;return {...previous,stale:true,failure:error};}throw error;}
|
|
29
|
+
})();flights.set(key,work);try{return await work;}finally{flights.delete(key);}
|
|
30
|
+
}
|
|
31
|
+
return async(key,request,params)=>{const snapshot=await source(key,request),body=Buffer.from(await project(snapshot.body,params));if(body.length>maxResponseBytes)throw Error('Projected source response exceeds limit');return {body,fetchedAt:snapshot.fetchedAt,stale:snapshot.stale,sha256:snapshot.sha256,failure:snapshot.failure};};
|
|
32
|
+
}
|
|
33
|
+
module.exports={createSnapshotProjection};
|
|
@@ -57,8 +57,10 @@ const COMPOSER = T.str(/^[a-z0-9]+(?:[_.-][a-z0-9]+)*\/[a-z0-9]+(?:(?:[_.]|-{1,2
|
|
|
57
57
|
const OSV_ECOS = ["Maven", "npm", "PyPI", "Packagist", "NuGet", "Go", "RubyGems", "crates.io", "Hex", "Pub", "CRAN", "Hackage", "SwiftURL", "GitHub Actions"];
|
|
58
58
|
const OSV_NAME = T.str(/^[\x21-\x7e]+$/, 300), OSV_VERSION = T.str(/^[\x21-\x7e]+$/, 100);
|
|
59
59
|
const OSV_PAGE_TOKEN = T.str(/^[\x21-\x7e]+$/, 2048);
|
|
60
|
-
const
|
|
61
|
-
const
|
|
60
|
+
const scopedOsvEcosystem = T.str(/^[A-Za-z][A-Za-z0-9 ._+-]*:[A-Za-z0-9][A-Za-z0-9 ._:+-]*$/, 160);
|
|
61
|
+
const OSV_ECOSYSTEM = (value, at) => OSV_ECOS.includes(value) ? value : scopedOsvEcosystem(value, at);
|
|
62
|
+
const OSV_FLAT = T.obj({ ecosystem: OSV_ECOSYSTEM, name: OSV_NAME, version: OSV_VERSION, page_token: OSV_PAGE_TOKEN }, ["page_token"]);
|
|
63
|
+
const OSV_NESTED = T.obj({ package: T.obj({ ecosystem: OSV_ECOSYSTEM, name: OSV_NAME }), version: OSV_VERSION, page_token: OSV_PAGE_TOKEN }, ["page_token"]);
|
|
62
64
|
/** fad sends the flat form; OSV's own querybatch form ({ package: {…}, version }) is accepted too — both end flat. */
|
|
63
65
|
const OSV_QUERY = (v, at) => {
|
|
64
66
|
if (isPlain(v) && "package" in v) { const q = OSV_NESTED(v, at); return { ecosystem: q.package.ecosystem, name: q.package.name, version: q.version, ...(q.page_token ? { page_token: q.page_token } : {}) }; }
|
|
@@ -82,6 +84,17 @@ const RESOURCES = {
|
|
|
82
84
|
"pypi/package": T.obj({ name: T.str(/^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$/, 100) }),
|
|
83
85
|
"ruby/gem": T.obj({ name: T.str(/^[A-Za-z0-9_.-]+$/, 100) }),
|
|
84
86
|
"go/module-latest": T.obj({ module: T.str(/^[a-z0-9.!_~-]+(\/[A-Za-z0-9.!_~+-]+)*$/, 300) }),
|
|
87
|
+
"go/module-info": T.obj({ module: T.str(/^[a-z0-9.!_~-]+(\/[A-Za-z0-9.!_~+-]+)*$/, 300), version: T.str(/^v\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+incompatible)?$/, 150) }),
|
|
88
|
+
"alpine/package": T.obj({ name: T.str(/^[a-z0-9][a-z0-9+_.-]*$/, 200) }),
|
|
89
|
+
"nginx/advisories": NONE,
|
|
90
|
+
"freexian/index": T.obj({page:T.int(1,10000)}),
|
|
91
|
+
"freexian/advisory": T.obj({slug:T.str(/^ela-\d+-\d+-[a-z0-9][a-z0-9.+-]*$/,250)}),
|
|
92
|
+
"freexian/tracker": T.obj({packages:T.arr(T.str(/^[a-z0-9][a-z0-9+.-]*$/,200),1,1000)}),
|
|
93
|
+
"freexian/vulnerability": T.obj({id:CVE}),
|
|
94
|
+
"alpine/vulnerability": T.obj({ id: CVE }),
|
|
95
|
+
"debian/history": T.obj({ until: T.str(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/, 20) }),
|
|
96
|
+
"debian/source-version": T.obj({ name:T.str(/^[a-z0-9][a-z0-9+.-]*$/,200),version:T.str(/^[0-9][A-Za-z0-9.+:~\-]*$/,150) }),
|
|
97
|
+
"debian/list": T.obj({ commit: T.str(/^[a-f0-9]{40}$/, 40), list: T.oneOf(['CVE','DSA','DLA']), packages: T.arr(T.str(/^[a-z0-9][a-z0-9+.-]*$/, 200), 1, 1000) }),
|
|
85
98
|
"nuget/service-index": NONE,
|
|
86
99
|
"nuget/registration": T.obj({ name: T.str(/^[A-Za-z0-9_.-]+$/, 100) }),
|
|
87
100
|
"nuget/registration-page": T.obj({ path: T.str(/^\/[A-Za-z0-9_.\/-]+\.json$/, 300) }),
|
|
@@ -95,6 +108,7 @@ const RESOURCES = {
|
|
|
95
108
|
"github/cve-release": NONE,
|
|
96
109
|
"github/cve-maven": T.obj({ keys: T.arr(T.str(/^[pa]:[a-z0-9][a-z0-9._:+-]*$/, 220), 1, 200) }),
|
|
97
110
|
"github/cve-npm": T.obj({ names: T.arr(T.str(/^(@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9._~-][a-z0-9._~-]*$/, 214), 1, 200) }),
|
|
111
|
+
"github/cve-packages": T.obj({ packages: T.arr(T.obj({ecosystem:T.str(/^(?:[A-Za-z0-9][A-Za-z0-9:._+-]*|system:deb:debian:\*)$/,150),name:OSV_NAME}),1,200) }),
|
|
98
112
|
"vigievuln/advisories": T.obj({ packages: T.arr(T.obj({ecosystem:T.oneOf(['Maven','npm']),name:OSV_NAME}),1,200) }),
|
|
99
113
|
"github/cve-archive": T.obj({ tag: T.str(/^[A-Za-z0-9._-]+$/, 100), name: T.str(/^[A-Za-z0-9._-]+\.zip$/i, 200) }),
|
|
100
114
|
"github/publisher-advisories": T.obj({ repo: T.str(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/, 200), page: T.int(1, 1000), perPage: T.int(1, 100) }, ["page", "perPage"]),
|
|
@@ -105,10 +119,11 @@ const RESOURCES = {
|
|
|
105
119
|
slug: T.str(/^[a-z0-9][a-z0-9._-]*$/, 200) }), 1, 100) }),
|
|
106
120
|
"wordpress/checksums": T.obj({ version: T.str(/^\d+(\.\d+){1,3}$/, 20), locale: T.str(/^[a-z]{2,3}(_[A-Z]{2})?$/, 10) }),
|
|
107
121
|
"drupal/advisories": T.obj({ packages: T.arr(T.str(/^drupal\/[a-z0-9_]+$/, 100), 1, 100) }),
|
|
108
|
-
"osvdb/ecosystem-archive": T.obj({ ecosystem: T.oneOf(OSV_ECOS) }),
|
|
122
|
+
"osvdb/ecosystem-archive": T.obj({ ecosystem: T.oneOf([...OSV_ECOS, "Debian", "Ubuntu", "Alpine", "AlmaLinux", "Rocky Linux", "Red Hat", "SUSE", "openSUSE"]) }),
|
|
109
123
|
"retire/signatures": NONE,
|
|
110
124
|
"euvd/cve-mapping": NONE,
|
|
111
125
|
"euvd/cves": T.obj({ ids: T.arr(CVE, 1, 100) }),
|
|
126
|
+
"euvd/vulnerability": T.obj({ id: T.str(/^EUVD-\d{4}-\d{1,12}$/, 24) }),
|
|
112
127
|
"euvd/exploited": T.obj({ page: T.int(0, 1000) }),
|
|
113
128
|
"certfr/cves": T.obj({ ids: T.arr(CVE, 1, 100) }),
|
|
114
129
|
"certfr/index": T.obj({ kind: T.oneOf(["avis", "alerte"]) }),
|
|
@@ -132,10 +147,12 @@ const HEADERS = {
|
|
|
132
147
|
/** The /v1/resource document → { provider, type, params, headers } or ValidationError. */
|
|
133
148
|
function validateResource(body) {
|
|
134
149
|
if (!isPlain(body)) throw new ValidationError("a JSON object is expected");
|
|
135
|
-
for (const k of Object.keys(body)) if (!["provider", "type", "params", "headers"].includes(k)) throw new ValidationError(`${k}: unexpected field`, k);
|
|
150
|
+
for (const k of Object.keys(body)) if (!["provider", "type", "params", "headers", "revalidate"].includes(k)) throw new ValidationError(`${k}: unexpected field`, k);
|
|
136
151
|
if (typeof body.provider !== "string" || typeof body.type !== "string") throw new ValidationError("provider and type are required strings");
|
|
137
152
|
const schema = RESOURCES[`${body.provider}/${body.type}`];
|
|
138
153
|
if (!schema) throw new ValidationError(`unknown resource ${String(body.provider).slice(0, 40)}/${String(body.type).slice(0, 40)}`, "type");
|
|
154
|
+
if (body.revalidate !== undefined && typeof body.revalidate !== 'boolean') throw new ValidationError('revalidate: boolean expected', 'revalidate');
|
|
155
|
+
if (body.revalidate && !require('../providers').getProvider(body.provider).revalidateTypes?.includes(body.type)) throw new ValidationError('revalidate: unsupported resource', 'revalidate');
|
|
139
156
|
const params = schema(body.params === undefined ? {} : body.params, "params");
|
|
140
157
|
let headers = {};
|
|
141
158
|
if (body.headers !== undefined) {
|
|
@@ -146,7 +163,7 @@ function validateResource(body) {
|
|
|
146
163
|
headers[k] = HEADERS[k](value, `headers.${k}`);
|
|
147
164
|
}
|
|
148
165
|
}
|
|
149
|
-
return { provider: body.provider, type: body.type, params, headers };
|
|
166
|
+
return { provider: body.provider, type: body.type, params, headers, ...(body.revalidate ? {revalidate:true} : {}) };
|
|
150
167
|
}
|
|
151
168
|
|
|
152
169
|
/** Query parameters of one route: spec = { name: validatorFromString }. Unknown → 400. */
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// A related upstream CVE is evidence about that CVE, not an alias or a
|
|
3
|
+
// package-level applicability assertion for every issue in an advisory.
|
|
4
|
+
function relatedRisk(cve, sourceField) {
|
|
5
|
+
return cve?.riskEvidence?.relationship === 'upstream' && cve?.[sourceField] === cve.riskEvidence.source;
|
|
6
|
+
}
|
|
7
|
+
function relatedSignal(cve, field) {
|
|
8
|
+
const evidence=cve?.[field+'Evidence'];
|
|
9
|
+
if(evidence?.relationship)return evidence.relationship==='upstream';
|
|
10
|
+
const own=[cve?.id,...(cve?.aliases||[])].some(id=>typeof id==='string' && /^CVE-\d{4}-\d{4,}$/i.test(id));
|
|
11
|
+
return !own && (cve?.upstream||[]).some(id=>typeof id==='string' && /^CVE-\d{4}-\d{4,}$/i.test(id));
|
|
12
|
+
}
|
|
13
|
+
function evidenceObject(cve) {
|
|
14
|
+
return { ...(cve?.riskEvidence?{risk:cve.riskEvidence}:{}),...(cve?.nvdEvidence?.records?.length?{nvd:cve.nvdEvidence.records}:{}),
|
|
15
|
+
...(cve?.cveEvidence?.length?{cves:cve.cveEvidence}:{}),...(cve?.euvdDetails?{euvd:cve.euvdDetails}:{}),...(cve?.kevEvidence?{kev:cve.kevEvidence}:{}),...(cve?.epssEvidence?{epss:cve.epssEvidence}:{}),
|
|
16
|
+
...(cve?.upstream?.length?{upstream:cve.upstream}:{}),...(cve?.related?.length?{related:cve.related}:{}) };
|
|
17
|
+
}
|
|
18
|
+
module.exports={relatedRisk,relatedSignal,evidenceObject};
|
package/lib/sarif-export.js
CHANGED
|
@@ -71,6 +71,7 @@ function buildSarif(matches, opts = {}) {
|
|
|
71
71
|
const id = m.cve?.id;
|
|
72
72
|
if (!id) continue;
|
|
73
73
|
const cve = m.cve;
|
|
74
|
+
const risk=require('./risk-evidence'),scoreSafe=!risk.relatedRisk(cve,'scoreSource'),severitySafe=!risk.relatedRisk(cve,'severitySource'),kevRelated=risk.relatedSignal(cve,'kev'),epssRelated=risk.relatedSignal(cve,'epss');
|
|
74
75
|
|
|
75
76
|
if (!rulesById.has(id)) {
|
|
76
77
|
const rule = {
|
|
@@ -85,9 +86,9 @@ function buildSarif(matches, opts = {}) {
|
|
|
85
86
|
properties: {},
|
|
86
87
|
};
|
|
87
88
|
// GitHub Code Scanning reads `security-severity` (a CVSS number string).
|
|
88
|
-
if (cve.score != null) rule.properties["security-severity"] = String(cve.score);
|
|
89
|
+
if (scoreSafe && cve.score != null) rule.properties["security-severity"] = String(cve.score);
|
|
89
90
|
const tags = ["security", "external/cwe", "dependency"];
|
|
90
|
-
if (cve.kev) tags.push("known-exploited", "cisa-kev");
|
|
91
|
+
if (cve.kev && !kevRelated) tags.push("known-exploited", "cisa-kev");
|
|
91
92
|
if (euvdExploited(cve)) tags.push("enisa-exploited");
|
|
92
93
|
rule.properties.tags = tags;
|
|
93
94
|
if (Array.isArray(cve.cwes)) rule.properties.cwe = cve.cwes;
|
|
@@ -97,8 +98,8 @@ function buildSarif(matches, opts = {}) {
|
|
|
97
98
|
const coord = depCoord(m.dep);
|
|
98
99
|
const purl = purlFor(m.dep);
|
|
99
100
|
const bits = [`${coord}@${m.dep.version || "?"}`];
|
|
100
|
-
if (cve.kev) bits.push("CISA-KEV (exploited)");
|
|
101
|
-
if (cve.epssPercentile != null) bits.push(
|
|
101
|
+
if (cve.kev) bits.push(kevRelated ? "Related upstream CVE listed in CISA-KEV" : "CISA-KEV (exploited)");
|
|
102
|
+
if (cve.epssPercentile != null) bits.push(`${epssRelated ? "Related upstream CVE EPSS" : "EPSS"} ${Math.round(cve.epssPercentile * 100)}%`);
|
|
102
103
|
if (cve.fixVersion) bits.push(`advisory-specific candidate ${cve.fixVersion}; package-wide safety unverified`);
|
|
103
104
|
const text = `${id} in ${bits.join(" · ")}${cve.description ? ` — ${cve.description.slice(0, 300)}` : ""}`;
|
|
104
105
|
|
|
@@ -109,9 +110,16 @@ function buildSarif(matches, opts = {}) {
|
|
|
109
110
|
|
|
110
111
|
const props = {};
|
|
111
112
|
if (purl) props.purl = purl;
|
|
112
|
-
if (
|
|
113
|
-
if (
|
|
114
|
-
if (
|
|
113
|
+
if (m.dep.artifactTargetId) props.artifactTargetId = m.dep.artifactTargetId;
|
|
114
|
+
if (m.dep.artifactPath) props.artifactPath = m.dep.artifactPath;
|
|
115
|
+
if (m.dep.artifactTargetId) for (const key of ["manager", "sourceName", "sourceVersion", "distribution", "binaryEvidence", "installEvidence", "sbomEvidence", "osPackageOwners"]) if (m.dep[key]) props[key] = m.dep[key];
|
|
116
|
+
const riskEvidence=risk.evidenceObject(cve);if(Object.keys(riskEvidence).length)props.relatedRiskEvidence=riskEvidence;
|
|
117
|
+
if(cve.historicalEvidence)props.historicalEvidence=cve.historicalEvidence;
|
|
118
|
+
const applicability=require('./applicability-evidence').applicabilityEvidence(cve);if(applicability.length)props.applicabilityEvidence=applicability;
|
|
119
|
+
if(cve.vendorEvidence)props.vendorEvidence=cve.vendorEvidence;
|
|
120
|
+
if (cve.epssScore != null && !epssRelated) props.epss = cve.epssScore;
|
|
121
|
+
if (cve.epssPercentile != null && !epssRelated) props.epssPercentile = cve.epssPercentile;
|
|
122
|
+
if (cve.kev && !kevRelated) props.kev = true;
|
|
115
123
|
if (euvdExploited(cve)) props.euvdExploited = true;
|
|
116
124
|
const euRefs = europeanReferences(cve);
|
|
117
125
|
if (euRefs.length) props.europeanReferences = euRefs.map(r => r.id);
|
|
@@ -126,10 +134,10 @@ function buildSarif(matches, opts = {}) {
|
|
|
126
134
|
|
|
127
135
|
results.push({
|
|
128
136
|
ruleId: id,
|
|
129
|
-
level: sarifLevel(cve.severity),
|
|
137
|
+
level: sarifLevel(severitySafe?cve.severity:"UNKNOWN"),
|
|
130
138
|
message: { text },
|
|
131
139
|
...(locations.length ? { locations } : {}),
|
|
132
|
-
partialFingerprints: { fadKey: m.findingId || `${coord}@${m.dep.version || "?"}|${id}` },
|
|
140
|
+
partialFingerprints: { fadKey: m.findingId || `${coord}@${m.dep.version || "?"}|${id}${m.dep.artifactTargetId ? `|${m.dep.artifactTargetId}` : ""}` },
|
|
133
141
|
properties: props,
|
|
134
142
|
});
|
|
135
143
|
}
|
package/lib/sbom-export.js
CHANGED
|
@@ -77,23 +77,34 @@ function buildCycloneDx(resolvedDeps, cveMatches, opts = {}) {
|
|
|
77
77
|
const variantsByCoord = new Map();
|
|
78
78
|
const dynamicComponents = new Map();
|
|
79
79
|
for (const dep of resolvedDeps.values()) {
|
|
80
|
-
|
|
80
|
+
// These ecosystems retain every scanned version on one coordinate record.
|
|
81
|
+
// Keep each version so findings can reference the correct component.
|
|
82
|
+
const versions = ["maven", "npm", "pypi"].includes(dep.ecosystem) && !dep.artifactTargetId && dep.provenance !== "embedded"
|
|
83
|
+
? [...new Set((dep.versions || []).filter(v => v && !/\$\{/.test(String(v))))] : [];
|
|
84
|
+
const variants = (versions.length
|
|
85
|
+
? versions.flatMap(version => variantsFor({ ...dep, version }, projectInfo.src))
|
|
86
|
+
: variantsFor(dep, projectInfo.src)).map(v => dep.artifactTargetId ? { ...v, ref: dep.coordKey } : v);
|
|
81
87
|
variantsByCoord.set(dep.coordKey, variants);
|
|
82
88
|
for (const variant of variants) {
|
|
83
89
|
const item = variant.dep;
|
|
84
90
|
const purl = purlFor(item);
|
|
85
91
|
const comp = { type: "library", name: item.name || item.artifactId, version: item.version || undefined };
|
|
86
92
|
if (item.namespace || item.groupId) comp.group = item.namespace || item.groupId;
|
|
87
|
-
const ref = variant.ref || bomRefFor(item, purl);
|
|
93
|
+
const ref = item.artifactTargetId ? item.coordKey : (variant.ref || bomRefFor(item, purl));
|
|
88
94
|
if (ref) comp["bom-ref"] = ref;
|
|
89
95
|
if (purl) comp.purl = purl;
|
|
90
96
|
const lic = licByCoord.get(dep.coordKey);
|
|
91
97
|
if (lic) comp.licenses = licenseEntry(lic);
|
|
92
98
|
if (variant.location) comp.properties = [{ name: "fad:location", value: variant.location }];
|
|
99
|
+
if (item.artifactTargetId) comp.properties = [...(comp.properties || []), { name: "fad:artifact-id", value: String(item.artifactTargetId) }, ...(item.artifactPath ? [{ name: "fad:artifact-path", value: String(item.artifactPath) }] : [])];
|
|
100
|
+
if (item.artifactTargetId) {
|
|
101
|
+
for (const [key, value] of Object.entries({ manager: item.manager, sourceName: item.sourceName, sourceVersion: item.sourceVersion, distribution: item.distribution && JSON.stringify(item.distribution), binaryEvidence: item.binaryEvidence && JSON.stringify(item.binaryEvidence), installEvidence: item.installEvidence && JSON.stringify(item.installEvidence), sbomEvidence: item.sbomEvidence && JSON.stringify(item.sbomEvidence), osPackageOwners: item.osPackageOwners?.length && JSON.stringify(item.osPackageOwners) }))
|
|
102
|
+
if (value) comp.properties.push({ name: `fad:${key}`, value: String(value) });
|
|
103
|
+
}
|
|
93
104
|
if (item.provenance === "embedded") {
|
|
94
|
-
comp.properties = [
|
|
105
|
+
comp.properties = [...(comp.properties || []),
|
|
95
106
|
{ name: "fad:provenance", value: "embedded" },
|
|
96
|
-
...((item.manifestPaths || [])[0] ? [{ name: "fad:location", value: item.manifestPaths[0] }] : []),
|
|
107
|
+
...(!variant.location && (item.manifestPaths || [])[0] ? [{ name: "fad:location", value: item.manifestPaths[0] }] : []),
|
|
97
108
|
];
|
|
98
109
|
}
|
|
99
110
|
components.push(comp);
|
|
@@ -123,17 +134,19 @@ function buildCycloneDx(resolvedDeps, cveMatches, opts = {}) {
|
|
|
123
134
|
let v = byCve.get(id);
|
|
124
135
|
if (!v) {
|
|
125
136
|
const cve = m.cve;
|
|
137
|
+
const risk=require('./risk-evidence'), scoreSafe=!risk.relatedRisk(cve,'scoreSource'), severitySafe=!risk.relatedRisk(cve,'severitySource');
|
|
138
|
+
const score=scoreSafe?cve.score:null;
|
|
139
|
+
const ownSeverity=severitySafe && cve.severity && String(cve.severity).toUpperCase()!=='UNKNOWN';
|
|
126
140
|
v = {
|
|
127
141
|
"bom-ref": `vuln-${id}`,
|
|
128
142
|
id,
|
|
129
143
|
source: advisorySource(id, m.source),
|
|
130
|
-
ratings:
|
|
144
|
+
ratings: score != null || (!scoreSafe && ownSeverity) ? [{
|
|
131
145
|
// A merged finding does not identify which source supplied the score.
|
|
132
146
|
...(m.source && !m.source.includes('+') ? { source: { name: advisorySource(id, m.source).name } } : {}),
|
|
133
|
-
score:
|
|
134
|
-
severity:
|
|
135
|
-
|
|
136
|
-
...(cve.cvssVector ? { vector: cve.cvssVector } : {}),
|
|
147
|
+
...(score != null ? {score,method:cvssMethod(cve.cvssVersion)} : {}),
|
|
148
|
+
...(severitySafe ? {severity:cdxSeverity(cve.severity)} : {}),
|
|
149
|
+
...(score != null && cve.cvssVector ? { vector: cve.cvssVector } : {}),
|
|
137
150
|
}] : [],
|
|
138
151
|
...(Array.isArray(cve.cwes) && cve.cwes.length ? { cwes: cve.cwes.map(cweNum).filter(n => n != null) } : {}),
|
|
139
152
|
...(cve.description ? { description: cve.description } : {}),
|
|
@@ -143,9 +156,20 @@ function buildCycloneDx(resolvedDeps, cveMatches, opts = {}) {
|
|
|
143
156
|
};
|
|
144
157
|
byCve.set(id, v);
|
|
145
158
|
}
|
|
159
|
+
const evidence=require('./risk-evidence').evidenceObject(m.cve);
|
|
160
|
+
if(Object.keys(evidence).length){const value=JSON.stringify(evidence);if(!v.properties.some(p=>p.name==='vigievuln:related-risk-evidence' && p.value===value))v.properties.push({name:'vigievuln:related-risk-evidence',value});}
|
|
161
|
+
if(m.cve.historicalEvidence){const value=JSON.stringify({refs:refs.filter(Boolean),evidence:m.cve.historicalEvidence});if(!v.properties.some(p=>p.name==='vigievuln:historical-evidence'&&p.value===value))v.properties.push({name:'vigievuln:historical-evidence',value});}
|
|
162
|
+
for(const evidence of require('./applicability-evidence').applicabilityEvidence(m.cve)){const value=JSON.stringify({refs:refs.filter(Boolean),...evidence});if(!v.properties.some(p=>p.name==='vigievuln:applicability-evidence'&&p.value===value))v.properties.push({name:'vigievuln:applicability-evidence',value});}
|
|
163
|
+
if(m.cve.vendorEvidence){const value=JSON.stringify({refs:refs.filter(Boolean),evidence:m.cve.vendorEvidence});if(!v.properties.some(p=>p.name==='vigievuln:vendor-evidence'&&p.value===value))v.properties.push({name:'vigievuln:vendor-evidence',value});}
|
|
146
164
|
for (const source of String(m.source || 'cache').split('+').filter(Boolean))
|
|
147
165
|
if (!v.properties.some(p => p.name === 'vigievuln:source' && p.value === source)) v.properties.push({ name: 'vigievuln:source', value: source });
|
|
148
166
|
for (const ref of refs) if (ref && !v.affects.some(a => a.ref === ref)) v.affects.push({ ref });
|
|
167
|
+
// Triage is per affected component, not per CVE. A global analysis.state
|
|
168
|
+
// would incorrectly clear other products sharing the same advisory.
|
|
169
|
+
if (m.suppressed) v.properties.push({ name: "vigievuln:triage", value: JSON.stringify({
|
|
170
|
+
refs: refs.filter(Boolean), suppressed: true, reason: m.suppressedReason || "ignored",
|
|
171
|
+
...(m.suppressionStatus ? { status: m.suppressionStatus } : {}),
|
|
172
|
+
}) });
|
|
149
173
|
if (m.cpeFiltered) v.properties.push({ name: "fad:cpe-filtered", value: "true" });
|
|
150
174
|
// One property per physical occurrence: consumers must be able to relate the SBOM
|
|
151
175
|
// entry to the report's finding identity and its application relation.
|
|
@@ -169,9 +193,11 @@ function buildCycloneDx(resolvedDeps, cveMatches, opts = {}) {
|
|
|
169
193
|
|
|
170
194
|
function buildVulnProps(cve) {
|
|
171
195
|
const props = [];
|
|
172
|
-
|
|
173
|
-
if
|
|
174
|
-
if (cve.
|
|
196
|
+
const risk=require('./risk-evidence');const evidence=risk.evidenceObject(cve);
|
|
197
|
+
if(Object.keys(evidence).length)props.push({name:'vigievuln:related-risk-evidence',value:JSON.stringify(evidence)});
|
|
198
|
+
if (cve.epssScore != null && !risk.relatedSignal(cve,'epss')) props.push({ name: "fad:epss", value: String(cve.epssScore) });
|
|
199
|
+
if (cve.epssPercentile != null && !risk.relatedSignal(cve,'epss')) props.push({ name: "fad:epssPercentile", value: String(cve.epssPercentile) });
|
|
200
|
+
if (cve.kev && !risk.relatedSignal(cve,'kev')) props.push({ name: "fad:kev", value: "true" });
|
|
175
201
|
if (euvdExploited(cve)) props.push({ name: "fad:euvdExploited", value: cve.euvd.exploitedSince || "true" });
|
|
176
202
|
if (cve.priority?.band) props.push({ name: "fad:priorityBand", value: cve.priority.band });
|
|
177
203
|
if (cve.priority?.score != null) props.push({ name: "fad:priorityScore", value: String(cve.priority.score) });
|