-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathjava_maven.js
More file actions
487 lines (442 loc) · 16.1 KB
/
Copy pathjava_maven.js
File metadata and controls
487 lines (442 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { EOL } from 'os'
import { XMLParser } from 'fast-xml-parser'
import { getLicense } from '../license/license_utils.js'
import Sbom from '../sbom.js'
import { getCustom, invokeCommand } from '../tools.js'
import { filterManifestPathsByDiscoveryIgnore, resolveWorkspaceDiscoveryIgnore } from '../workspace.js'
import Base_java, { ecosystem_maven } from "./base_java.js";
/** @typedef {import('../provider').Provider} */
/** @typedef {import('../provider').Provided} Provided */
/** @typedef {{name: string, version: string}} Package */
/** @typedef {{groupId: string, artifactId: string, version: string, scope: string, ignore: boolean}} Dependency */
export default class Java_maven extends Base_java {
constructor() {
super('mvn', 'mvnw' + (process.platform === 'win32' ? '.cmd' : ''))
}
/**
* @param {string} manifestName - the subject manifest name-type
* @returns {boolean} - return true if `pom.xml` is the manifest name-type
*/
isSupported(manifestName) {
return 'pom.xml' === manifestName
}
/**
* @param {string} manifestDir - the directory where the manifest lies
*/
validateLockFile() { return true; }
/**
* Provide content and content type for maven-maven stack analysis.
* @param {string} manifest - the manifest path or name
* @param {{}} [opts={}] - optional various options to pass along the application
* @returns {Provided}
*/
provideStack(manifest, opts = {}) {
return {
ecosystem: ecosystem_maven,
content: this.#createSbomStackAnalysis(manifest, opts),
contentType: 'application/vnd.cyclonedx+json'
}
}
/**
* Provide content and content type for maven-maven component analysis.
* @param {string} manifest - path to the manifest file
* @param {{}} [opts={}] - optional various options to pass along the application
* @returns {Provided}
*/
provideComponent(manifest, opts = {}) {
return {
ecosystem: ecosystem_maven,
content: this.#getSbomForComponentAnalysis(manifest, opts),
contentType: 'application/vnd.cyclonedx+json'
}
}
/**
* Read license from pom.xml manifest, with fallback to LICENSE file
* @param {string} manifestPath - path to pom.xml
* @returns {string|null}
*/
readLicenseFromManifest(manifestPath) {
let fromPom = null;
try {
const xml = fs.readFileSync(manifestPath, 'utf-8');
const parser = new XMLParser({ ignoreAttributes: false });
const obj = parser.parse(xml);
const project = obj?.project;
if (project?.licenses?.license) {
const license = Array.isArray(project.licenses.license)
? project.licenses.license[0]
: project.licenses.license;
fromPom = (license?.name && license.name.trim()) || null;
}
} catch {
// leave fromPom as null
}
return getLicense(fromPom, manifestPath);
}
/**
* Create a Dot Graph dependency tree for a manifest path.
* @param {string} manifest - path for pom.xml
* @param {{}} [opts={}] - optional various options to pass along the application
* @returns {string} the Dot Graph content
* @private
*/
#createSbomStackAnalysis(manifest, opts = {}) {
const manifestDir = path.dirname(manifest)
const mvn = this.selectToolBinary(manifest, opts)
const mvnArgs = JSON.parse(getCustom('TRUSTIFY_DA_MVN_ARGS', '[]', opts));
if (!Array.isArray(mvnArgs)) {
throw new Error(`configured maven args is not an array, is a ${typeof mvnArgs}`)
}
// clean maven target
try {
this._invokeCommand(mvn, ['-q', 'clean', ...mvnArgs], { cwd: manifestDir })
} catch (error) {
throw new Error(`failed to clean maven target`, { cause: error })
}
// create dependency graph in a temp file
let tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trustify_da_'))
let tmpDepTree = path.join(tmpDir, 'mvn_deptree.txt')
// build initial command (dot outputType is not available for verbose mode)
let depTreeCmdArgs = ['-q', 'org.apache.maven.plugins:maven-dependency-plugin:3.6.0:tree',
'-Dscope=compile', '-Dverbose',
'-DoutputType=text', `-DoutputFile=${tmpDepTree}`]
// exclude ignored dependencies, exclude format is groupId:artifactId:scope:version.
// version and scope are marked as '*' if not specified (we do not use scope yet)
let ignoredDeps = new Array()
let ignoredArgs = new Array()
this.#getDependencies(manifest).forEach(dep => {
if (dep.ignore) {
ignoredArgs.push(`${dep['groupId']}:${dep['artifactId']}`)
//version is not reliable because we're not resolving the effective pom
ignoredDeps.push(this.toPurl(dep.groupId, dep.artifactId))
}
})
if (ignoredArgs.length > 0) {
depTreeCmdArgs.push(`-Dexcludes=${ignoredArgs.join(',')}`)
}
// execute dependency tree command
try {
this._invokeCommand(mvn, [...depTreeCmdArgs, ...mvnArgs], { cwd: manifestDir })
} catch (error) {
throw new Error(`failed creating maven dependency tree`, { cause: error })
}
// read dependency tree from temp file
let content = fs.readFileSync(tmpDepTree)
if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
console.error("Dependency tree that will be used as input for creating the BOM =>" + EOL + EOL + content.toString())
}
let sbom = this.createSbomFileFromTextFormat(content.toString(), ignoredDeps, opts, manifest);
// delete temp file and directory
fs.rmSync(tmpDir, { recursive: true, force: true })
// return dependency graph as string
return sbom
}
/**
*
* @param {String} textGraphList Text graph String of the manifest
* @param {[String]} ignoredDeps List of ignored dependencies to be omitted from sbom
* @param {String} manifestPath Path to the pom.xml manifest
* @return {String} formatted sbom Json String with all dependencies
*/
createSbomFileFromTextFormat(textGraphList, ignoredDeps, opts, manifestPath) {
let lines = textGraphList.split(EOL);
// get root component
let root = lines[0];
let rootPurl = this.parseDep(root);
const license = this.readLicenseFromManifest(manifestPath);
let sbom = new Sbom();
sbom.addRoot(rootPurl, license);
this.parseDependencyTree(root, 0, lines.slice(1), sbom);
return sbom.filterIgnoredDeps(ignoredDeps).getAsJsonString(opts);
}
/**
* Create a dependency list for a manifest content.
* @param {{}} [opts={}] - optional various options to pass along the application
* @returns {[Dependency]} the Dot Graph content
* @private
*/
#getSbomForComponentAnalysis(manifestPath, opts = {}) {
const mvn = this.selectToolBinary(manifestPath, opts)
const mvnArgs = JSON.parse(getCustom('TRUSTIFY_DA_MVN_ARGS', '[]', opts));
if (!Array.isArray(mvnArgs)) {
throw new Error(`configured maven args is not an array, is a ${typeof mvnArgs}`)
}
const tmpEffectivePom = path.resolve(path.join(path.dirname(manifestPath), 'effective-pom.xml'))
// create effective pom and save to temp file
try {
this._invokeCommand(mvn, ['-q', 'help:effective-pom', `-Doutput=${tmpEffectivePom}`, ...mvnArgs], { cwd: path.dirname(manifestPath) })
} catch (error) {
throw new Error(`failed creating maven effective pom`, { cause: error })
}
// iterate over all dependencies in original pom and collect all ignored ones
let ignored = this.#getDependencies(manifestPath).filter(d => d.ignore)
// iterate over all dependencies and create a package for every non-ignored one
/** @type [Dependency] */
let dependencies = this.#getDependencies(tmpEffectivePom)
.filter(d => !this.#dependencyIn(d, ignored))
dependencies = this.#resolveVersionRanges(dependencies, manifestPath, opts)
let sbom = new Sbom();
let rootDependency = this.#getRootFromPom(tmpEffectivePom, manifestPath);
let purlRoot = this.toPurl(rootDependency.groupId, rootDependency.artifactId, rootDependency.version)
const license = this.readLicenseFromManifest(manifestPath);
sbom.addRoot(purlRoot, license)
dependencies.forEach(dep => {
let currentPurl = this.toPurl(dep.groupId, dep.artifactId, dep.version)
sbom.addDependency(purlRoot, currentPurl)
})
fs.rmSync(tmpEffectivePom)
// return dependencies list
return sbom.getAsJsonString(opts)
}
/**
*
* @param effectivePomManifest effective pom manifest path
* @param originalManifest pom.xml manifest path
* @return {Dependency} returns the root dependency for the pom
* @private
*/
#getRootFromPom(effectivePomManifest) {
let parser = new XMLParser()
let buf = fs.readFileSync(effectivePomManifest)
let effectivePomStruct = parser.parse(buf.toString())
let pomRoot
if (effectivePomStruct['project']) {
pomRoot = effectivePomStruct['project']
} else { // if there is no project root tag, then it's a multi module/submodules aggregator parent POM
for (let proj of effectivePomStruct['projects']['project']) {
// need to choose the aggregate POM and not one of the modules.
if (proj.packaging && proj.packaging === 'pom') {
pomRoot = proj
}
}
}
/** @type Dependency */
let rootDependency = {
groupId: pomRoot['groupId'],
artifactId: pomRoot['artifactId'],
version: pomRoot['version'],
scope: '*',
ignore: false
}
return rootDependency
}
/**
* Get a list of dependencies with marking of dependencies commented with <!--exhortignore-->.
* @param {string} manifest - path for pom.xml
* @returns {[Dependency]} an array of dependencies
* @private
*/
#getDependencies(manifest) {
/** @type [Dependency] */
let ignored = []
// build xml parser with options
let parser = new XMLParser({
commentPropName: '#comment', // mark comments with #comment
isArray: (_, jpath) => 'project.dependencies.dependency' === jpath,
parseTagValue: false
})
// read manifest pom.xml file into buffer
let buf = fs.readFileSync(manifest)
// parse manifest pom.xml to json
let pomJson = parser.parse(buf.toString())
// iterate over all dependencies and chery pick dependencies with a exhortignore comment
let pomXml;
// project without modules
if (pomJson['project']) {
if (pomJson['project']['dependencies'] !== undefined) {
pomXml = pomJson['project']['dependencies']['dependency']
} else {
pomXml = []
}
} else { // project with modules
pomXml = pomJson['projects']['project'].filter(project => project.dependencies !== undefined).flatMap(project => project.dependencies.dependency)
}
pomXml.forEach(dep => {
let ignore = false
if (dep['#comment'] && dep['#comment'].includes('exhortignore')) { // #comment is an array or a string
ignore = true
}
if (dep['scope'] !== 'test') {
ignored.push({
groupId: dep['groupId'],
artifactId: dep['artifactId'],
version: dep['version'] ? dep['version'].toString() : '*',
scope: '*',
ignore: ignore
})
}
})
// return list of dependencies
return ignored
}
/**
* Utility function for looking up a dependency in a list of dependencies ignoring the "ignored"
* field
* @param dep {Dependency} dependency to look for
* @param deps {[Dependency]} list of dependencies to look in
* @returns boolean true if found dep in deps
* @private
*/
#dependencyIn(dep, deps) {
return deps.filter(d => dep.artifactId === d.artifactId && dep.groupId === d.groupId && dep.scope === d.scope).length > 0
}
/**
* Returns true if the given version string is a Maven version range
* (starts with '[' or '(').
* @param {string} version
* @returns {boolean}
* @private
*/
#isVersionRange(version) {
return typeof version === 'string' && (version.startsWith('[') || version.startsWith('('))
}
/**
* Resolves Maven version ranges in the given dependency list by running
* maven-dependency-plugin:tree and reading the concrete versions it selects.
* If no dependency uses a version range, returns the list unchanged.
* @param {Dependency[]} dependencies
* @param {string} manifestPath
* @param {object} opts
* @returns {Dependency[]}
* @private
*/
#resolveVersionRanges(dependencies, manifestPath, opts = {}) {
// short-circuit if no dependency has a version range
if (!dependencies.some(dep => this.#isVersionRange(dep.version))) {
return dependencies
}
const mvn = this.selectToolBinary(manifestPath, opts)
const mvnArgs = JSON.parse(getCustom('TRUSTIFY_DA_MVN_ARGS', '[]', opts));
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'trustify_da_range_'))
const tmpDepTree = path.join(tmpDir, 'mvn_deptree_ranges.txt')
try {
this._invokeCommand(mvn, [
'-q',
'org.apache.maven.plugins:maven-dependency-plugin:3.6.0:tree',
'-Dscope=compile',
'-DoutputType=text',
`-DoutputFile=${tmpDepTree}`,
...mvnArgs
], { cwd: path.dirname(manifestPath) })
const content = fs.readFileSync(tmpDepTree)
const lines = content.toString().split(EOL).filter(l => l.trim() !== '')
// Build a map of groupId:artifactId -> resolved version from depth-1 entries
/** @type {Map<string, string>} */
const resolvedVersions = new Map()
for (const line of lines) {
if (this._getDepth(line) === 1) {
const purl = this.parseDep(line)
resolvedVersions.set(`${purl.namespace}:${purl.name}`, purl.version)
}
}
// Replace version ranges with resolved concrete versions
return dependencies.map(dep => {
if (this.#isVersionRange(dep.version)) {
const key = `${dep.groupId}:${dep.artifactId}`
const resolved = resolvedVersions.get(key)
if (resolved) {
return { ...dep, version: resolved }
}
}
return dep
})
} catch (error) {
if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
console.error("Failed to resolve Maven version ranges: " + error.message)
}
return dependencies
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true })
}
}
}
const DEFAULT_MAVEN_DISCOVERY_IGNORE = [
'**/target/**',
]
/**
* Discover all pom.xml manifest paths in a Maven multi-module project.
*
* @param {string} workspaceRoot - Absolute or relative path to workspace root (must contain pom.xml)
* @param {object} [opts={}]
* @returns {Promise<string[]>} Paths to pom.xml files (absolute)
*/
export async function discoverMavenModules(workspaceRoot, opts = {}) {
const root = path.resolve(workspaceRoot)
const rootPom = path.join(root, 'pom.xml')
if (!fs.existsSync(rootPom)) {
return []
}
let mvnBin
try {
mvnBin = new Java_maven().selectToolBinary(rootPom, opts)
} catch {
return [rootPom]
}
const visited = new Set()
const manifestPaths = [rootPom]
collectMavenModules(root, mvnBin, visited, manifestPaths)
const ignorePatterns = [...resolveWorkspaceDiscoveryIgnore(opts), ...DEFAULT_MAVEN_DISCOVERY_IGNORE]
return filterManifestPathsByDiscoveryIgnore(manifestPaths, root, ignorePatterns)
}
/**
* @param {string} dir - Absolute path to directory containing pom.xml
* @param {string} mvnBin - Maven binary path
* @param {Set<string>} visited - Already-visited directories (cycle guard)
* @param {string[]} manifestPaths - Accumulator for discovered pom.xml paths
*/
function collectMavenModules(dir, mvnBin, visited, manifestPaths) {
const resolvedDir = path.resolve(dir)
if (visited.has(resolvedDir)) {
return
}
visited.add(resolvedDir)
const modules = listMavenModules(resolvedDir, mvnBin)
for (const mod of modules) {
const moduleDir = path.resolve(resolvedDir, mod)
const modulePom = path.join(moduleDir, 'pom.xml')
if (fs.existsSync(modulePom)) {
manifestPaths.push(modulePom)
collectMavenModules(moduleDir, mvnBin, visited, manifestPaths)
}
}
}
/**
* @param {string} dir - Directory containing pom.xml
* @param {string} mvnBin - Maven binary path
* @returns {string[]} Module directory names (relative to `dir`)
*/
function listMavenModules(dir, mvnBin) {
let output
try {
output = invokeCommand(mvnBin, [
'help:evaluate',
'-Dexpression=project.modules',
'-q',
'-DforceStdout',
'-f', path.join(dir, 'pom.xml'),
'--batch-mode',
], { cwd: dir })
} catch {
return []
}
const raw = output.toString().trim()
if (!raw || raw.startsWith('<modules')) {
return []
}
return parseMavenModuleList(raw)
}
/**
* @param {string} raw - Raw stdout from mvn help:evaluate -DforceStdout
* @returns {string[]}
*/
function parseMavenModuleList(raw) {
const parser = new XMLParser()
const parsed = parser.parse(raw)
const entries = parsed?.strings?.string
if (!entries) { return [] }
const list = Array.isArray(entries) ? entries : [entries]
return list.map(s => String(s).trim()).filter(Boolean)
}