vigievuln 1.2.1 → 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 +12 -2
- package/README.md +10 -4
- 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/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/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-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 +34 -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 +50 -8
- 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 +32 -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/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/package.json +12 -3
- package/vigievuln.js +204 -95
package/lib/cli-image.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const { Command, InvalidArgumentError } = require('commander');
|
|
6
|
+
const { acquireInventories, assessInventories, writeSnapshot, incompleteCapabilities } = require('./artifacts/scan');
|
|
7
|
+
|
|
8
|
+
const REPORTS = Object.freeze({
|
|
9
|
+
json: { name: 'findings.json', write: (p, f) => require('./json-export').writeFindings(p, f) },
|
|
10
|
+
html: { name: 'cve-report.html', write: (p, f) => fs.writeFileSync(f, require('./cve-report').generateHtmlReport(p)) },
|
|
11
|
+
doc: { name: 'cve-report.doc', write: (p, f) => fs.writeFileSync(f, require('./cve-report').generateWordReport(p)) },
|
|
12
|
+
sbom: { name: 'sbom.cdx.json', write: (p, f) => require('./sbom-export').writeCycloneDx(p.resolvedDeps, p.cveMatches, f, { projectInfo: p.projectInfo, toolVersion: p.toolVersion }) },
|
|
13
|
+
csaf: { name: 'vex.csaf.json', write: (p, f) => require('./csaf-export').writeCsaf(p.resolvedDeps, p.cveMatches, f, { projectInfo: p.projectInfo, toolVersion: p.toolVersion }) },
|
|
14
|
+
sarif: { name: 'findings.sarif.json', write: (p, f) => require('./sarif-export').writeSarif(p.cveMatches, f, { projectInfo: p.projectInfo, toolVersion: p.toolVersion }) },
|
|
15
|
+
xlsx: { name: 'report.xlsx', write: (p, f) => require('./xlsx-export').writeXlsx(p, f) },
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
function jsonFile(file) {
|
|
19
|
+
if (fs.statSync(file).size > 1024 * 1024) throw Error('configuration file is too large');
|
|
20
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
21
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw Error('configuration must be a JSON object');
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
function distribution(value) {
|
|
25
|
+
const match = /^([a-z][a-z0-9_-]*):([^\s:]+)$/.exec(value);
|
|
26
|
+
if (!match) throw new InvalidArgumentError('expected distribution-id:release, e.g. debian:12');
|
|
27
|
+
return { id: match[1], versionId: match[2] };
|
|
28
|
+
}
|
|
29
|
+
// Compare existing files by inode and resolve parent symlinks for new outputs.
|
|
30
|
+
function canonicalFile(file) {
|
|
31
|
+
const absolute = path.resolve(file); let current = absolute, suffix = [];
|
|
32
|
+
while (!fs.existsSync(current)) { const parent = path.dirname(current); if (parent === current) break; suffix.unshift(path.basename(current)); current = parent; }
|
|
33
|
+
try { current = fs.realpathSync(current); } catch { /* unresolved path */ }
|
|
34
|
+
return path.join(current, ...suffix);
|
|
35
|
+
}
|
|
36
|
+
function sameFile(a,b) {
|
|
37
|
+
if (canonicalFile(a) === canonicalFile(b)) return true;
|
|
38
|
+
try { const x=fs.statSync(a),y=fs.statSync(b); return x.dev===y.dev && x.ino===y.ino; } catch { return false; }
|
|
39
|
+
}
|
|
40
|
+
function reportFiles(opts) {
|
|
41
|
+
if (opts.report === false) return [];
|
|
42
|
+
const explicit=Object.keys(REPORTS).filter(format=>opts['report'+format[0].toUpperCase()+format.slice(1)]!==undefined);
|
|
43
|
+
const selected=opts.reports?opts.reports.split(',').map(s=>s.trim()):explicit.length?explicit:['html','json'];
|
|
44
|
+
const formats=[...new Set([...selected,...explicit])];
|
|
45
|
+
if(formats.some(format=>!REPORTS[format]))throw Error('unknown report format');
|
|
46
|
+
return formats.map(format=>{const specified=opts['report'+format[0].toUpperCase()+format.slice(1)];return {format,file:path.resolve(typeof specified==='string'?specified:path.join(opts.reportOutput,REPORTS[format].name))};});
|
|
47
|
+
}
|
|
48
|
+
function makeCommand() {
|
|
49
|
+
const command = new Command().name('vigievuln image').description('Native image, rootfs and publisher-inventory audit. No Docker or package-manager execution.')
|
|
50
|
+
.argument('[input]', 'Docker/OCI/rootfs archive, directory, registry reference or inventory')
|
|
51
|
+
.option('--config <file>', 'read scan configuration from a JSON file')
|
|
52
|
+
.option('--source-profile <profile>', 'advisory operator scope: all, us, eu or proxy')
|
|
53
|
+
.option('--proxy <url>', 'corporate forward proxy for outbound connections')
|
|
54
|
+
.option('--proxy-cache <url|vigievuln|default>', 'use a shared advisory proxy')
|
|
55
|
+
.option('--proxy-rate-limit-wait-ms <milliseconds>', 'maximum proxy retry wait per request (default: 45000)', Number)
|
|
56
|
+
.option('--reuse-stable-advisories', 'reuse cached individual advisories unchanged for at least the configured age', true)
|
|
57
|
+
.option('--no-reuse-stable-advisories', 'refresh older individual advisories using normal cache lifetimes')
|
|
58
|
+
.option('--stable-advisory-age-days <days>', 'minimum unchanged advisory age for reuse (default: 365)', Number)
|
|
59
|
+
.option('--force-update', 'revalidate consulted online sources, retaining cached data on failure')
|
|
60
|
+
.option('--proxy-cache-token <token>', 'shared advisory proxy authentication token')
|
|
61
|
+
.option('--vigievuln-proxy [domain]', 'use the hosted VigieVuln proxy, fr or com')
|
|
62
|
+
.option('--allow-insecure-http', 'allow HTTP to the configured advisory proxy for this invocation')
|
|
63
|
+
.option('--registry', 'obtain input directly from an OCI registry; offline uses a prepared cached inventory')
|
|
64
|
+
.option('--platform <os/arch[/variant]>', 'select an image platform; otherwise inspect all available platforms')
|
|
65
|
+
.option('--prefer-sbom', 'prefer publisher SBOMs when associated with the selected images; signatures remain unverified')
|
|
66
|
+
.option('--registry-auth <file>', 'JSON credentials {username,password,token,authOrigins}; never invokes credential helpers')
|
|
67
|
+
.option('--insecure', 'allow HTTP registry endpoints explicitly')
|
|
68
|
+
.option('--inventory', 'input is an exported VigieVuln artifact inventory')
|
|
69
|
+
.option('--sbom', 'input is a CycloneDX/SPDX or attestation JSON document')
|
|
70
|
+
.option('--expected-digest <digest>', 'require a supplied SBOM subject to agree with this image digest')
|
|
71
|
+
.option('--advisory-config <file>', 'JSON custom distribution advisory scope and optional source URL')
|
|
72
|
+
.option('--distribution <id:release>', 'explicit distribution scope for imported advisories or SBOM', distribution)
|
|
73
|
+
.option('--offline', 'zero network access; use imported advisory snapshots and cached inventories')
|
|
74
|
+
.option('--enrich <sources>', 'enrichment sources: nvd,kev,epss,gcve,euvd,certfr or none', value => value === 'none' ? [] : value.split(',').map(s => s.trim()), ['nvd', 'kev', 'epss', 'gcve', 'euvd', 'certfr'])
|
|
75
|
+
.option('--no-osv', 'exclude OSV advisory matching')
|
|
76
|
+
.option('--no-distro-advisories', 'exclude independent distribution tracker consultations')
|
|
77
|
+
.option('--no-publisher-advisories', 'exclude publisher advisory feeds')
|
|
78
|
+
.option('--no-nvd', 'exclude NVD enrichment')
|
|
79
|
+
.option('--no-kev', 'exclude CISA KEV enrichment')
|
|
80
|
+
.option('--no-epss', 'exclude EPSS enrichment')
|
|
81
|
+
.option('--no-gcve', 'exclude native GCVE advisory matching and derived aliases')
|
|
82
|
+
.option('--no-euvd', 'exclude ENISA EUVD enrichment')
|
|
83
|
+
.option('--no-certfr', 'exclude CERT-FR enrichment')
|
|
84
|
+
.option('--cache-dir <directory>', 'cache directory containing prepared vulnerability data')
|
|
85
|
+
.option('--prepare-cache <file>', 'warm and export advisory cache for an inventory')
|
|
86
|
+
.option('--definitions <directory>', 'find image declarations in source; only explicit matching digests bind to scanned images')
|
|
87
|
+
.option('--export-inventory <file>', 'save portable inventory independently of image contents')
|
|
88
|
+
.option('--import-advisories <file>', 'import a native OSV JSON/JSONL/ZIP dataset for --distribution')
|
|
89
|
+
.option('--snapshot-complete', 'declare imported dataset complete for the stated distribution release')
|
|
90
|
+
.option('--sync-advisories', 'prepare a distribution advisory snapshot online; requires --distribution when no image is supplied')
|
|
91
|
+
.option('--limits <file>', 'JSON resource policy {artifactLimits,registryLimits,maxMetadataBytes,...}')
|
|
92
|
+
.option('--report-output <directory>', 'report directory', './vigievuln-report')
|
|
93
|
+
.option('-r, --reports <formats>', 'comma-separated report formats: ' + Object.keys(REPORTS).join(','))
|
|
94
|
+
.option('--no-report', 'write no reports; inventory export and CI gates remain active')
|
|
95
|
+
.option('--fail-on <severity>', 'fail with exit 1 for matching findings: low,medium,high,critical,kev', 'none')
|
|
96
|
+
.option('--fail-on-incomplete [capabilities]', 'exit 2 for incomplete inventory/advisories/sources', false)
|
|
97
|
+
.option('--lang <language>', 'report language: en or fr', 'en');
|
|
98
|
+
for (const format of Object.keys(REPORTS)) command.option(`--report-${format} [file]`, `write ${format} report`);
|
|
99
|
+
return command;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function run(args, injected = {}) {
|
|
103
|
+
const command = makeCommand();
|
|
104
|
+
command.parse(args, { from: 'user' });
|
|
105
|
+
const setup = require('./image-network').configureImageNetwork(command, injected);
|
|
106
|
+
try {
|
|
107
|
+
const opts = setup.options, input = command.args[0];
|
|
108
|
+
for (const warning of setup.warnings) console.warn(`⚠ ${warning}`);
|
|
109
|
+
if (![opts.registry, opts.inventory, opts.sbom].filter(Boolean).length) opts.mode = 'artifact';
|
|
110
|
+
if ([opts.registry, opts.inventory, opts.sbom].filter(Boolean).length > 1) throw Error('--registry, --inventory and --sbom are mutually exclusive');
|
|
111
|
+
if (opts.preferSbom && !opts.registry) throw Error('--prefer-sbom requires --registry');
|
|
112
|
+
if (opts.prepareCache && (!opts.inventory || opts.offline)) throw Error('--prepare-cache requires an inventory and online mode');
|
|
113
|
+
if (!['en', 'fr'].includes(opts.lang)) throw Error('--lang must be en or fr');
|
|
114
|
+
if (!['none', 'low', 'medium', 'high', 'critical', 'kev'].includes(opts.failOn)) throw Error('invalid --fail-on severity');
|
|
115
|
+
const required = opts.failOnIncomplete ? (opts.failOnIncomplete === true ? 'inventory,advisories,sources' : opts.failOnIncomplete).split(',').map(x => x.trim()) : [];
|
|
116
|
+
if (required.some(x => !['inventory', 'advisories', 'sources'].includes(x))) throw Error('invalid --fail-on-incomplete capability');
|
|
117
|
+
const cacheDir = opts.cacheDir;
|
|
118
|
+
const policy = opts.limits ? jsonFile(opts.limits) : {};
|
|
119
|
+
const credentials = opts.registryAuth ? jsonFile(opts.registryAuth) : {
|
|
120
|
+
token: process.env.VIGIEVULN_REGISTRY_TOKEN, username: process.env.VIGIEVULN_REGISTRY_USER, password: process.env.VIGIEVULN_REGISTRY_PASSWORD,
|
|
121
|
+
};
|
|
122
|
+
const options = { ...policy, ...opts, cacheDir, credentials, authOrigins: credentials.authOrigins || [],
|
|
123
|
+
...(opts.advisoryConfig ? { advisoryConfig: typeof opts.advisoryConfig === 'string' ? jsonFile(opts.advisoryConfig) : opts.advisoryConfig } : {}) };
|
|
124
|
+
if (opts.osv === false && (opts.importAdvisories || opts.syncAdvisories)) throw Error('OSV advisories are excluded by the selected source profile');
|
|
125
|
+
if (opts.importAdvisories) {
|
|
126
|
+
if (!opts.distribution) throw Error('--import-advisories requires --distribution');
|
|
127
|
+
const imported = await require('./system-inventory').importSystemAdvisories(opts.importAdvisories, { ...options, complete: !!opts.snapshotComplete });
|
|
128
|
+
console.log(`Imported ${imported.recordCount} advisory records for ${imported.ecosystem}.`);
|
|
129
|
+
}
|
|
130
|
+
if (!input) {
|
|
131
|
+
if (opts.syncAdvisories) {
|
|
132
|
+
if (!opts.distribution) throw Error('--sync-advisories requires --distribution when no image is supplied');
|
|
133
|
+
const synced = await require('./system-inventory').syncSystemAdvisories(opts.distribution, options);
|
|
134
|
+
console.log(`Prepared ${synced.recordCount} advisory records for ${synced.ecosystem}.`);
|
|
135
|
+
return { synced };
|
|
136
|
+
}
|
|
137
|
+
if (opts.importAdvisories) return {};
|
|
138
|
+
throw Error('an image/archive/rootfs/inventory input is required; see vigievuln image --help');
|
|
139
|
+
}
|
|
140
|
+
const reports = reportFiles(opts);
|
|
141
|
+
const outputs = [...(opts.exportInventory ? [{label:'inventory',file:path.resolve(opts.exportInventory)}] : []), ...(opts.prepareCache ? [{label:'cache',file:path.resolve(opts.prepareCache)}] : []), ...reports.map(r => ({label:r.format,file:r.file}))];
|
|
142
|
+
if (reports.length) outputs.push({label:'checksums',file:path.join(path.dirname(reports[0].file),'SHA256SUMS')});
|
|
143
|
+
for (let i=0;i<outputs.length;i++) {
|
|
144
|
+
if (fs.existsSync(input) && sameFile(input,outputs[i].file)) throw Error(`${outputs[i].label} output must not overwrite the input artifact`);
|
|
145
|
+
for(let j=0;j<i;j++) if(sameFile(outputs[i].file,outputs[j].file)) throw Error('output paths must be distinct');
|
|
146
|
+
}
|
|
147
|
+
const targets = await acquireInventories(input, options);
|
|
148
|
+
const savedReferences = new Map();
|
|
149
|
+
for (const target of targets) for (const ref of target.metadata?.declarations || []) if (ref?.id && !savedReferences.has(ref.id)) savedReferences.set(ref.id, ref);
|
|
150
|
+
let imageReferences = [...savedReferences.values()];
|
|
151
|
+
if (opts.definitions) {
|
|
152
|
+
const discovery = require('./image-references').discoverImageReferences(path.resolve(opts.definitions));
|
|
153
|
+
imageReferences = require('./image-references').bindImageDefinitions(targets, discovery.references);
|
|
154
|
+
for (const target of targets) target.metadata.definitionDiscovery = { status: discovery.warnings.length ? 'incomplete' : target.metadata.definitions.length ? 'matched' : 'no-match', source: path.basename(path.resolve(opts.definitions)) };
|
|
155
|
+
if (discovery.warnings.length) for (const target of targets) target.warnings.push(...discovery.warnings.map(w => ({ ...w, capability: 'inventory' })));
|
|
156
|
+
}
|
|
157
|
+
if (opts.exportInventory) await writeSnapshot(opts.exportInventory, targets);
|
|
158
|
+
const result = await assessInventories(targets, options);
|
|
159
|
+
if (opts.prepareCache) {
|
|
160
|
+
const gaps = incompleteCapabilities(result, ['advisories', 'sources']);
|
|
161
|
+
if (gaps.length) console.warn('⚠ Prepared cache has incomplete advisory or source coverage; review the scan notices.');
|
|
162
|
+
const prepared = await require('./cache-archive-sqlite').exportCache(opts.prepareCache, { sourceDir: cacheDir,
|
|
163
|
+
proxyOrigin: options.proxyCache ? require('./proxy-scope').proxyOrigin(options.proxyCache) : undefined });
|
|
164
|
+
console.log(`Prepared cache: ${prepared.path}`);
|
|
165
|
+
}
|
|
166
|
+
const toolVersion = require('../package.json').version;
|
|
167
|
+
const payload = { ...result, toolVersion, locale: opts.lang,
|
|
168
|
+
projectInfo: { name: path.basename(input), src: '(artifact inventory)', toolVersion, generatedAt: new Date().toISOString(),
|
|
169
|
+
artifacts: result.artifacts, ...(imageReferences.length ? { imageReferences } : {}), provenance: { mode: opts.offline ? 'offline' : 'online',notices:[...(setup.notices||[]),...(result.notices||[])],
|
|
170
|
+
dataSources: result.artifacts.flatMap(a => a.coverage.filter(c => c.capability === 'advisories' || c.capability === 'sources').map(c => ({
|
|
171
|
+
label: c.ecosystem || c.source || c.collector, status: c.execution === 'not-applicable' ? 'disabled' : c.execution === 'completed' ? 'cached' : 'missing',
|
|
172
|
+
asOf: c.fetchedAt ? new Date(c.fetchedAt).toISOString() : null, detail: c.reason || c.execution }))) } } };
|
|
173
|
+
let written = [];
|
|
174
|
+
if (opts.report !== false) {
|
|
175
|
+
for (const { format, file } of reports) {
|
|
176
|
+
await fs.promises.mkdir(path.dirname(file), { recursive: true });
|
|
177
|
+
await REPORTS[format].write(payload, file);
|
|
178
|
+
written.push(file);
|
|
179
|
+
}
|
|
180
|
+
if (written.length) {
|
|
181
|
+
const checksum = path.join(path.dirname(written[0]), 'SHA256SUMS');
|
|
182
|
+
require('./report-integrity').writeChecksums(written, checksum, { baseDir: path.dirname(checksum) });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
const gate = require('./gate').evaluateGate(result.cveMatches, opts.failOn);
|
|
186
|
+
const gaps = incompleteCapabilities(result, required);
|
|
187
|
+
if (opts.failOn === 'kev') {
|
|
188
|
+
gaps.push(...incompleteCapabilities(result, ['advisories']));
|
|
189
|
+
for (const artifact of result.artifacts) {
|
|
190
|
+
const hasCve = result.cveMatches.some(m => m.dep.artifactTargetId === artifact.id);
|
|
191
|
+
const kev = artifact.coverage.find(c => c.capability === 'sources' && c.collector === 'kev');
|
|
192
|
+
if (hasCve && (!kev || kev.execution !== 'completed')) gaps.push({ target: artifact.id, capability: 'kev' });
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const malicious = result.cveMatches.some(m => m.malicious && !m.suppressed);
|
|
196
|
+
const exitCode = gaps.length ? 2 : gate.failed || malicious ? 1 : 0;
|
|
197
|
+
process.exitCode = exitCode;
|
|
198
|
+
console.log(`${result.artifacts.length} artifact(s), ${result.resolvedDeps.size} components, ${result.cveMatches.length} findings, ${result.warnings.length} warning(s).`);
|
|
199
|
+
for (const warning of result.warnings) console.warn(`⚠ ${warning.message}`);
|
|
200
|
+
for (const file of written) console.log(file);
|
|
201
|
+
if (gaps.length) console.warn(`Required coverage incomplete: ${[...new Set(gaps.map(g => g.capability))].join(', ')}.`);
|
|
202
|
+
return { ...result, written, exitCode };
|
|
203
|
+
} finally { setup.restore(); }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
module.exports = { run, makeCommand, REPORTS };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Parse file-backed ELF structures without executing the inspected file.
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const MAX_SEGMENT = 32 * 1024 * 1024;
|
|
4
|
+
function extractElfMetadataFile(fd, size, options = {}) {
|
|
5
|
+
try {
|
|
6
|
+
const max = options.maxMetadataBytes || MAX_SEGMENT;
|
|
7
|
+
function read(pos, n) {
|
|
8
|
+
if (!Number.isSafeInteger(pos) || !Number.isSafeInteger(n) || pos < 0 || n < 0 || n > max || pos + n > size) throw Error('ELF bounds or metadata limit');
|
|
9
|
+
const b = Buffer.alloc(n); let off = 0;
|
|
10
|
+
while (off < n) { const got = fs.readSync(fd, b, off, n - off, pos + off); if (!got) throw Error('ELF truncated'); off += got; }
|
|
11
|
+
return b;
|
|
12
|
+
}
|
|
13
|
+
const h = read(0, 16);
|
|
14
|
+
if (!h.subarray(0, 4).equals(Buffer.from([127,69,76,70])) || ![1,2].includes(h[4]) || ![1,2].includes(h[5])) throw Error('unsupported ELF class or byte order');
|
|
15
|
+
const bits = h[4] === 1 ? 32 : 64, le = h[5] === 1;
|
|
16
|
+
const u16 = (b,p) => le ? b.readUInt16LE(p) : b.readUInt16BE(p);
|
|
17
|
+
const u32 = (b,p) => le ? b.readUInt32LE(p) : b.readUInt32BE(p);
|
|
18
|
+
const word = (b,p) => { const v = bits === 32 ? BigInt(u32(b,p)) : le ? b.readBigUInt64LE(p) : b.readBigUInt64BE(p); if (v > BigInt(Number.MAX_SAFE_INTEGER)) throw Error('ELF integer exceeds safe range'); return Number(v); };
|
|
19
|
+
const header = read(0, bits === 32 ? 52 : 64);
|
|
20
|
+
const phoff = word(header, bits === 32 ? 28 : 32), phentsize = u16(header, bits === 32 ? 42 : 54), phnum = u16(header, bits === 32 ? 44 : 56);
|
|
21
|
+
if (phnum > 4096 || (phnum && phentsize < (bits === 32 ? 32 : 56))) throw Error('unsupported ELF program header table');
|
|
22
|
+
const table = read(phoff, phnum * phentsize), segments = [];
|
|
23
|
+
for (let i = 0; i < phnum; i++) { const p = i * phentsize; const type = u32(table,p), flags = u32(table,p + (bits === 32 ? 24 : 4)); const offset = word(table,p + (bits === 32 ? 4 : 8)), vaddr = word(table,p + (bits === 32 ? 8 : 16)), filesz = word(table,p + (bits === 32 ? 16 : 32)); if (offset + filesz > size) throw Error('ELF segment outside file'); segments.push({ type, flags, offset, vaddr, filesz }); }
|
|
24
|
+
const mapped = (addr,n) => { const s = segments.find(x => x.type === 1 && addr >= x.vaddr && addr - x.vaddr + n <= x.filesz); if (!s) throw Error('ELF unmapped address'); return s.offset + addr - s.vaddr; };
|
|
25
|
+
const result = { format:'elf', bits, endian: le ? 'little' : 'big', machine: u16(header,18), type: u16(header,16), needed: [] };
|
|
26
|
+
const interp = segments.find(s => s.type === 3); if (interp && interp.filesz) result.interpreter = read(interp.offset,interp.filesz).toString('utf8').replace(/\0.*$/s,'');
|
|
27
|
+
for (const s of segments.filter(x => x.type === 4)) {
|
|
28
|
+
const b = read(s.offset,s.filesz); let p = 0;
|
|
29
|
+
while (p + 12 <= b.length) { const namesz = u32(b,p), descsz = u32(b,p+4), type = u32(b,p+8); p += 12; const a = Math.ceil(namesz/4)*4, d = Math.ceil(descsz/4)*4; if (p + a + d > b.length) break; if (type === 3 && b.subarray(p,p+namesz).toString('ascii').replace(/\0+$/,'') === 'GNU' && descsz <= 1024) result.buildId = b.subarray(p+a,p+a+descsz).toString('hex'); p += a+d; }
|
|
30
|
+
}
|
|
31
|
+
const dynamic = segments.find(s => s.type === 2);
|
|
32
|
+
if (dynamic) {
|
|
33
|
+
const b = read(dynamic.offset,dynamic.filesz), step = bits === 32 ? 8 : 16; let str = null, strsz = null, soname = null; const needed=[];
|
|
34
|
+
for (let p=0; p+step<=b.length; p+=step) { const tag=word(b,p), val=word(b,p+step/2); if (!tag) break; if(tag===5) str=val; else if(tag===10) strsz=val; else if(tag===1) needed.push(val); else if(tag===14) soname=val; }
|
|
35
|
+
if (str !== null && strsz !== null && strsz <= max) { const strings=read(mapped(str,strsz),strsz); const get = n => { if(n>=strings.length) throw Error('ELF string offset'); const end=strings.indexOf(0,n); if(end<0) throw Error('ELF unterminated string'); return strings.toString('utf8',n,end); }; result.needed=needed.map(get); if(soname!==null) result.soname=get(soname); }
|
|
36
|
+
}
|
|
37
|
+
result.go = require('./go-buildinfo').extractGoBuildInfo({read, segments, mapped, max});
|
|
38
|
+
if (!result.go) delete result.go;
|
|
39
|
+
return result;
|
|
40
|
+
} catch (error) { return { format:'elf', status:'unavailable', reason:error.message }; }
|
|
41
|
+
}
|
|
42
|
+
module.exports = { extractElfMetadataFile, MAX_SEGMENT };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// Go linker build-info blob; supports inline and pre-1.18 pointer formats.
|
|
2
|
+
const MAGIC = Buffer.from('\xff Go buildinf:', 'latin1');
|
|
3
|
+
function extractGoBuildInfo({read, segments, mapped, max}) {
|
|
4
|
+
try {
|
|
5
|
+
let budget = max, skipped = false;
|
|
6
|
+
for (const s of segments.filter(x => x.type === 1 && (x.flags & 2) && x.filesz)) {
|
|
7
|
+
if (s.filesz > budget) { skipped = true; continue; }
|
|
8
|
+
budget -= s.filesz;
|
|
9
|
+
const b = read(s.offset,s.filesz);
|
|
10
|
+
for (let pos = b.indexOf(MAGIC); pos >= 0; pos = b.indexOf(MAGIC,pos+1)) {
|
|
11
|
+
if ((s.vaddr+pos)%16 || pos+32>b.length) continue;
|
|
12
|
+
const ptrSize=b[pos+14], flags=b[pos+15]; if (![4,8].includes(ptrSize) || (flags & ~3)) continue;
|
|
13
|
+
const le=!(flags&1);
|
|
14
|
+
const ptr=(buf,p) => { const n=ptrSize===4 ? BigInt(le?buf.readUInt32LE(p):buf.readUInt32BE(p)) : le?buf.readBigUInt64LE(p):buf.readBigUInt64BE(p); if(n>BigInt(Number.MAX_SAFE_INTEGER)) throw Error('pointer overflow'); return Number(n); };
|
|
15
|
+
const memory=(addr,n)=>read(mapped(addr,n),n);
|
|
16
|
+
let version, mod;
|
|
17
|
+
if (flags&2) {
|
|
18
|
+
let p=pos+32;
|
|
19
|
+
const string=()=>{ let n=0, mult=1, c, count=0; do { if(p>=b.length || count++>=8) throw Error('varint'); c=b[p++]; n+=(c&127)*mult; mult*=128; } while(c&128); if(!Number.isSafeInteger(n) || n>max || p+n>b.length) throw Error('string bounds'); const t=b.toString('latin1',p,p+n); p+=n; return t; };
|
|
20
|
+
version=string(); mod=string();
|
|
21
|
+
} else {
|
|
22
|
+
const str=addr=>{ if(!addr)return ''; const hdr=memory(addr,ptrSize*2), start=ptr(hdr,0), len=ptr(hdr,ptrSize); if(len>max) throw Error('string limit'); return memory(start,len).toString('latin1'); };
|
|
23
|
+
version=str(ptr(b,pos+16)); mod=str(ptr(b,pos+16+ptrSize));
|
|
24
|
+
}
|
|
25
|
+
if (!version.startsWith('go')) continue;
|
|
26
|
+
// Module text is surrounded by 16-byte sentinels, as in debug/buildinfo.
|
|
27
|
+
if (mod.length >= 33 && mod[mod.length-17] === '\n') mod=Buffer.from(mod.slice(16,-16),'latin1').toString('utf8'); else mod='';
|
|
28
|
+
const modules=[],settings={}; let last=null;
|
|
29
|
+
for (const line of mod.split('\n')) { const f=line.split('\t'); if ((f[0]==='mod'||f[0]==='dep') && f.length>=3) { last={kind:f[0],path:f[1],version:f[2],sum:f[3]||null}; modules.push(last); } else if(f[0]==='=>' && last && f.length>=2) last.replace={path:f[1],version:f[2] || null,sum:f[3]||null}; else if(f[0]==='build' && f.length===2) { const i=f[1].indexOf('='); if(i>0) {const key=f[1].slice(0,i),value=f[1].slice(i+1);if(/^[A-Za-z0-9_.-]{1,80}$/.test(key) && value.length<=1024) {if(Object.hasOwn(settings,key))settings[key]=null;else settings[key]=value;}} } }
|
|
30
|
+
return { version, modules, settings };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (skipped) return {status:'unavailable',reason:'Go build information search exceeded metadata limit'};
|
|
34
|
+
} catch { return {status:'unavailable',reason:'Malformed Go build information'}; }
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
module.exports={extractGoBuildInfo};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Format registry keeps new binary parsers independent of the walker.
|
|
2
|
+
const extractors = new Map([
|
|
3
|
+
['pe', (fd,size) => require('./pe-metadata').extractPeMetadataFile(fd,size)],
|
|
4
|
+
['elf', (fd,size,opts) => require('./elf-metadata').extractElfMetadataFile(fd,size,opts)],
|
|
5
|
+
]);
|
|
6
|
+
function extractMetadata(kind,fd,size,opts) { const fn=extractors.get(kind); return fn ? fn(fd,size,opts) : {format:kind,status:'unsupported'}; }
|
|
7
|
+
module.exports={extractors,extractMetadata};
|
|
@@ -3,9 +3,8 @@
|
|
|
3
3
|
* (.dll/.exe/.so/.dylib) and hash each. Dependency archives (.jar/.war/.ear) are
|
|
4
4
|
* owned by the Maven codec's jar-scan.js, not here.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* hashed or reported.
|
|
6
|
+
* ELF magic is recognized regardless of filename; PE and Mach-O also require
|
|
7
|
+
* an appropriate extension. Other data and spoofed extensions are rejected.
|
|
9
8
|
*
|
|
10
9
|
* @author: N.BRAUN
|
|
11
10
|
* @email: pp9ping@gmail.com
|
|
@@ -28,7 +27,7 @@ const MAGIC_BYTES = 8; // enough for every signature we sniff
|
|
|
28
27
|
const MAX_FILE_BYTES = 512 * 1024 * 1024;
|
|
29
28
|
const HASH_CHUNK_BYTES = 1024 * 1024;
|
|
30
29
|
|
|
31
|
-
function inspectFile(fp, kind, detectOnly) {
|
|
30
|
+
function inspectFile(fp, kind, detectOnly, opts = {}) {
|
|
32
31
|
let fd;
|
|
33
32
|
try {
|
|
34
33
|
fd = fs.openSync(fp, "r");
|
|
@@ -36,9 +35,12 @@ function inspectFile(fp, kind, detectOnly) {
|
|
|
36
35
|
if (!before.isFile()) throw Error("not a regular file");
|
|
37
36
|
const magic = Buffer.alloc(MAGIC_BYTES);
|
|
38
37
|
const n = fs.readSync(fd, magic, 0, magic.length, 0);
|
|
39
|
-
|
|
40
|
-
if (
|
|
41
|
-
|
|
38
|
+
const actual = sniffKind(magic.subarray(0, n));
|
|
39
|
+
if (!actual || (actual !== "elf" && actual !== kind)) return null;
|
|
40
|
+
kind = actual;
|
|
41
|
+
if (detectOnly) return { kind };
|
|
42
|
+
const limit = opts.maxFileBytes ?? MAX_FILE_BYTES;
|
|
43
|
+
if (before.size > limit) throw Error(`file size ${before.size} exceeds binary scan limit ${limit} bytes`);
|
|
42
44
|
const sha1 = crypto.createHash("sha1"), sha256 = crypto.createHash("sha256");
|
|
43
45
|
const chunk = Buffer.alloc(Math.min(HASH_CHUNK_BYTES, before.size));
|
|
44
46
|
let offset = 0;
|
|
@@ -48,11 +50,11 @@ function inspectFile(fp, kind, detectOnly) {
|
|
|
48
50
|
sha1.update(chunk.subarray(0, count)); sha256.update(chunk.subarray(0, count));
|
|
49
51
|
offset += count;
|
|
50
52
|
}
|
|
51
|
-
const metadata =
|
|
53
|
+
const metadata = require("./metadata").extractMetadata(kind, fd, before.size, opts);
|
|
52
54
|
const after = fs.fstatSync(fd);
|
|
53
55
|
if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs)
|
|
54
56
|
throw Error("file changed during binary scan");
|
|
55
|
-
return { size: offset, sha1: sha1.digest("hex"), sha256: sha256.digest("hex"), metadata };
|
|
57
|
+
return { kind, size: offset, sha1: sha1.digest("hex"), sha256: sha256.digest("hex"), metadata };
|
|
56
58
|
} finally { if (fd !== undefined) fs.closeSync(fd); }
|
|
57
59
|
}
|
|
58
60
|
|
|
@@ -73,12 +75,11 @@ function scanBinaries(dir, opts = {}) {
|
|
|
73
75
|
if (e.isDirectory()) { if (!skipDir(fp, e.name)) stack.push(fp); continue; }
|
|
74
76
|
if (!e.isFile()) continue;
|
|
75
77
|
const ext = extKind(e.name);
|
|
76
|
-
if (!ext) continue; // not an allowlisted extension
|
|
77
78
|
try {
|
|
78
|
-
|
|
79
|
-
const h = inspectFile(fp, ext, opts.detectOnly);
|
|
79
|
+
const h = inspectFile(fp, ext, opts.detectOnly, opts);
|
|
80
80
|
if (!h) continue;
|
|
81
|
-
|
|
81
|
+
if (onProgress) onProgress(fp);
|
|
82
|
+
out.push({ path: fp, ...h, declaredName: e.name });
|
|
82
83
|
if (opts.detectOnly) return out;
|
|
83
84
|
} catch (error) { warn(fp, error); }
|
|
84
85
|
}
|
|
@@ -1,26 +1,27 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* lib/codecs/binary/sniff.js — file-type confirmation for the binary codec.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* magic) is rejected. We never trust the extension alone.
|
|
4
|
+
* ELF is identified by magic irrespective of filename. PE and Mach-O retain
|
|
5
|
+
* extension and magic confirmation, avoiding ambiguous signatures.
|
|
7
6
|
*
|
|
8
7
|
* @author: N.BRAUN
|
|
9
8
|
* @email: pp9ping@gmail.com
|
|
10
9
|
*/
|
|
11
10
|
|
|
12
|
-
//
|
|
11
|
+
// Format detectors are ordered; extensions remain hints for formats whose
|
|
12
|
+
// signatures can overlap other file types (notably Mach-O fat binaries).
|
|
13
|
+
const detectors = [
|
|
14
|
+
{ kind: "pe", matches: b => b[0] === 0x4d && b[1] === 0x5a },
|
|
15
|
+
{ kind: "elf", matches: b => b[0] === 0x7f && b[1] === 0x45 && b[2] === 0x4c && b[3] === 0x46 },
|
|
16
|
+
{ kind: "zip", matches: b => b[0] === 0x50 && b[1] === 0x4b && b[2] === 0x03 && b[3] === 0x04 },
|
|
17
|
+
{ kind: "macho", matches: b => {
|
|
18
|
+
const signatures = [0xfeedface, 0xfeedfacf, 0xcafebabe, 0xcafebabf];
|
|
19
|
+
return signatures.includes(b.readUInt32BE(0)) || signatures.includes(b.readUInt32LE(0));
|
|
20
|
+
} },
|
|
21
|
+
];
|
|
13
22
|
function sniffKind(buf) {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
if (b0 === 0x4d && b1 === 0x5a) return "pe"; // MZ
|
|
17
|
-
if (b0 === 0x7f && b1 === 0x45 && b2 === 0x4c && b3 === 0x46) return "elf"; // \x7FELF
|
|
18
|
-
if (b0 === 0x50 && b1 === 0x4b && b2 === 0x03 && b3 === 0x04) return "zip"; // PK\x03\x04
|
|
19
|
-
const be = ((b0 << 24) | (b1 << 16) | (b2 << 8) | b3) >>> 0;
|
|
20
|
-
const le = ((b3 << 24) | (b2 << 16) | (b1 << 8) | b0) >>> 0;
|
|
21
|
-
const machO = new Set([0xfeedface, 0xfeedfacf, 0xcafebabe, 0xcafebabf]);
|
|
22
|
-
if (machO.has(be) || machO.has(le)) return "macho";
|
|
23
|
-
return null;
|
|
23
|
+
if (!buf || buf.length < 4) return null;
|
|
24
|
+
return detectors.find(d => d.matches(buf))?.kind || null;
|
|
24
25
|
}
|
|
25
26
|
|
|
26
27
|
const EXT_PE = /\.(dll|exe)$/i;
|
|
@@ -34,4 +35,4 @@ function extKind(name) {
|
|
|
34
35
|
return null;
|
|
35
36
|
}
|
|
36
37
|
|
|
37
|
-
module.exports = { sniffKind, extKind };
|
|
38
|
+
module.exports = { sniffKind, extKind, detectors };
|
|
@@ -17,7 +17,11 @@ module.exports = {
|
|
|
17
17
|
id: "binary",
|
|
18
18
|
label: "Binaries",
|
|
19
19
|
osvEcosystem: null, // no OSV ecosystem until identified
|
|
20
|
-
manifestNames: ["*.dll", "*.exe", "*.so", "*.dylib"],
|
|
20
|
+
manifestNames: ["*.dll", "*.exe", "*.so", "*.dylib"],
|
|
21
|
+
async detectFile(fp) {
|
|
22
|
+
const fs = require("fs"); let handle;
|
|
23
|
+
try { handle = await fs.promises.open(fp, "r"); const b = Buffer.alloc(4); const { bytesRead } = await handle.read(b, 0, 4, 0); return require("./binary/sniff").sniffKind(b.subarray(0, bytesRead)) === "elf"; } catch { return false; } finally { if (handle) await handle.close(); }
|
|
24
|
+
}, // lets detectCodecs include us in auto mode
|
|
21
25
|
|
|
22
26
|
detect(dir) {
|
|
23
27
|
try {
|
|
@@ -31,7 +35,7 @@ module.exports = {
|
|
|
31
35
|
const out = new Map();
|
|
32
36
|
const warnings = [];
|
|
33
37
|
let records;
|
|
34
|
-
try { records = scanBinaries(dir, { onProgress: opts.onBinaryProgress, onWarning: warning => warnings.push(warning), srcRoot: opts.srcRoot || dir, excludePath: opts.excludePath, defaultExcludes: opts.defaultExcludes }); }
|
|
38
|
+
try { records = scanBinaries(dir, { ...opts, onProgress: opts.onBinaryProgress, onWarning: warning => warnings.push(warning), srcRoot: opts.srcRoot || dir, excludePath: opts.excludePath, defaultExcludes: opts.defaultExcludes }); }
|
|
35
39
|
catch (e) { return { deps: out, warnings: [{ type: "dependency-coverage", reason: "binary-scan-error", ecosystem: "binary", manifestPath: dir, message: `binary scan failed: ${e.message}` }] }; }
|
|
36
40
|
for (const r of records) {
|
|
37
41
|
const record = makeDepRecord({
|
|
@@ -45,6 +49,22 @@ module.exports = {
|
|
|
45
49
|
});
|
|
46
50
|
if (r.metadata) record.binaryMetadata = r.metadata;
|
|
47
51
|
out.set(`binary:${r.path}`, record);
|
|
52
|
+
const goVersion = /^go(\d+)\.(\d+)(?:\.(\d+))?$/.exec(r.metadata?.go?.version || "");
|
|
53
|
+
if (goVersion) {
|
|
54
|
+
const version = `v${goVersion[1]}.${goVersion[2]}.${goVersion[3] || "0"}`;
|
|
55
|
+
const dep = makeDepRecord({ ecosystem: "go", name: "stdlib", version, manifestPath: r.path, provenance: "binary-module", scope: "transitive" });
|
|
56
|
+
dep.coordKey = `binary-module:${r.path}:stdlib@${version}`;
|
|
57
|
+
dep.binaryEvidence = { binaryPath: r.path, source: "go-buildinfo", runtimeVersion: r.metadata.go.version, symbolReachability: "unknown" };
|
|
58
|
+
out.set(dep.coordKey, dep);
|
|
59
|
+
}
|
|
60
|
+
for (const module of r.metadata?.go?.modules || []) {
|
|
61
|
+
const selected = module.replace || module;
|
|
62
|
+
if (!selected.path || !/^v\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/.test(selected.version || "")) continue;
|
|
63
|
+
const dep = makeDepRecord({ ecosystem: "go", name: selected.path, version: selected.version, manifestPath: r.path, provenance: "binary-module", scope: "transitive" });
|
|
64
|
+
dep.coordKey = `binary-module:${r.path}:${selected.path}@${selected.version}`;
|
|
65
|
+
dep.binaryEvidence = { binaryPath: r.path, source: "go-buildinfo", original: module };
|
|
66
|
+
out.set(dep.coordKey, dep);
|
|
67
|
+
}
|
|
48
68
|
}
|
|
49
69
|
return { deps: out, warnings };
|
|
50
70
|
},
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
* @author: N.BRAUN
|
|
21
21
|
* @email: pp9ping@gmail.com
|
|
22
22
|
*/
|
|
23
|
-
const { resolveLibraryAccessor, findCatalogVersion } = require("./catalog");
|
|
23
|
+
const { resolveLibraryAccessor, findCatalogVersion, normKey } = require("./catalog");
|
|
24
24
|
const { compareMavenVersions } = require("../../maven-version");
|
|
25
25
|
|
|
26
26
|
const COORD = "[A-Za-z0-9_.\\-]+";
|
|
@@ -79,6 +79,8 @@ function resolveVer(raw, ctx) {
|
|
|
79
79
|
m = v.match(/\$\{?([\w.]+)\}?/);
|
|
80
80
|
if (m) {
|
|
81
81
|
const k = m[1];
|
|
82
|
+
if (ctx.ambiguousVars?.has(k)) return null;
|
|
83
|
+
if (ctx.extVars?.has(k) && m[0] !== v) return null;
|
|
82
84
|
if (ctx.localVars && ctx.localVars[k] != null) return ctx.localVars[k];
|
|
83
85
|
if (ctx.properties && ctx.properties[k] != null) return ctx.properties[k];
|
|
84
86
|
}
|
|
@@ -338,6 +340,38 @@ function findExcludes(clean, mask, from, to) {
|
|
|
338
340
|
return out;
|
|
339
341
|
}
|
|
340
342
|
|
|
343
|
+
// Spring Boot imports its matching BOM only when BOTH plugins are applied. Limit
|
|
344
|
+
// inference to a top-level plugins block: pluginManagement, apply false, comments
|
|
345
|
+
// and strings do not establish that either plugin runs in this project.
|
|
346
|
+
function springBootBom(clean, mask, blocks, ctx) {
|
|
347
|
+
const applied = new Map();
|
|
348
|
+
for (const block of blocks) {
|
|
349
|
+
if (block.header !== "plugins" || enclosingBlocks(blocks, block.open).length) continue;
|
|
350
|
+
const declarations = [...clean.slice(block.open + 1, block.close).matchAll(
|
|
351
|
+
/\b(?:id\s*(?:\(\s*)?(["'])([^"']+)\1\s*\)?|alias\s*\(\s*libs\.plugins\.([\w.]+)\s*\))/g
|
|
352
|
+
)].filter(m => mask[block.open + 1 + m.index] !== " ");
|
|
353
|
+
for (let i = 0; i < declarations.length; i++) {
|
|
354
|
+
const m = declarations[i];
|
|
355
|
+
const start = block.open + 1 + m.index + m[0].length;
|
|
356
|
+
const end = i + 1 < declarations.length ? block.open + 1 + declarations[i + 1].index : block.close;
|
|
357
|
+
const suffix = clean.slice(start, end);
|
|
358
|
+
if (/\bapply\s*(?:\(\s*)?false\b/.test(mask.slice(start, end))) continue;
|
|
359
|
+
const plugin = m[3] && Object.entries(ctx.catalog?.plugins || {}).find(([alias]) => normKey(alias) === normKey(m[3]))?.[1];
|
|
360
|
+
const id = m[2] || plugin?.id;
|
|
361
|
+
const versionExpr = suffix.match(/^\s*\.?\s*version\s*(?:\(\s*)?(["'])(.*?)\1/s);
|
|
362
|
+
let version = versionExpr ? versionExpr[2] : plugin?.version;
|
|
363
|
+
// Only resolve a whole variable here; resolveVer's best-effort dependency
|
|
364
|
+
// parsing would turn "4.${patch}" into just the value of patch.
|
|
365
|
+
if (version?.includes("$")) version = /^\$(?:[\w.]+|\{[\w.]+\})$/.test(version) ? resolveVer(version, ctx) : null;
|
|
366
|
+
if (id) applied.set(id, version || null);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
const version = applied.get("org.springframework.boot");
|
|
370
|
+
// Unknown and dynamic versions cannot identify a concrete BOM safely.
|
|
371
|
+
if (!applied.has("io.spring.dependency-management") || !version || !/^\d[\w.\-]*$/.test(version)) return null;
|
|
372
|
+
return { group: "org.springframework.boot", name: "spring-boot-dependencies", version, inferred: true };
|
|
373
|
+
}
|
|
374
|
+
|
|
341
375
|
/**
|
|
342
376
|
* Best-effort parse of a build.gradle / build.gradle.kts.
|
|
343
377
|
* @param opts { catalog, properties, kotlin, extraExcludes } — catalog from
|
|
@@ -359,6 +393,28 @@ function parseBuildScript(text, opts = {}) {
|
|
|
359
393
|
const { clean, mask } = lexScript(src);
|
|
360
394
|
for (const m of clean.matchAll(/\b(?:val|def)\s+(\w+)\s*=\s*["']([^"']*)["']/g)) ctx.localVars[m[1]] = m[2];
|
|
361
395
|
const blocks = scriptBlocks(clean, mask);
|
|
396
|
+
if (!opts.kotlin) {
|
|
397
|
+
// Recognize only literal assignments directly in a top-level Groovy ext
|
|
398
|
+
// block. Any other assignment to the same name makes its value uncertain.
|
|
399
|
+
const assignments = [...mask.matchAll(/\b([A-Za-z_]\w*)\s*(?:\*\*=|<<=|>>>=|>>=|\+=|-=|\*=|\/=|%=|&=|\|=|\^=|=(?!=))/g)];
|
|
400
|
+
const extAssignments = assignments.filter(m => {
|
|
401
|
+
const parents = enclosingBlocks(blocks, m.index);
|
|
402
|
+
return parents.length === 1 && parents[0].header === "ext" && !/[\w.]/.test(mask[m.index - 1] || "");
|
|
403
|
+
});
|
|
404
|
+
// Indexed or method-based writes may compute the property name at runtime.
|
|
405
|
+
const indirectWrite = /\b(?:ext|(?:project\s*\.\s*)?ext)\s*(?:\[|\.\s*(?:set|setProperty)\s*\()|\b(?:setProperty|setExtProperty)\s*\(/.test(mask);
|
|
406
|
+
ctx.ambiguousVars = new Set();
|
|
407
|
+
ctx.extVars = new Set();
|
|
408
|
+
for (const m of extAssignments) {
|
|
409
|
+
const name = m[1];
|
|
410
|
+
const literal = clean.slice(m.index + m[0].length).match(/^[ \t]*(["'])(\d[\w.\-]*)\1(?=[ \t]*(?:;|\n|}|$))/);
|
|
411
|
+
const mutated = new RegExp(`(?:\\b${name}\\s*(?:\\+\\+|--)|(?:\\+\\+|--)\\s*(?:[A-Za-z_]\\w*\\s*\\.\\s*)*${name}\\b)`).test(mask);
|
|
412
|
+
if (!literal || indirectWrite || mutated || assignments.filter(a => a[1] === name).length !== 1 || !/^\w+\s*=$/.test(m[0])) {
|
|
413
|
+
ctx.ambiguousVars.add(name);
|
|
414
|
+
delete ctx.localVars[name];
|
|
415
|
+
} else { ctx.localVars[name] = literal[2]; ctx.extVars.add(name); }
|
|
416
|
+
}
|
|
417
|
+
}
|
|
362
418
|
const blockAt = new Map(blocks.map(b => [b.open, b]));
|
|
363
419
|
const isGlobal = idx => enclosingBlocks(blocks, idx).some(b => GLOBAL_HEADER.test(b.header));
|
|
364
420
|
|
|
@@ -380,6 +436,9 @@ function parseBuildScript(text, opts = {}) {
|
|
|
380
436
|
if (coord && coord.group && coord.name && !platformBoms.some(b => b.group === coord.group && b.name === coord.name)) platformBoms.push(coord);
|
|
381
437
|
blankSpans.push([pm.index, end + 1]);
|
|
382
438
|
}
|
|
439
|
+
// Keep an explicit platform declaration authoritative when it names this BOM.
|
|
440
|
+
const bootBom = springBootBom(clean, mask, blocks, ctx);
|
|
441
|
+
if (bootBom && !platformBoms.some(b => b.group === bootBom.group && b.name === bootBom.name)) platformBoms.push(bootBom);
|
|
383
442
|
|
|
384
443
|
// 2. force(…) / forcedModules = [ … ] — a FORCE is a version constraint that wins over
|
|
385
444
|
// every other requirement, not a dependency: it only applies if something brings the
|
|
@@ -507,10 +566,12 @@ function parseBuildScript(text, opts = {}) {
|
|
|
507
566
|
const scope = depScope(d.config);
|
|
508
567
|
const existing = byKey.get(key);
|
|
509
568
|
if (!existing) {
|
|
510
|
-
byKey.set(key, { group: d.group, name: d.name, version, configuration: d.config, ...scope, exclusionSets: [exclusions] });
|
|
569
|
+
byKey.set(key, { group: d.group, name: d.name, version, configuration: d.config, configurations: [d.config], ...scope, exclusionSets: [exclusions], gradleDeclarations: [{ configuration: d.config, exclusions }] });
|
|
511
570
|
continue;
|
|
512
571
|
}
|
|
513
572
|
existing.exclusionSets.push(exclusions);
|
|
573
|
+
existing.gradleDeclarations.push({ configuration: d.config, exclusions });
|
|
574
|
+
if (!existing.configurations.includes(d.config)) existing.configurations.push(d.config);
|
|
514
575
|
// The WIDEST scope wins (a production declaration beats a test one, whatever the
|
|
515
576
|
// order): `testImplementation` listed above `implementation` used to file the dep as
|
|
516
577
|
// test-only — out of the production count and the CI gate. The version follows the
|