vigievuln 1.2.1 → 1.3.1
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 +7 -1044
- package/README.md +37 -64
- package/lib/airgap-project.js +35 -7
- package/lib/applicability-evidence.js +12 -0
- package/lib/artifacts/applications.js +58 -0
- package/lib/artifacts/component-scope.js +31 -0
- package/lib/artifacts/cve-view.js +108 -0
- package/lib/artifacts/enrichment.js +87 -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/inventory-scope.js +50 -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 +199 -0
- package/lib/artifacts/risk-report.js +120 -0
- package/lib/artifacts/sbom.js +68 -0
- package/lib/artifacts/scan.js +411 -0
- package/lib/cache-archive-sqlite.js +41 -25
- package/lib/charts.js +143 -34
- 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/scan.js +14 -13
- package/lib/codecs/binary/sniff.js +16 -15
- package/lib/codecs/binary.codec.js +22 -2
- 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/csaf-export.js +13 -6
- 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-record-coverage.js +109 -0
- package/lib/cve-report.js +348 -181
- package/lib/deps-descriptor.js +25 -3
- package/lib/diagnostics.js +25 -0
- package/lib/diff.js +0 -0
- package/lib/epss.js +6 -6
- package/lib/euvd.js +40 -6
- package/lib/finding-enrichment.js +166 -0
- package/lib/finding-summary.js +5 -4
- package/lib/i18n.js +48 -10
- 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 +53 -9
- 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 +79 -32
- 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 +23 -19
- 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 +82 -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 +32 -12
- package/lib/source-health.js +57 -16
- package/lib/source-image-scan.js +57 -0
- package/lib/source-profile.js +6 -3
- package/lib/system-inventory/advisories.js +170 -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/package.json +12 -3
- package/vigievuln.js +225 -102
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const crypto = require('node:crypto');
|
|
6
|
+
const { makeDepRecord } = require('../dep-record');
|
|
7
|
+
const {IMAGE_COMPONENT_SCOPE,imageComponentRole} = require('./component-scope');
|
|
8
|
+
const { openArtifact } = require('./index');
|
|
9
|
+
const { collectInstalledApplications } = require('./applications');
|
|
10
|
+
const { collectSystemInventory, assessSystemInventory, syncSystemAdvisories } = require('../system-inventory');
|
|
11
|
+
|
|
12
|
+
const SNAPSHOT_SCHEMA = 'vigievuln-artifact-inventory/1';
|
|
13
|
+
const sha = value => crypto.createHash('sha256').update(value).digest('hex');
|
|
14
|
+
function normalizeWarnings(values = [], capability = 'inventory') {
|
|
15
|
+
return values.map(value => typeof value === 'string'
|
|
16
|
+
? { type: capability === 'inventory' ? 'dependency-coverage' : 'source-unavailable', capability, message: value }
|
|
17
|
+
: { capability, ...value });
|
|
18
|
+
}
|
|
19
|
+
function coverageRecords(values = [], targetId, capability) {
|
|
20
|
+
return values.map((value, index) => {
|
|
21
|
+
const execution = value.execution || ({ complete: 'completed', completed: 'completed', unsupported: 'partial',
|
|
22
|
+
incomplete: 'partial', unknown: 'partial', missing: 'not-run', failed: 'failed', absent: 'not-applicable' })[value.status] || 'partial';
|
|
23
|
+
return { ...value, artifactTargetId: targetId, capability: value.capability || capability,
|
|
24
|
+
collector: value.collector || value.source || `${capability}-${index}`, execution,
|
|
25
|
+
result: value.result || (execution === 'not-applicable' ? 'not-applicable' : 'indeterminate') };
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
function portable(value, root, replacement = '') {
|
|
29
|
+
if (typeof value === 'string') return value.split(root + path.sep).join(replacement).split(root.replace(/\\/g, '/') + '/').join(replacement);
|
|
30
|
+
if (Array.isArray(value)) return value.map(v => portable(v, root, replacement));
|
|
31
|
+
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, portable(v, root, replacement)]));
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
function qualify(dep, targetId) {
|
|
35
|
+
const out = { ...dep, artifactTargetId: targetId };
|
|
36
|
+
out.artifactPath = dep.manifestPaths?.[0] || dep.manifestPath || dep.installEvidence?.path || null;
|
|
37
|
+
out.coordKey = `artifact:${targetId}:${dep.coordKey || [dep.manager, dep.name, dep.version, out.artifactPath].join(':')}`;
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
const PACKAGE_TYPES = { dpkg: 'deb', deb: 'deb', apk: 'apk', rpm: 'rpm' };
|
|
41
|
+
function systemDep(pkg, targetId, distribution) {
|
|
42
|
+
const dep = makeDepRecord({ ecosystem: 'system', namespace: distribution?.id || '', name: pkg.name,
|
|
43
|
+
version: pkg.version, manifestPath: pkg.manifestPath, provenance: pkg.provenance || 'installed', scope: 'runtime' });
|
|
44
|
+
dep.coordKey = [pkg.manager || '', pkg.name || '', pkg.version || '', pkg.architecture || '', pkg.manifestPath || ''].map(value => encodeURIComponent(String(value))).join(':');
|
|
45
|
+
return qualify({ ...dep, manager: pkg.manager, packageType: pkg.packageType || PACKAGE_TYPES[pkg.manager] || null,
|
|
46
|
+
architecture: pkg.architecture, sourceName: pkg.sourceName, sourceVersion: pkg.sourceVersion,
|
|
47
|
+
distribution, systemEvidence: pkg.evidence || null, packageMetadata:pkg.packageMetadata || null, packageOrigin:pkg.packageOrigin || null }, targetId);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function inventoryTarget(target, options = {}) {
|
|
51
|
+
const system = await collectSystemInventory(target.root, options);
|
|
52
|
+
const applications = await collectInstalledApplications(target.root, options);
|
|
53
|
+
const binaries = await require('../codecs/binary.codec').collect(target.root, { ...options, defaultExcludes: false, srcRoot: target.root });
|
|
54
|
+
const order = (a, b) => JSON.stringify([a.ecosystem, a.manager, a.namespace, a.name, a.version, a.architecture, a.manifestPath, a.manifestPaths]).localeCompare(JSON.stringify([b.ecosystem, b.manager, b.namespace, b.name, b.version, b.architecture, b.manifestPath, b.manifestPaths]));
|
|
55
|
+
const packages = portable(system.packages, target.root).map(p => ({ ...p, ...(p.ownedPaths ? { ownedPaths: [...p.ownedPaths].sort() } : {}) })).sort(order);
|
|
56
|
+
const appDeps = portable([...applications.deps.values(), ...binaries.deps.values()], target.root).sort(order);
|
|
57
|
+
const id = target.kind === 'rootfs' && target.metadata.format === 'directory'
|
|
58
|
+
? `rootfs-inventory:sha256:${sha(JSON.stringify({ distribution: system.distribution, packages, deps: appDeps }))}` : target.id;
|
|
59
|
+
const owners = new Map();
|
|
60
|
+
const pathKey = value => path.posix.normalize('/' + String(value || '').replace(/\\/g, '/').replace(/^\/+/, ''));
|
|
61
|
+
for (const pkg of packages) for (const ownedPath of pkg.ownedPaths || []) {
|
|
62
|
+
const keys = new Set([pathKey(ownedPath)]);
|
|
63
|
+
// Resolve directory aliases such as merged-/usr, never follow the file's own
|
|
64
|
+
// symlink: ownership of a link does not confer ownership of its destination.
|
|
65
|
+
try {
|
|
66
|
+
const root = fs.realpathSync(target.root), parent = fs.realpathSync(path.dirname(path.join(root, ownedPath.replace(/^\/+/, ''))));
|
|
67
|
+
if (parent === root || parent.startsWith(root + path.sep)) keys.add(pathKey(path.relative(root, path.join(parent, path.basename(ownedPath)))));
|
|
68
|
+
} catch { /* Removed/unavailable owned paths do not create invented evidence. */ }
|
|
69
|
+
for (const key of keys) {
|
|
70
|
+
const list = owners.get(key) || [];
|
|
71
|
+
list.push({ name: pkg.name, version: pkg.version, manager: pkg.manager, evidencePath: pkg.manifestPath });
|
|
72
|
+
owners.set(key, list);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const deps = [...packages.map(p => systemDep(p, id, system.distribution)), ...appDeps.map(d => {
|
|
76
|
+
const evidence = d.binaryEvidence?.binaryPath || d.installEvidence?.path || d.manifestPaths?.[0];
|
|
77
|
+
// A shared aggregate manifest does not prove that every package it names is OS-owned.
|
|
78
|
+
const aggregate = ['composer', 'composer-php', 'nuget'].includes(d.installEvidence?.source);
|
|
79
|
+
const owned = evidence && !aggregate ? owners.get(pathKey(evidence)) : null;
|
|
80
|
+
return qualify(owned?.length ? { ...d, osPackageOwners: owned } : d, id);
|
|
81
|
+
})];
|
|
82
|
+
for(const dep of deps){dep.imageRole=imageComponentRole(dep);dep.scope=dep.imageRole==='transitive'?'transitive':'runtime';}
|
|
83
|
+
const warnings = portable(normalizeWarnings([...(system.warnings || []), ...applications.warnings, ...binaries.warnings,
|
|
84
|
+
...(target.metadata.warnings || [])]), target.root);
|
|
85
|
+
const coverage = coverageRecords(system.coverage, id, 'inventory');
|
|
86
|
+
coverage.push({ artifactTargetId: id, capability: 'inventory', collector: 'installed-applications',
|
|
87
|
+
execution: applications.warnings.length ? 'partial' : 'completed', result: 'indeterminate', count: applications.deps.size });
|
|
88
|
+
coverage.push({ artifactTargetId: id, capability: 'inventory', collector: 'native-binaries',
|
|
89
|
+
execution: binaries.warnings.length ? 'partial' : 'completed', result: 'indeterminate', count: [...binaries.deps.values()].filter(d => d.ecosystem === 'binary').length });
|
|
90
|
+
if (target.metadata.warnings?.length) coverage.push({ artifactTargetId: id, capability: 'inventory', collector: 'artifact-reader', execution: 'partial', result: 'indeterminate' });
|
|
91
|
+
const source = options.source || path.basename(target.metadata.source || target.root);
|
|
92
|
+
const acquisition = options.registry ? { kind: 'registry', reference: source } : {
|
|
93
|
+
kind: target.metadata.format === 'directory' ? 'rootfs-directory' : target.metadata.format === 'oci-layout' && target.metadata.source && fs.statSync(target.metadata.source).isDirectory() ? 'oci-layout' : 'archive', source,
|
|
94
|
+
};
|
|
95
|
+
return { id, kind: target.kind, metadata: { ...target.metadata, componentScope:IMAGE_COMPONENT_SCOPE, source, acquisition, definitions: [], definitionDiscovery: {status:'not-supplied'} },
|
|
96
|
+
evidence: 'content-inventory', inventoryAt: new Date().toISOString(), distribution: system.distribution,
|
|
97
|
+
packages, deps, coverage, warnings, componentCount: deps.length };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function sbomTarget(input, options = {}) {
|
|
101
|
+
const parsed = require('./sbom').readSbom(input, options);
|
|
102
|
+
const id = 'sbom-inventory:sha256:' + sha(JSON.stringify(typeof input === 'string' ? JSON.parse(fs.readFileSync(input, 'utf8')) : input));
|
|
103
|
+
// A root component's name is not an os-release identity.
|
|
104
|
+
const mismatch = options.distribution && parsed.distribution && (options.distribution.id !== parsed.distribution.id || options.distribution.versionId !== parsed.distribution.versionId);
|
|
105
|
+
if (mismatch) parsed.warnings.push({ type: 'dependency-coverage', reason: 'sbom-distribution-conflict', message: 'Requested distribution conflicts with publisher SBOM distribution evidence.' });
|
|
106
|
+
const distribution = parsed.warnings.some(w => w.reason === 'sbom-distribution-conflict') ? null : (options.distribution || parsed.distribution || null);
|
|
107
|
+
const packages = parsed.systemPackages;
|
|
108
|
+
const deps = [...packages.map(p => systemDep(p, id, distribution)), ...[...parsed.deps.values()].map(d => qualify(d, id))];
|
|
109
|
+
return { id, kind: 'sbom', metadata: { ...parsed.metadata, source: typeof input === 'string' ? path.basename(input) : options.source,
|
|
110
|
+
digest: options.expectedDigest || parsed.metadata.subjectDigests?.[0] || null, platform: options.platform || parsed.metadata.platform,
|
|
111
|
+
acquisition: options.registry ? { kind: 'registry', reference: options.registryReference || options.source } : { kind: 'sbom', source: typeof input === 'string' ? path.basename(input) : options.source || null }, definitions: [], definitionDiscovery: {status:'not-supplied'} },
|
|
112
|
+
evidence: 'sbom', inventoryAt: new Date().toISOString(), distribution, packages, deps,
|
|
113
|
+
warnings: parsed.warnings, coverage: [{ artifactTargetId: id, capability: 'inventory', collector: 'sbom',
|
|
114
|
+
execution: 'partial', result: 'indeterminate', reason: 'Publisher inventory; component completeness and signature not verified.' }], componentCount: deps.length };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function createSnapshot(targets) {
|
|
118
|
+
const content = { schema: SNAPSHOT_SCHEMA, generatedAt: new Date().toISOString(), targets };
|
|
119
|
+
return { ...content, integrity: { algorithm: 'sha256', digest: sha(JSON.stringify(content)) } };
|
|
120
|
+
}
|
|
121
|
+
function validateSnapshot(doc) {
|
|
122
|
+
if (!doc || typeof doc !== 'object' || Array.isArray(doc)) throw Error('invalid artifact inventory schema or integrity');
|
|
123
|
+
const { integrity, ...content } = doc;
|
|
124
|
+
if (content.schema !== SNAPSHOT_SCHEMA || !Array.isArray(content.targets) || !content.targets.length || integrity?.algorithm !== 'sha256' || integrity.digest !== sha(JSON.stringify(content))) throw Error('invalid artifact inventory schema or integrity');
|
|
125
|
+
const targetIds = new Set(), componentIds = new Set();
|
|
126
|
+
for (const target of content.targets) {
|
|
127
|
+
if (!target || typeof target.id !== 'string' || !target.id || targetIds.has(target.id) || !target.metadata || !Array.isArray(target.deps) || !Array.isArray(target.packages) || !Array.isArray(target.coverage) || !Array.isArray(target.warnings)) throw Error('invalid or duplicate artifact inventory target');
|
|
128
|
+
targetIds.add(target.id);
|
|
129
|
+
for (const dep of target.deps) {
|
|
130
|
+
if (typeof dep?.coordKey !== 'string' || !dep.coordKey || componentIds.has(dep.coordKey) || dep.artifactTargetId !== target.id || typeof dep.ecosystem !== 'string' || typeof dep.name !== 'string') throw Error('invalid or duplicate artifact inventory component');
|
|
131
|
+
componentIds.add(dep.coordKey);
|
|
132
|
+
}
|
|
133
|
+
for (const record of target.coverage) if (record.artifactTargetId && record.artifactTargetId !== target.id) throw Error('artifact inventory coverage target mismatch');
|
|
134
|
+
}
|
|
135
|
+
return content.targets;
|
|
136
|
+
}
|
|
137
|
+
function readSnapshot(file, options = {}) {
|
|
138
|
+
if (fs.statSync(file).size > (options.maxSnapshotBytes ?? 128 * 1024 * 1024)) throw Error('artifact inventory exceeds configured size limit');
|
|
139
|
+
return validateSnapshot(JSON.parse(fs.readFileSync(file, 'utf8'))).map(t => ({ ...require('./inventory-scope').applyComponentScope(t), evidence: 'cached-inventory', originalEvidence: t.originalEvidence || t.evidence }));
|
|
140
|
+
}
|
|
141
|
+
async function writeSnapshot(file, targets) {
|
|
142
|
+
const absolute = path.resolve(file);
|
|
143
|
+
await fs.promises.mkdir(path.dirname(absolute), { recursive: true });
|
|
144
|
+
const temp = absolute + '.' + crypto.randomUUID() + '.tmp';
|
|
145
|
+
try { await fs.promises.writeFile(temp, JSON.stringify(createSnapshot(targets), null, 2) + '\n', { mode: 0o600 }); await fs.promises.rename(temp, absolute); }
|
|
146
|
+
finally { await fs.promises.rm(temp, { force: true }); }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function acquireInventories(input, options = {}) {
|
|
150
|
+
if (options.inventory) return readSnapshot(input, options);
|
|
151
|
+
if (options.sbom) return [sbomTarget(input, options)];
|
|
152
|
+
const cache = options.registry ? require('../cache-repository').createCacheRepository(options.cacheDir) : null;
|
|
153
|
+
const legacyCacheKey = sha(JSON.stringify([input, options.platform || null, !!options.preferSbom]));
|
|
154
|
+
const ref = options.registry ? require('../image-registry').parseReference(input) : null;
|
|
155
|
+
const cacheKey = ref ? sha(JSON.stringify([`${ref.registry}/${ref.repository}@${ref.reference}`, options.platform || null, !!options.preferSbom])) : legacyCacheKey;
|
|
156
|
+
if (options.registry && options.offline) {
|
|
157
|
+
const saved = cache.get('image-inventory', cacheKey) || cache.get('image-inventory', legacyCacheKey);
|
|
158
|
+
if (!saved?.value || saved.value.schema !== SNAPSHOT_SCHEMA) throw Error('image inventory is not cached; import an inventory/archive or prepare this reference online');
|
|
159
|
+
const targets = validateSnapshot(saved.value).map(require('./inventory-scope').applyComponentScope);
|
|
160
|
+
return targets.map(target => ({ ...target, evidence: 'cached-inventory', originalEvidence: target.originalEvidence || target.evidence,
|
|
161
|
+
warnings: [...target.warnings, { type: 'cached-image-resolution', severity:'info', capability: 'sources', message: 'Using the prepared image digest and inventory offline; the registry tag is not re-resolved in this mode.' }] }));
|
|
162
|
+
}
|
|
163
|
+
const persist = targets => {
|
|
164
|
+
targets = targets.map(require('./inventory-scope').applyComponentScope);
|
|
165
|
+
validateSnapshot(createSnapshot(targets));
|
|
166
|
+
if (cache) cache.put('image-inventory', cacheKey, createSnapshot(targets));
|
|
167
|
+
return targets;
|
|
168
|
+
};
|
|
169
|
+
if (cache && !options.forceUpdate && !require('../cache-policy').shouldForceUpdate()) {
|
|
170
|
+
let targets;
|
|
171
|
+
try {
|
|
172
|
+
const saved = cache.get('image-inventory', cacheKey) || cache.get('image-inventory', legacyCacheKey);
|
|
173
|
+
if (saved?.value) targets = validateSnapshot(saved.value);
|
|
174
|
+
} catch { /* Invalid snapshots must be rebuilt from verified content online. */ }
|
|
175
|
+
const digest = targets?.[0]?.metadata?.acquisition?.indexDigest;
|
|
176
|
+
// Publisher SBOMs can be updated independently of the image digest.
|
|
177
|
+
const scoped = targets?.map(require('./inventory-scope').applyComponentScope);
|
|
178
|
+
if (digest && scoped.every(t => t.evidence === 'content-inventory' && t.metadata?.componentScope === require('./component-scope').IMAGE_COMPONENT_SCOPE && !t.warnings.some(w => w.reason === require('./inventory-scope').SCOPE_REASON) && t.metadata?.acquisition?.indexDigest === digest)) {
|
|
179
|
+
const current = ref.reference.includes(':') ? ref.reference : await require('../image-registry').fetchRegistryDigest(input,
|
|
180
|
+
{...options, fetcher:options.registryFetcher || options.fetcher, limits:options.registryLimits});
|
|
181
|
+
if (current === digest) return scoped.map(target => ({...target, evidence:'cached-inventory', originalEvidence:target.originalEvidence || target.evidence}));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
let registry = null, opened = null, sbomAttempt = null;
|
|
185
|
+
try {
|
|
186
|
+
if (options.registry) {
|
|
187
|
+
if (options.preferSbom) {
|
|
188
|
+
try {
|
|
189
|
+
const discovered = await require('../image-registry').fetchRegistrySboms(input, { ...options, fetcher: options.registryFetcher || options.fetcher, limits: options.registryLimits });
|
|
190
|
+
// Never drop image platforms when only a subset has publisher metadata.
|
|
191
|
+
const subjects = new Set(discovered.documents.map(d => d.expectedDigest));
|
|
192
|
+
if (discovered.documents.length && subjects.size >= (discovered.metadata.platforms?.length || 1)) {
|
|
193
|
+
const targets = discovered.documents.map(item => sbomTarget(item.document, { ...options, expectedDigest: item.expectedDigest,
|
|
194
|
+
...(item.source?.binding?.kind === 'oci-subject' ? { boundSubjectDigest: item.expectedDigest,
|
|
195
|
+
boundSubjectEvidence: { type: 'oci-manifest-subject', manifestDigest: item.source.manifestDigest } } : {}),
|
|
196
|
+
platform: item.platform, registryReference: input, source: `${input}@${item.expectedDigest}` }));
|
|
197
|
+
// Prefer metadata only when every component can actually be assessed.
|
|
198
|
+
// Signature verification remains explicitly outside this evidence.
|
|
199
|
+
const unusable = targets.some(t => t.warnings.some(w => w.reason !== 'sbom-unverified'));
|
|
200
|
+
if (!unusable) {
|
|
201
|
+
for (const target of targets) { target.metadata.registryEvidence = discovered.metadata; target.metadata.acquisition.resolvedDigest = target.metadata.digest; target.metadata.acquisition.indexDigest = discovered.metadata.digest; }
|
|
202
|
+
return persist(targets);
|
|
203
|
+
}
|
|
204
|
+
sbomAttempt = { status: 'fallback', reason: 'Publisher inventory lacks component identity, distribution, or source-package evidence.' };
|
|
205
|
+
} else sbomAttempt = { status: 'fallback', reason: 'Publisher inventory is not available for every selected image platform.' };
|
|
206
|
+
} catch (error) {
|
|
207
|
+
sbomAttempt = { status: 'fallback', reason: 'Publisher inventory could not be validated; full image content was requested.' };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
registry = await require('../image-registry').fetchRegistryImage(input, { ...options, fetcher: options.registryFetcher || options.fetcher, limits: options.registryLimits });
|
|
211
|
+
}
|
|
212
|
+
opened = await openArtifact(registry?.path || input, { ...options, limits: options.artifactLimits });
|
|
213
|
+
const targets = [];
|
|
214
|
+
for (const target of opened.targets) {
|
|
215
|
+
if (options.platform) {
|
|
216
|
+
const platform = target.metadata.platform;
|
|
217
|
+
if (!platform || [platform.os, platform.architecture, platform.variant].filter(Boolean).join('/') !== options.platform && [platform.os, platform.architecture].join('/') !== options.platform) continue;
|
|
218
|
+
}
|
|
219
|
+
const inventory = await inventoryTarget(target, { ...options, source: registry ? input : undefined });
|
|
220
|
+
if (registry) { inventory.metadata.registryEvidence = registry.metadata; inventory.metadata.acquisition.resolvedDigest = inventory.metadata.digest || null; inventory.metadata.acquisition.indexDigest = registry.metadata.digest; }
|
|
221
|
+
if (sbomAttempt) inventory.metadata.publisherInventory = sbomAttempt;
|
|
222
|
+
targets.push(inventory);
|
|
223
|
+
}
|
|
224
|
+
if (!targets.length) throw Error('no artifact matches the requested platform');
|
|
225
|
+
return persist(targets);
|
|
226
|
+
} finally { if (opened) await opened.cleanup(); if (registry) await registry.cleanup(); }
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function assessInventories(targets, options = {}) {
|
|
230
|
+
options.onArtifactProgress?.({stage:'Component identities'});
|
|
231
|
+
targets=targets.map(target=>require('./inventory-scope').applyComponentScope(target,{checkPolicy:false}));
|
|
232
|
+
for(const target of targets){
|
|
233
|
+
for(const pkg of target.packages){const origin=require('../system-inventory/distribution-sources').identifyPackageOrigin(pkg,options);if(origin)pkg.packageOrigin=origin;}
|
|
234
|
+
for(const dep of target.deps){const origin=require('../system-inventory/distribution-sources').identifyPackageOrigin(dep,options);if(origin)dep.packageOrigin=origin;}
|
|
235
|
+
const identity=await require('./go-main-identity').resolveGoMainIdentities(target,options);
|
|
236
|
+
for(const dep of identity.deps){const qualified=qualify({...dep,imageRole:'direct',scope:'runtime'},target.id);if(!target.deps.some(d=>d.coordKey===qualified.coordKey))target.deps.push(qualified);}
|
|
237
|
+
target.coverage.push({...identity.coverage,artifactTargetId:target.id,capability:'inventory'});
|
|
238
|
+
target.warnings.push(...identity.warnings);
|
|
239
|
+
}
|
|
240
|
+
const resolvedDeps = new Map(), cveMatches = [], warnings = [], artifacts = [], warmed = new Set();
|
|
241
|
+
const nativeDeps=new Map();
|
|
242
|
+
for(const target of targets)for(const dep of target.deps||[])if(dep.ecosystem!=='binary' && (!dep.osPackageOwners?.length || dep.binaryEvidence))nativeDeps.set(dep.coordKey,dep);
|
|
243
|
+
let native={matches:[],unknown:[],coverage:{status:'not-applicable'}},nativePreparation={sources:[],coverage:[],warnings:[]};
|
|
244
|
+
if(nativeDeps.size){
|
|
245
|
+
const nativeOptions={...options};
|
|
246
|
+
try{
|
|
247
|
+
options.onArtifactProgress?.({stage:'Native advisory preparation'});
|
|
248
|
+
nativePreparation=await require('../native-source-prepare').prepareNativeSources(nativeDeps,nativeOptions);
|
|
249
|
+
if(nativePreparation.sources.length){
|
|
250
|
+
const store=require('../advisory-store').openAdvisoryStore({cacheDir:options.cacheDir});
|
|
251
|
+
options.onArtifactProgress?.({stage:'Native advisory matching'});
|
|
252
|
+
try{native=require('../native-advisories').matchNativePackages(nativeDeps,store,{sources:nativePreparation.sources});}finally{store.close();}
|
|
253
|
+
}
|
|
254
|
+
}catch(error){nativePreparation.warnings.push(`Native advisory scan failed: ${error.message}`);native.coverage={status:'incomplete',reason:error.message};}
|
|
255
|
+
}
|
|
256
|
+
for (const original of targets) {
|
|
257
|
+
const target = JSON.parse(JSON.stringify(original));
|
|
258
|
+
let targetWarnings = normalizeWarnings(target.warnings);
|
|
259
|
+
const assessedPackages = new Set();
|
|
260
|
+
const coverage = [...target.coverage];
|
|
261
|
+
options.onArtifactProgress?.({stage:'Distribution advisories'});
|
|
262
|
+
const distroKey = JSON.stringify(target.distribution);
|
|
263
|
+
if (options.osv !== false && !options.offline && target.packages.length && !warmed.has(distroKey) && !require('../providers').hasHostedProxy()) {
|
|
264
|
+
warmed.add(distroKey);
|
|
265
|
+
try {
|
|
266
|
+
const scope=require('../system-inventory').scope(target.distribution,options);
|
|
267
|
+
const cached=scope && require('../cache-repository').createCacheRepository(options.cacheDir).getSnapshot('system-osv:'+scope.ecosystem);
|
|
268
|
+
const age=Date.now()-(cached?.fetchedAt||0);
|
|
269
|
+
if(options.refresh || !cached?.complete || cached.stale || age<0 || age>=require('../cache-policy').DEFAULT_TTL_MS)
|
|
270
|
+
await syncSystemAdvisories(target.distribution, options);
|
|
271
|
+
}
|
|
272
|
+
catch (error) { targetWarnings.push({ type: 'source-unavailable', capability: 'sources', message: `System advisory refresh failed: ${error.message}` }); }
|
|
273
|
+
}
|
|
274
|
+
for (const dep of target.deps) resolvedDeps.set(dep.coordKey, dep);
|
|
275
|
+
for(const source of nativePreparation.coverage){
|
|
276
|
+
coverage.push(...coverageRecords([{...source,collector:`native-${source.source}`}],target.id,'sources'));
|
|
277
|
+
if(source.issue && source.issue!=='refresh-failed')targetWarnings.push({type:'source-unavailable',severity:source.issue==='missing-source'?'info':undefined,capability:'sources',source:source.source,message:`${source.source}: ${source.reason}.`});
|
|
278
|
+
}
|
|
279
|
+
for(const warning of nativePreparation.warnings)targetWarnings.push(typeof warning==='string'?{type:'source-unavailable',capability:'sources',message:warning}:{capability:'sources',...warning});
|
|
280
|
+
const nativeUnknown=native.unknown.filter(item=>!item.artifactTargetId||item.artifactTargetId===target.id);
|
|
281
|
+
if(nativeUnknown.length){coverage.push({artifactTargetId:target.id,capability:'sources',collector:'native-comparisons',execution:'completed',result:'indeterminate',affectsCompleteness:false,affectsAssessment:true,count:nativeUnknown.length});targetWarnings.push({...require('../diagnostics').advisoryEvidenceDiagnostic(nativeUnknown),capability:'sources'});}
|
|
282
|
+
if (target.packages.length && options.osv === false) {
|
|
283
|
+
coverage.push({ artifactTargetId: target.id, capability: 'advisories', collector: 'system-osv', execution: 'not-applicable', result: 'not-consulted', expected:false, reason: 'OSV is excluded by source configuration.' });
|
|
284
|
+
} else if (target.packages.length) {
|
|
285
|
+
const systemInventory = { distribution: target.distribution, packages: target.packages.filter(p=>!['third-party','ambiguous'].includes(p.packageOrigin?.status)) };
|
|
286
|
+
const excluded=target.packages.length-systemInventory.packages.length;
|
|
287
|
+
if(excluded){const reason='Distribution OSV ranges do not establish applicability for packages declaring another vendor.';coverage.push({artifactTargetId:target.id,capability:'advisories',collector:'system-osv-vendor-scope',execution:'partial',result:'indeterminate',count:excluded,reason});targetWarnings.push({type:'dependency-coverage',severity:'info',capability:'advisories',message:reason});}
|
|
288
|
+
const hostedOnline = !options.offline && require('../providers').hasHostedProxy();
|
|
289
|
+
let assessment;
|
|
290
|
+
try {
|
|
291
|
+
assessment = hostedOnline ? await require('../system-inventory').assessTargetedSystemInventory(systemInventory, options)
|
|
292
|
+
: await assessSystemInventory(systemInventory, options);
|
|
293
|
+
if (options.offline && assessment.coverage.some(c => c.status === 'missing')) {
|
|
294
|
+
const targeted = await require('../system-inventory').assessTargetedSystemInventory(systemInventory, options);
|
|
295
|
+
if (targeted.coverage.some(c => c.consulted > c.unknown)) assessment = targeted;
|
|
296
|
+
}
|
|
297
|
+
} catch(error) {
|
|
298
|
+
assessment={matches:[],coverage:[{source:'system-osv',status:'incomplete',reason:error.message}],warnings:[`System OSV assessment failed: ${error.message}`]};
|
|
299
|
+
}
|
|
300
|
+
if (assessment.coverage.length && assessment.coverage.every(c=>c.status==='complete')) for(const pkg of systemInventory.packages) assessedPackages.add(`${pkg.manager}:${pkg.name}@${pkg.version}`);
|
|
301
|
+
coverage.push(...coverageRecords(assessment.coverage, target.id, 'advisories'));
|
|
302
|
+
targetWarnings.push(...normalizeWarnings(assessment.warnings, 'advisories'));
|
|
303
|
+
for (const match of assessment.matches) {
|
|
304
|
+
const dep = systemDep(match.dep, target.id, target.distribution);
|
|
305
|
+
const full = resolvedDeps.get(dep.coordKey) || dep;
|
|
306
|
+
const cve = { ...match.cve, score: match.cve.score ?? match.cve.cvss ?? null,
|
|
307
|
+
fixVersion: match.cve.fixVersion || match.fixVersion || null,
|
|
308
|
+
osvRefs: match.cve.osvRefs || match.cve.references || [] };
|
|
309
|
+
cveMatches.push({ ...match, dep: full, cve });
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
options.onArtifactProgress?.({stage:'Distribution security trackers'});
|
|
313
|
+
const distribution=await require('../system-inventory/distribution-sources').assessDistributionSources({distribution:target.distribution,packages:target.packages},{...options,confirmedMatches:[...cveMatches,...native.matches].filter(m=>m.dep?.artifactTargetId===target.id)});
|
|
314
|
+
coverage.push(...coverageRecords(distribution.coverage,target.id,'advisories'));
|
|
315
|
+
targetWarnings.push(...normalizeWarnings(distribution.warnings,'advisories'));
|
|
316
|
+
for(const match of distribution.matches){const dep=systemDep(match.dep,target.id,target.distribution);cveMatches.push({...match,dep:resolvedDeps.get(dep.coordKey)||dep});}
|
|
317
|
+
options.onArtifactProgress?.({stage:'Application advisories'});
|
|
318
|
+
const appDeps = new Map(target.deps.filter(d => d.ecosystem !== 'system' && d.ecosystem !== 'binary' && (!d.osPackageOwners?.length || !!d.binaryEvidence)).map(d => [d.coordKey, d]));
|
|
319
|
+
if (appDeps.size && options.osv === false) {
|
|
320
|
+
coverage.push({ artifactTargetId: target.id, capability:'advisories',collector:'osv-application',execution:'not-applicable',result:'not-consulted',expected:false,reason:'OSV is excluded by source configuration.' });
|
|
321
|
+
} else if (appDeps.size) {
|
|
322
|
+
const appWarnings = [];
|
|
323
|
+
try {
|
|
324
|
+
const matches = await require('../osv').queryOsvForDeps(appDeps, { ...options, allowStaleFallback: true,
|
|
325
|
+
onWarning: warning => appWarnings.push(typeof warning === 'string' ? { type: 'osv-coverage', message: warning } : warning) });
|
|
326
|
+
cveMatches.push(...matches);
|
|
327
|
+
const incomplete=appWarnings.some(w=>!require('../diagnostics').isInformational(w));
|
|
328
|
+
coverage.push({ artifactTargetId: target.id, capability: 'advisories', collector: 'osv-application',
|
|
329
|
+
execution: incomplete ? 'partial' : 'completed', result: matches.length ? 'affected' : incomplete ? 'indeterminate' : 'no-match', count: appDeps.size });
|
|
330
|
+
} catch (error) {
|
|
331
|
+
appWarnings.push({ type: 'source-unavailable', message: `Application advisory scan failed: ${error.message}` });
|
|
332
|
+
coverage.push({ artifactTargetId: target.id, capability: 'advisories', collector: 'osv-application', execution: 'failed', result: 'indeterminate' });
|
|
333
|
+
}
|
|
334
|
+
targetWarnings.push(...normalizeWarnings(appWarnings, 'advisories'));
|
|
335
|
+
}
|
|
336
|
+
options.onArtifactProgress?.({stage:'Publisher advisories'});
|
|
337
|
+
const publisher=await require('./publisher-advisories').assessPublisherAdvisories(appDeps,options);
|
|
338
|
+
cveMatches.push(...publisher.matches);
|
|
339
|
+
coverage.push(...coverageRecords(publisher.coverage,target.id,'advisories'));
|
|
340
|
+
targetWarnings.push(...normalizeWarnings(publisher.warnings,'advisories'));
|
|
341
|
+
const identifiedBinaryPaths=new Set(target.deps.filter(d=>d.binaryEvidence?.source==='go-vcs-and-module-proxy').map(d=>d.binaryEvidence.binaryPath));
|
|
342
|
+
const unknownBinaries = target.deps.filter(d => d.ecosystem === 'binary' && !d.osPackageOwners?.length && !identifiedBinaryPaths.has(d.artifactPath));
|
|
343
|
+
if (unknownBinaries.length) {
|
|
344
|
+
coverage.push({ artifactTargetId: target.id, capability: 'advisories', collector: 'native-binaries', execution: 'partial', result: 'indeterminate', count: unknownBinaries.length, reason: 'Native binary identities cannot all be established from embedded metadata.' });
|
|
345
|
+
targetWarnings.push({ type: 'dependency-coverage', severity:'info', capability: 'advisories', message: `${unknownBinaries.length} native binaries have no authenticated package/version identity.` });
|
|
346
|
+
}
|
|
347
|
+
const archiveContext=require('./applications').classifyOwnedArchiveWarnings(targetWarnings,target.packages,assessedPackages);
|
|
348
|
+
if(archiveContext.informational.length){
|
|
349
|
+
targetWarnings=archiveContext.warnings;
|
|
350
|
+
// Reclassify the collector only when none of its original inventory
|
|
351
|
+
// diagnostics remain; never hide malformed archives or unresolved files.
|
|
352
|
+
if(!targetWarnings.some(w=>w.capability==='inventory' && !require('../diagnostics').isInformational(w)))
|
|
353
|
+
for(const check of coverage)if(check.collector==='installed-applications' && check.execution==='partial')check.execution='completed';
|
|
354
|
+
targetWarnings.push(...archiveContext.informational.map(({warning,owner,path})=>({...warning,severity:'info',type:'os-owned-component',owner,
|
|
355
|
+
message:`${path} is covered by its installed OS package ${owner.name}@${owner.version}; no independent Maven identity is declared.`})));
|
|
356
|
+
}
|
|
357
|
+
for (const check of coverage) {
|
|
358
|
+
if (check.affectsCompleteness === false || ['completed', 'not-applicable'].includes(check.execution)) continue;
|
|
359
|
+
if (check.collector==='native-binaries' || check.collector==='native-comparisons' || check.collector==='go-main-identity' || check.collector==='system-osv-vendor-scope' || check.issue==='missing-source') continue;
|
|
360
|
+
if (targetWarnings.some(w => w.capability === check.capability && !require('../diagnostics').isInformational(w))) continue;
|
|
361
|
+
targetWarnings.push({ type: check.capability === 'inventory' ? 'dependency-coverage' : 'source-unavailable',
|
|
362
|
+
capability: check.capability, message: `${check.collector || check.source || check.capability}: ${check.reason || check.execution}; coverage is incomplete.` });
|
|
363
|
+
}
|
|
364
|
+
warnings.push(...targetWarnings.map(w => ({ artifactTargetId: target.id, ...w })));
|
|
365
|
+
artifacts.push({ id: target.id, kind: target.kind, metadata: target.metadata, evidence: target.evidence,
|
|
366
|
+
originalEvidence: target.originalEvidence, distribution: target.distribution, inventoryAt: target.inventoryAt,
|
|
367
|
+
componentCount: target.deps.length, coverage, advisoryObservations:distribution.observations, components: target.deps.map(d => ({ ecosystem: d.ecosystem, packageType: d.packageType,
|
|
368
|
+
namespace: d.namespace, name: d.name, version: d.version, sourceName:d.sourceName || null, sourceVersion:d.sourceVersion || null, packageOrigin:d.packageOrigin || null, architecture: d.architecture, artifactPath: d.artifactPath,
|
|
369
|
+
provenance: d.provenance, imageRole:d.imageRole || null, coordKey: d.coordKey, binaryEvidence:d.binaryEvidence, osPackageOwners: d.osPackageOwners || [],
|
|
370
|
+
purl: require('../purl').purlFor(d) })) });
|
|
371
|
+
}
|
|
372
|
+
const combined=require('../merge-sources').mergeBySource(cveMatches,native.matches);
|
|
373
|
+
cveMatches.splice(0,cveMatches.length,...combined);
|
|
374
|
+
for (const artifact of artifacts) {
|
|
375
|
+
options.onArtifactProgress?.({stage:'Image updates'});
|
|
376
|
+
try { artifact.imageUpdate=await require('../image-update').resolveImageUpdate(artifact.metadata,options); }
|
|
377
|
+
catch (error) { artifact.imageUpdate={status:'unknown',reference:artifact.metadata?.acquisition?.reference||null,reason:`Image update lookup unavailable: ${error.message}`,verifiedFix:false}; }
|
|
378
|
+
const matches = cveMatches.filter(m => m.dep?.artifactTargetId === artifact.id);
|
|
379
|
+
options.onArtifactProgress?.({stage:'CVE enrichment'});
|
|
380
|
+
const enrichment = await require('./enrichment').enrichArtifactFindings(matches, options);
|
|
381
|
+
const recordSources = new Set(['nvd', 'euvd', 'euvd-details']);
|
|
382
|
+
artifact.coverage.push(...enrichment.coverage.map(c => ({ ...c, artifactTargetId: artifact.id,
|
|
383
|
+
...(recordSources.has(c.collector) ? { affectsCompleteness:false,
|
|
384
|
+
diagnostics:enrichment.warnings.filter(w => w.source === c.collector) } : {}) })));
|
|
385
|
+
warnings.push(...enrichment.warnings.filter(w => !recordSources.has(w.source)).map(w => ({ ...w, artifactTargetId: artifact.id })));
|
|
386
|
+
}
|
|
387
|
+
const recordSummary = require('../cve-record-coverage').summarizeCveRecords(cveMatches,
|
|
388
|
+
{ ...options, coverage: artifacts.flatMap(a => a.coverage) });
|
|
389
|
+
if (recordSummary.warning) warnings.push(recordSummary.warning);
|
|
390
|
+
require('../priority').attachPriority(cveMatches);
|
|
391
|
+
const diagnostics=require('../diagnostics').partitionDiagnostics(warnings);
|
|
392
|
+
return { resolvedDeps, cveMatches: require('../finding-summary').uniqueFindings(cveMatches), ...diagnostics, artifacts };
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function incompleteCapabilities(result, required = ['inventory', 'advisories', 'sources']) {
|
|
396
|
+
const gaps = [];
|
|
397
|
+
for (const target of result.artifacts) {
|
|
398
|
+
for (const capability of required) {
|
|
399
|
+
if (capability === 'sources') {
|
|
400
|
+
if (result.warnings.some(w => w.affectsCompleteness !== false && w.artifactTargetId === target.id && /source|osv/.test(w.type))) gaps.push({ target: target.id, capability });
|
|
401
|
+
} else {
|
|
402
|
+
const records = target.coverage.filter(c => c.capability === capability);
|
|
403
|
+
if (!records.length || records.some(c => c.affectsCompleteness !== false && !['completed', 'not-applicable'].includes(c.execution))) gaps.push({ target: target.id, capability });
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
return gaps;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
module.exports = { acquireInventories, assessInventories, inventoryTarget, sbomTarget, readSnapshot, writeSnapshot,
|
|
411
|
+
createSnapshot, validateSnapshot, incompleteCapabilities, coverageRecords, systemDep, SNAPSHOT_SCHEMA };
|
|
@@ -5,33 +5,48 @@ const path=require('node:path');
|
|
|
5
5
|
const os=require('node:os');
|
|
6
6
|
const crypto=require('node:crypto');
|
|
7
7
|
const zlib=require('node:zlib');
|
|
8
|
-
const
|
|
9
|
-
const {
|
|
10
|
-
const
|
|
8
|
+
const tar=require('tar-stream');
|
|
9
|
+
const {pipeline}=require('node:stream/promises');
|
|
10
|
+
const {Transform}=require('node:stream');
|
|
11
11
|
const {openCacheDb,closeCacheDbs,SCHEMA_VERSION}=require('./cache-db');
|
|
12
12
|
const {proxyOrigin:canonicalOrigin}=require('./proxy-scope');
|
|
13
13
|
const FORMAT='vigievuln-sqlite-cache';
|
|
14
14
|
const ALLOWED=new Set(['.vigie-vuln/','.vigie-vuln/cache.sqlite','.vigie-vuln/cli-bundle-meta.json','.vigievuln-archive-origin.json']);
|
|
15
15
|
const sha256=file=>new Promise((resolve,reject)=>{const hash=crypto.createHash('sha256'),stream=fs.createReadStream(file);stream.on('data',part=>hash.update(part));stream.on('error',reject);stream.on('end',()=>resolve(hash.digest('hex')))});
|
|
16
|
-
async function
|
|
17
|
-
let
|
|
16
|
+
async function extractArchive(file,stage){
|
|
17
|
+
const seen=new Set(),extract=tar.extract();let failure,total=0;
|
|
18
|
+
extract.on('entry',(header,stream,next)=>{
|
|
19
|
+
(async()=>{
|
|
20
|
+
const name=header.name;
|
|
21
|
+
if(!ALLOWED.has(name)||seen.has(name)||seen.size>=4)throw Error('unsupported cache bundle: missing, duplicate or unexpected archive entries');
|
|
22
|
+
seen.add(name);
|
|
23
|
+
if(name==='.vigie-vuln/'){
|
|
24
|
+
if(header.type!=='directory')throw Error('cache bundle contains links or special files');
|
|
25
|
+
for await(const _ of stream){};next();return;
|
|
26
|
+
}
|
|
27
|
+
if(header.type!=='file' && header.type!=='contiguous-file')throw Error('cache bundle contains links or special files');
|
|
28
|
+
const limit=name==='.vigie-vuln/cache.sqlite'?64*1024**3:1024**2;
|
|
29
|
+
if(!Number.isSafeInteger(header.size)||header.size<0||header.size>limit||(total+=header.size)>64*1024**3+2*1024**2)throw Error('cache bundle exceeds size limit');
|
|
30
|
+
const destination=path.join(stage,...name.split('/'));
|
|
31
|
+
await fs.promises.mkdir(path.dirname(destination),{recursive:true,mode:0o700});
|
|
32
|
+
await pipeline(stream,fs.createWriteStream(destination,{flags:'wx',mode:0o600}));next();
|
|
33
|
+
})().catch(error=>{failure=error;stream.destroy();extract.destroy(error);});
|
|
34
|
+
});
|
|
35
|
+
let expanded=0;const counter=new Transform({transform(chunk,encoding,callback){expanded+=chunk.length;if(expanded>64*1024**3+16*1024**2)callback(Error('cache bundle exceeds size limit'));else callback(null,chunk);}});
|
|
36
|
+
try{await pipeline(fs.createReadStream(file),zlib.createGunzip(),counter,extract);}
|
|
37
|
+
catch(error){if(failure)throw failure;if(error.message==='cache bundle exceeds size limit')throw error;throw Error('unsupported cache bundle: invalid gzip or tar data');}
|
|
38
|
+
if(!seen.has('.vigie-vuln/cache.sqlite')||!seen.has('.vigie-vuln/cli-bundle-meta.json'))throw Error('unsupported cache bundle: missing or unexpected archive entries');
|
|
39
|
+
}
|
|
40
|
+
async function createArchive(file,stage,names){
|
|
41
|
+
const pack=tar.pack();const output=pipeline(pack,zlib.createGzip(),fs.createWriteStream(file,{flags:'wx',mode:0o600}));
|
|
18
42
|
try{
|
|
19
|
-
(
|
|
20
|
-
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
if(typeof code==='string' && /^[A-Z][A-Z0-9_]{0,31}$/.test(code))throw Error(`cannot inspect cache bundle: tar process failed (${code})`);
|
|
27
|
-
if(typeof code==='number')throw Error(`unsupported cache bundle: tar exited with status ${code}`);
|
|
28
|
-
if(typeof error?.signal==='string' && /^SIG[A-Z0-9]+$/.test(error.signal))throw Error(`cannot inspect cache bundle: tar terminated (${error.signal})`);
|
|
29
|
-
throw Error('cannot inspect cache bundle: tar failed');
|
|
30
|
-
}
|
|
31
|
-
const listed=names.trim().split(/\r?\n/).filter(Boolean);
|
|
32
|
-
if(!listed.length||listed.length>4||!listed.includes('.vigie-vuln/cache.sqlite')||!listed.includes('.vigie-vuln/cli-bundle-meta.json')||listed.some(name=>!ALLOWED.has(name)))throw Error('unsupported cache bundle: missing or unexpected archive entries');
|
|
33
|
-
const types=details.trim().split(/\r?\n/);
|
|
34
|
-
if(types.length!==listed.length||types.some(line=>!['-','d'].includes(line[0])))throw Error('cache bundle contains links or special files');
|
|
43
|
+
for(const name of names){
|
|
44
|
+
const source=path.join(stage,...name.split('/')),stat=await fs.promises.stat(source);
|
|
45
|
+
const entry=pack.entry({name,size:stat.size,mode:0o600,type:'file'});
|
|
46
|
+
await pipeline(fs.createReadStream(source),entry);
|
|
47
|
+
}
|
|
48
|
+
pack.finalize();await output;
|
|
49
|
+
}catch(error){pack.destroy(error);await output.catch(()=>{});throw error;}
|
|
35
50
|
}
|
|
36
51
|
function verifyDb(file){
|
|
37
52
|
const db=openCacheDb({cacheDir:path.dirname(file),readonly:true});
|
|
@@ -158,11 +173,12 @@ function mergeDatabase(targetFile,incomingFile){
|
|
|
158
173
|
}
|
|
159
174
|
async function importCache(source,{targetDir=require('./cache-directory').getCacheDir(),proxyOrigin,replace=false,force=false,onProgress,requireUsableSeed=false}={}){
|
|
160
175
|
const abs=path.resolve(source);if(!fs.statSync(abs).isFile())throw Error('cache bundle is not a file');
|
|
161
|
-
onProgress?.({phase:'validating'});
|
|
176
|
+
onProgress?.({phase:'validating'});
|
|
177
|
+
fs.mkdirSync(path.dirname(targetDir),{recursive:true,mode:0o700});
|
|
162
178
|
const stage=fs.mkdtempSync(path.join(path.dirname(targetDir),'vigievuln-sqlite-import-'));
|
|
163
179
|
try{
|
|
164
180
|
onProgress?.({phase:'extracting'});
|
|
165
|
-
await
|
|
181
|
+
await extractArchive(abs,stage);
|
|
166
182
|
const root=path.join(stage,'.vigie-vuln'),file=path.join(root,'cache.sqlite'),manifestPath=path.join(root,'cli-bundle-meta.json');
|
|
167
183
|
for(const item of [root,file,manifestPath]){const st=fs.lstatSync(item);if(st.isSymbolicLink()||st.nlink!==1&&st.isFile()||!(st.isFile()||st.isDirectory()))throw Error('unsafe cache bundle entry')}
|
|
168
184
|
const manifest=JSON.parse(fs.readFileSync(manifestPath,'utf8'));
|
|
@@ -204,8 +220,8 @@ async function exportCache(destination,{sourceDir=require('./cache-directory').g
|
|
|
204
220
|
try {
|
|
205
221
|
// Enumerate exactly the files accepted by the reader. SQLite may create
|
|
206
222
|
// sidecars in a temporary directory; never include them implicitly.
|
|
207
|
-
const
|
|
208
|
-
await
|
|
223
|
+
const names=['.vigie-vuln/cache.sqlite','.vigie-vuln/cli-bundle-meta.json'];if(proxyOrigin)names.push('.vigievuln-archive-origin.json');
|
|
224
|
+
await createArchive(temporary,stage,names);
|
|
209
225
|
verifyStandaloneSnapshot(file);
|
|
210
226
|
fs.renameSync(temporary,abs);
|
|
211
227
|
} finally {fs.rmSync(temporary,{force:true})}
|