Repository navigation
Expand file tree
/
Copy pathcli.js
More file actions
644 lines (617 loc) · 19 KB
/
Copy pathcli.js
File metadata and controls
644 lines (617 loc) · 19 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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
#!/usr/bin/env node
import fs from 'node:fs'
import * as path from "path";
import yargs from 'yargs'
import { hideBin } from 'yargs/helpers'
import { resolveConfig } from './config.js'
import { getProjectLicense, getLicenseDetails } from './license/index.js'
import { runRemediation } from './remediate.js'
import { generateReport } from './remediation_report.js'
import client, { selectTrustifyDABackend, generateSbom } from './index.js'
/**
* Builds a yargs middleware that loads `.trustify-da.yml` (discovered by walking
* up from the command's target path, or cwd when no path is available) and fills `--providers`, `--sources`, and
* `--group-by` with config file values when they were not supplied on the CLI or
* via environment variables. Precedence: CLI flag > env var > config file > default.
* @param {string} [pathKey] - positional argument holding the target path; defaults to the current working directory
* @param {{ groupBy?: boolean }} [options={}] - set `groupBy` when the command exposes `--group-by`
* @returns {(args: object) => object} yargs middleware
*/
function configMiddleware(pathKey, options = {}) {
return args => {
const startPath = pathKey === undefined ? process.cwd() : args[pathKey]
const envVars = options.groupBy
? process.env
: Object.fromEntries(Object.entries(process.env).filter(([key]) => key !== 'TRUSTIFY_DA_GROUP_BY'))
const merged = resolveConfig(
startPath,
{ backendUrl: args.backendUrl, providers: args.providers, sources: args.sources, groupBy: args['group-by'] },
envVars
)
if (merged.backendUrlSource === 'file' && process.env.TRUSTIFY_DA_TOKEN) {
throw new Error('Refusing to send TRUSTIFY_DA_TOKEN to a backend selected by project configuration. Set --backend-url or TRUSTIFY_DA_BACKEND_URL to explicitly trust it.')
}
if (args.providers !== undefined || merged.providers.length) {
args.providers = merged.providers.join(',')
}
if (args.sources !== undefined || merged.sources.length) {
args.sources = merged.sources.join(',')
}
if (merged.backendUrl != null) {
args.backendUrl = merged.backendUrl
}
if (options.groupBy) {
args['group-by'] = merged.groupBy
}
const fileExclude = merged.remediation?.exclude
if (Array.isArray(fileExclude) && fileExclude.length > 0) {
const cliExclude = Array.isArray(args.exclude) ? args.exclude : []
args.exclude = [...new Set([...cliExclude, ...fileExclude])]
}
return args
}
}
// command for component analysis take manifest type and content
const component = {
command: 'component </path/to/manifest>',
desc: 'produce component report for manifest path',
builder: yargs => yargs.positional(
'/path/to/manifest',
{
desc: 'manifest path for analyzing',
type: 'string',
normalize: true,
}
).options({
workspaceDir: {
alias: 'w',
desc: 'Workspace root directory (for monorepos; lock file is expected here)',
type: 'string',
normalize: true,
},
backendUrl: {
desc: 'Trustify DA backend URL (env: TRUSTIFY_DA_BACKEND_URL)',
type: 'string',
},
providers: {
desc: 'Comma-separated list of vulnerability providers (env: TRUSTIFY_DA_PROVIDERS)',
type: 'string',
},
sources: {
desc: 'Comma-separated list of vulnerability sources (env: TRUSTIFY_DA_SOURCES)',
type: 'string',
}
}).middleware(configMiddleware('/path/to/manifest')),
handler: async args => {
let manifestName = args['/path/to/manifest']
const opts = args.workspaceDir ? { TRUSTIFY_DA_WORKSPACE_DIR: args.workspaceDir } : {}
if (args.backendUrl !== undefined) {
opts.TRUSTIFY_DA_BACKEND_URL = args.backendUrl
}
if (args.providers !== undefined) {
opts.TRUSTIFY_DA_PROVIDERS = args.providers
}
if (args.sources !== undefined) {
opts.TRUSTIFY_DA_SOURCES = args.sources
}
let res = await client.componentAnalysis(manifestName, opts)
console.log(JSON.stringify(res, null, 2))
}
}
const validateToken = {
command: 'validate-token <token-provider> [--token-value thevalue]',
desc: 'Validates input token if authentic and authorized',
builder: yargs => yargs.positional(
'token-provider',
{
desc: 'the token provider name',
type: 'string'
}
).options({
tokenValue: {
alias: 'value',
desc: 'the actual token value to be checked',
type: 'string',
}
}),
handler: async args => {
let tokenProvider = args['token-provider'].toUpperCase()
let opts={}
if(args['tokenValue'] !== undefined && args['tokenValue'].trim() !=="" ) {
let tokenValue = args['tokenValue'].trim()
opts[`TRUSTIFY_DA_PROVIDER_${tokenProvider}_TOKEN`] = tokenValue
}
let res = await client.validateToken(opts)
console.log(res)
}
}
// command for image analysis takes OCI image references
const image = {
command: 'image <image-refs..>',
desc: 'produce image analysis report for OCI image references',
builder: yargs => yargs.positional(
'image-refs',
{
desc: 'OCI image references to analyze (one or more)',
type: 'string',
array: true,
}
).options({
html: {
alias: 'r',
desc: 'Get the report as HTML instead of JSON',
type: 'boolean',
conflicts: 'summary'
},
summary: {
alias: 's',
desc: 'For JSON report, get only the \'summary\'',
type: 'boolean',
conflicts: 'html'
},
backendUrl: {
desc: 'Trustify DA backend URL (env: TRUSTIFY_DA_BACKEND_URL)',
type: 'string',
},
providers: {
desc: 'Comma-separated list of vulnerability providers (env: TRUSTIFY_DA_PROVIDERS)',
type: 'string',
},
sources: {
desc: 'Comma-separated list of vulnerability sources (env: TRUSTIFY_DA_SOURCES)',
type: 'string',
}
}).middleware(configMiddleware()),
handler: async args => {
let imageRefs = args['image-refs']
if (!Array.isArray(imageRefs)) {
imageRefs = [imageRefs]
}
let html = args['html']
let summary = args['summary']
const opts = {}
if (args.backendUrl !== undefined) {
opts.TRUSTIFY_DA_BACKEND_URL = args.backendUrl
}
if (args.providers !== undefined) {
opts.TRUSTIFY_DA_PROVIDERS = args.providers
}
if (args.sources !== undefined) {
opts.TRUSTIFY_DA_SOURCES = args.sources
}
let res = await client.imageAnalysis(imageRefs, html, opts)
if(summary && !html) {
let summaries = {}
for (let [imageRef, report] of Object.entries(res)) {
for (let provider in report.providers) {
if (report.providers[provider].sources !== undefined) {
for (let source in report.providers[provider].sources) {
if (report.providers[provider].sources[source].summary) {
if (!summaries[imageRef]) {
summaries[imageRef] = {};
}
if (!summaries[imageRef][provider]) {
summaries[imageRef][provider] = {};
}
summaries[imageRef][provider][source] = report.providers[provider].sources[source].summary
}
}
}
}
}
res = summaries
}
console.log(html ? res : JSON.stringify(res, null, 2))
}
}
// command for stack analysis takes a manifest path
const stack = {
command: 'stack </path/to/manifest> [--html|--summary]',
desc: 'produce stack report for manifest path',
builder: yargs => yargs.positional(
'/path/to/manifest',
{
desc: 'manifest path for analyzing',
type: 'string',
normalize: true,
}
).options({
html: {
alias: 'r',
desc: 'Get the report as HTML instead of JSON',
type: 'boolean',
conflicts: 'summary'
},
summary: {
alias: 's',
desc: 'For JSON report, get only the \'summary\'',
type: 'boolean',
conflicts: 'html'
},
workspaceDir: {
alias: 'w',
desc: 'Workspace root directory (for monorepos; lock file is expected here)',
type: 'string',
normalize: true,
},
backendUrl: {
desc: 'Trustify DA backend URL (env: TRUSTIFY_DA_BACKEND_URL)',
type: 'string',
},
providers: {
desc: 'Comma-separated list of vulnerability providers (env: TRUSTIFY_DA_PROVIDERS)',
type: 'string',
},
sources: {
desc: 'Comma-separated list of vulnerability sources (env: TRUSTIFY_DA_SOURCES)',
type: 'string',
}
}).middleware(configMiddleware('/path/to/manifest')),
handler: async args => {
let manifest = args['/path/to/manifest']
let html = args['html']
let summary = args['summary']
const opts = args.workspaceDir ? { TRUSTIFY_DA_WORKSPACE_DIR: args.workspaceDir } : {}
if (args.backendUrl !== undefined) {
opts.TRUSTIFY_DA_BACKEND_URL = args.backendUrl
}
if (args.providers !== undefined) {
opts.TRUSTIFY_DA_PROVIDERS = args.providers
}
if (args.sources !== undefined) {
opts.TRUSTIFY_DA_SOURCES = args.sources
}
let theProvidersSummary = new Map();
let theProvidersObject ={}
let res = await client.stackAnalysis(manifest, html, opts)
if(summary)
{
for (let provider in res.providers ) {
if (res.providers[provider].sources !== undefined) {
for(let source in res.providers[provider].sources ) {
if(res.providers[provider].sources[source].summary) {
theProvidersSummary.set(source,res.providers[provider].sources[source].summary)
}
}
}
}
for (let [provider, providerSummary] of theProvidersSummary) {
theProvidersObject[provider]=providerSummary
}
}
console.log(html ? res : JSON.stringify(
!html && summary ? theProvidersObject : res,
null,
2
))
}
}
// command for batch stack analysis (workspace)
const stackBatch = {
command: 'stack-batch </path/to/workspace-root> [--html|--summary] [--concurrency <n>] [--ignore <pattern>...] [--metadata] [--fail-fast]',
desc: 'produce stack report for all packages/crates in a workspace (Cargo or JS/TS)',
builder: yargs => yargs.positional(
'/path/to/workspace-root',
{
desc: 'workspace root directory (containing Cargo.toml+Cargo.lock or package.json+lock file)',
type: 'string',
normalize: true,
}
).options({
html: {
alias: 'r',
desc: 'Get the report as HTML instead of JSON',
type: 'boolean',
conflicts: 'summary'
},
summary: {
alias: 's',
desc: 'For JSON report, get only the \'summary\' per package',
type: 'boolean',
conflicts: 'html'
},
concurrency: {
alias: 'c',
desc: 'Max parallel SBOM generations (default: 10, env: TRUSTIFY_DA_BATCH_CONCURRENCY)',
type: 'number',
},
ignore: {
alias: 'i',
desc: 'Extra glob patterns excluded from workspace discovery (merged with defaults). Repeat flag per pattern. Env: TRUSTIFY_DA_WORKSPACE_DISCOVERY_IGNORE (comma-separated)',
type: 'string',
array: true,
},
metadata: {
alias: 'm',
desc: 'Return { analysis, metadata } with per-manifest errors (env: TRUSTIFY_DA_BATCH_METADATA=true)',
type: 'boolean',
default: false,
},
failFast: {
desc: 'Stop on first invalid package.json or SBOM error (env: TRUSTIFY_DA_CONTINUE_ON_ERROR=false)',
type: 'boolean',
default: false,
},
backendUrl: {
desc: 'Trustify DA backend URL (env: TRUSTIFY_DA_BACKEND_URL)',
type: 'string',
},
providers: {
desc: 'Comma-separated list of vulnerability providers (env: TRUSTIFY_DA_PROVIDERS)',
type: 'string',
},
sources: {
desc: 'Comma-separated list of vulnerability sources (env: TRUSTIFY_DA_SOURCES)',
type: 'string',
}
}).middleware(configMiddleware('/path/to/workspace-root')),
handler: async args => {
const workspaceRoot = args['/path/to/workspace-root']
const html = args['html']
const summary = args['summary']
const opts = {}
if (args.backendUrl !== undefined) {
opts.TRUSTIFY_DA_BACKEND_URL = args.backendUrl
}
if (args.concurrency != null) {
opts.batchConcurrency = args.concurrency
}
const extraIgnores = Array.isArray(args.ignore) ? args.ignore.filter(p => p != null && String(p).trim()) : []
if (extraIgnores.length > 0) {
opts.workspaceDiscoveryIgnore = extraIgnores
}
if (args.metadata) {
opts.batchMetadata = true
}
if (args.failFast) {
opts.continueOnError = false
}
if (args.providers !== undefined) {
opts.TRUSTIFY_DA_PROVIDERS = args.providers
}
if (args.sources !== undefined) {
opts.TRUSTIFY_DA_SOURCES = args.sources
}
let res = await client.stackAnalysisBatch(workspaceRoot, html, opts)
const batchAnalysis =
res && typeof res === 'object' && res != null && 'analysis' in res ? res.analysis : res
if (summary && !html && typeof batchAnalysis === 'object') {
const summaries = {}
for (const [purl, report] of Object.entries(batchAnalysis)) {
if (report?.providers) {
for (const provider of Object.keys(report.providers)) {
const sources = report.providers[provider]?.sources
if (sources) {
for (const [source, data] of Object.entries(sources)) {
if (data?.summary) {
if (!summaries[purl]) {
summaries[purl] = {}
}
if (!summaries[purl][provider]) {
summaries[purl][provider] = {}
}
summaries[purl][provider][source] = data.summary
}
}
}
}
}
}
if (res && typeof res === 'object' && res != null && 'metadata' in res) {
res = { analysis: summaries, metadata: res.metadata }
} else {
res = summaries
}
}
if (html) {
const htmlContent = res && typeof res === 'object' && 'analysis' in res ? res.analysis : res
console.log(htmlContent)
} else {
console.log(JSON.stringify(res, null, 2))
}
}
}
// command for license checking
const license = {
command: 'license </path/to/manifest>',
desc: 'Display project license information from manifest and LICENSE file in JSON format',
builder: yargs => yargs.positional(
'/path/to/manifest',
{
desc: 'manifest path for license analysis',
type: 'string',
normalize: true,
}
),
handler: async args => {
let manifestPath = args['/path/to/manifest']
const opts = {} // CLI options can be extended in the future
try {
selectTrustifyDABackend(opts)
} catch (err) {
console.error(JSON.stringify({ error: err.message }, null, 2))
process.exit(1)
}
let localResult
try {
localResult = getProjectLicense(manifestPath)
} catch (err) {
console.error(JSON.stringify({ error: `Failed to read manifest: ${err.message}` }, null, 2))
process.exit(1)
}
const errors = []
// Build LicenseInfo objects
const buildLicenseInfo = async (spdxId) => {
if (!spdxId) {return null}
const licenseInfo = { spdxId }
try {
const details = await getLicenseDetails(spdxId, opts)
if (details) {
// Check if backend recognized the license as valid
if (details.category === 'UNKNOWN') {
errors.push(`"${spdxId}" is not a valid SPDX license identifier. Please use a valid SPDX expression (e.g., "Apache-2.0", "MIT"). See https://spdx.org/licenses/`)
} else {
Object.assign(licenseInfo, details)
}
} else {
errors.push(`No license details found for ${spdxId}`)
}
} catch (err) {
errors.push(`Failed to fetch details for ${spdxId}: ${err.message}`)
}
return licenseInfo
}
const output = {
manifestLicense: await buildLicenseInfo(localResult.fromManifest),
fileLicense: await buildLicenseInfo(localResult.fromFile),
mismatch: localResult.mismatch
}
if (errors.length > 0) {
output.errors = errors
}
console.log(JSON.stringify(output, null, 2))
}
}
const sbom = {
command: 'sbom </path/to/manifest> [--output]',
desc: 'generate a CycloneDX SBOM from a manifest file',
builder: yargs => yargs.positional(
'/path/to/manifest',
{
desc: 'manifest path for SBOM generation',
type: 'string',
normalize: true,
}
).options({
output: {
alias: 'o',
desc: 'Write SBOM JSON to a file instead of stdout',
type: 'string',
normalize: true,
},
workspaceDir: {
alias: 'w',
desc: 'Workspace root directory (for monorepos; lock file is expected here)',
type: 'string',
normalize: true,
},
name: {
alias: 'n',
desc: 'Root component name for the SBOM (overrides the manifest name field)',
type: 'string',
},
}),
handler: async args => {
let manifest = args['/path/to/manifest']
const opts = args.workspaceDir ? { TRUSTIFY_DA_WORKSPACE_DIR: args.workspaceDir } : {}
if (args.name) {
opts.TRUSTIFY_DA_SBOM_NAME = args.name
}
let result
try {
result = await generateSbom(manifest, opts)
} catch (err) {
console.error(JSON.stringify({ error: `Failed to generate SBOM: ${err.message}` }, null, 2))
process.exit(1)
}
const json = JSON.stringify(result, null, 2)
if (args.output) {
try {
fs.writeFileSync(args.output, json)
} catch (err) {
console.error(JSON.stringify({ error: `Failed to write output file: ${err.message}` }, null, 2))
process.exit(1)
}
} else {
console.log(json)
}
}
}
const remediate = {
command: 'remediate <path>',
desc: 'Scan and apply vulnerability remediations to manifest files',
builder: yargs => yargs.positional(
'path',
{
desc: 'Path to manifest file or directory',
type: 'string',
normalize: true,
}
).options({
'dry-run': {
alias: 'd',
type: 'boolean',
desc: 'Preview changes without modifying files',
},
providers: {
desc: 'Comma-separated list of vulnerability providers (env: TRUSTIFY_DA_PROVIDERS)',
type: 'string',
},
sources: {
desc: 'Comma-separated list of vulnerability sources (env: TRUSTIFY_DA_SOURCES)',
type: 'string',
},
'group-by': {
type: 'string',
choices: ['dependency', 'bundle'],
desc: 'Report grouping strategy (default: dependency)',
},
exclude: {
desc: 'Version-less purl glob to exclude from remediation, e.g. pkg:maven/com.example/legacy-lib. Supports globs: * within a segment (pkg:maven/com.example/* for a group), ** across segments (pkg:maven/** for an ecosystem). Repeat flag per entry.',
type: 'string',
array: true,
},
backendUrl: {
desc: 'Trustify DA backend URL (env: TRUSTIFY_DA_BACKEND_URL)',
type: 'string',
},
}).middleware(configMiddleware('path', { groupBy: true })),
handler: async args => {
try {
const result = await runRemediation(args.path, {
dryRun: args['dry-run'],
providers: args.providers,
sources: args.sources,
backendUrl: args.backendUrl,
exclude: Array.isArray(args.exclude)
? args.exclude.filter(p => p != null && String(p).trim())
: [],
})
if (result.remediations.length === 0 && result.manifests.length === 0) {
console.log('No supported manifest files found.')
process.exit(result.exitCode)
}
for (const s of result.skipped) {
console.warn(`Warning: skipped ${s.groupId}:${s.artifactId} → ${s.newVersion}: ${s.reason}`)
}
if (!args['dry-run'] && result.appliedFiles.length > 0) {
console.log(`Updated ${result.appliedFiles.length} file(s):`)
for (const file of result.appliedFiles) {
console.log(` ${file}`)
}
console.log('')
}
console.log(generateReport(result.remediations, { groupBy: args['group-by'], dryRun: args['dry-run'] }))
process.exit(result.exitCode)
} catch (err) {
console.error(err.message)
process.exit(1)
}
}
}
// parse and invoke the command
yargs(hideBin(process.argv))
.usage(`Usage: ${process.argv[0].includes("node") ? path.parse(process.argv[1]).base : path.parse(process.argv[0]).base} {component|stack|stack-batch|image|validate-token|license|sbom|remediate}`)
.command(stack)
.command(stackBatch)
.command(component)
.command(image)
.command(validateToken)
.command(license)
.command(sbom)
.command(remediate)
.scriptName('')
.version(false)
.demandCommand(1)
.wrap(null)
.parse()