forked from CycloneDX/cdxgen
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
1811 lines (1760 loc) · 53 KB
/
index.js
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const readInstalled = require("read-installed");
const parsePackageJsonName = require("parse-packagejson-name");
const os = require("os");
const pathLib = require("path");
const request = require("request");
const ssri = require("ssri");
const fs = require("fs");
const { v4: uuidv4 } = require("uuid");
const { PackageURL } = require("packageurl-js");
const builder = require("xmlbuilder");
const utils = require("./utils");
const sbtUtils = require("./sbt-utils");
const { spawnSync } = require("child_process");
const selfPjson = require("./package.json");
const { findJSImports } = require("./analyzer");
const semver = require("semver");
const { option } = require("yargs");
const nodeCleanup = require('node-cleanup');
const resourcesManager = utils.resourcesManager();
nodeCleanup(resourcesManager.cleanUp);
// Construct maven command
let MVN_CMD = "mvn";
if (process.env.MVN_CMD) {
MVN_CMD = process.env.MVN_CMD;
} else if (process.env.MAVEN_HOME) {
MVN_CMD = pathLib.join(process.env.MAVEN_HOME, "bin", "mvn");
}
// Construct gradle cache directory
let GRADLE_CACHE_DIR =
process.env.GRADLE_CACHE_DIR ||
pathLib.join(os.homedir(), ".gradle", "caches", "modules-2", "files-2.1");
if (process.env.GRADLE_USER_HOME) {
GRADLE_CACHE_DIR =
process.env.GRADLE_USER_HOME + "/caches/modules-2/files-2.1";
}
// Construct sbt cache directory
let SBT_CACHE_DIR =
process.env.SBT_CACHE_DIR || pathLib.join(os.homedir(), ".ivy2", "cache");
// Debug mode flag
const DEBUG_MODE =
process.env.SCAN_DEBUG_MODE === "debug" ||
process.env.SHIFTLEFT_LOGGING_LEVEL === "debug" ||
process.env.NODE_ENV !== "production";
// CycloneDX Hash pattern
const HASH_PATTERN =
"^([a-fA-F0-9]{32}|[a-fA-F0-9]{40}|[a-fA-F0-9]{64}|[a-fA-F0-9]{96}|[a-fA-F0-9]{128})$";
// Timeout milliseconds. Default 10 mins
const TIMEOUT_MS = process.env.CDXGEN_TIMEOUT_MS || 10 * 60 * 1000;
/**
* Method to create global external references
*
* @param pkg
* @returns {Array}
*/
function addGlobalReferences(src, filename) {
let externalReferences = [];
externalReferences.push({
reference: { "@type": "other", url: src, comment: "Base path" },
});
let packageFileMeta = filename;
if (!filename.includes(src)) {
packageFileMeta = pathLib.join(src, filename);
}
externalReferences.push({
reference: {
"@type": "other",
url: packageFileMeta,
comment: "Package file",
},
});
return externalReferences;
}
/**
* Function to create metadata block
*
*/
function addMetadata(deterministicForTests) {
let now = deterministicForTests ? '2022-06-03T09:34:10.062Z' : new Date().toISOString();
let metadata = {
timestamp: now,
tools: [
{
tool: {
vendor: "AppThreat",
name: "cdxgen",
version: selfPjson.version,
},
},
],
authors: [
{
author: { name: selfPjson.author, email: "cloud@appthreat.com" },
},
],
supplier: undefined,
};
return metadata;
}
/**
* Method to create external references
*
* @param pkg
* @returns {Array}
*/
function addExternalReferences(pkg, format = "xml") {
let externalReferences = [];
if (format === "xml") {
if (pkg.homepage) {
externalReferences.push({
reference: { "@type": "website", url: pkg.homepage },
});
}
if (pkg.bugs && pkg.bugs.url) {
externalReferences.push({
reference: { "@type": "issue-tracker", url: pkg.bugs.url },
});
}
if (pkg.repository && pkg.repository.url) {
externalReferences.push({
reference: { "@type": "vcs", url: pkg.repository.url },
});
}
} else {
if (pkg.homepage) {
externalReferences.push({
type: "website",
url: pkg.homepage,
});
}
if (pkg.bugs && pkg.bugs.url) {
externalReferences.push({
type: "issue-tracker",
url: pkg.bugs.url,
});
}
if (pkg.repository && pkg.repository.url) {
externalReferences.push({
type: "vcs",
url: pkg.repository.url,
});
}
}
return externalReferences;
}
/**
* For all modules in the specified package, creates a list of
* component objects from each one.
*/
exports.listComponents = listComponents;
function listComponents(allImports, pkg, ptype = "npm", format = "xml") {
let list = {};
let isRootPkg = ptype === "npm";
if (Array.isArray(pkg)) {
pkg.forEach((p) => {
addComponent(allImports, p, ptype, list, false, format);
});
} else {
addComponent(allImports, pkg, ptype, list, isRootPkg, format);
}
if (format === "xml") {
return Object.keys(list).map((k) => ({ component: list[k] }));
} else {
return Object.keys(list).map((k) => list[k]);
}
}
/**
* Given the specified package, create a CycloneDX component and add it to the list.
*/
function addComponent(
allImports,
pkg,
ptype,
list,
isRootPkg = false,
format = "xml"
) {
//read-installed with default options marks devDependencies as extraneous
//if a package is marked as extraneous, do not include it as a component
if (pkg.extraneous) return;
if (!isRootPkg) {
let pkgIdentifier = parsePackageJsonName(pkg.name);
let group = pkg.group || pkgIdentifier.scope;
// Create empty group
group = group || "";
let name = pkgIdentifier.fullName || pkg.name;
// Skip @types package for npm
if (ptype == "npm" && (group === "types" || name.startsWith("@types"))) {
return;
}
let version = pkg.version;
let licenses = utils.getLicenses(pkg, format);
let purl = new PackageURL(
ptype,
group,
name,
version,
pkg.qualifiers,
pkg.subpath
);
let purlString = purl.toString();
purlString = decodeURIComponent(purlString);
let component = {
group: group,
name: name,
version: version,
hashes: [],
licenses: licenses,
purl: purlString,
externalReferences: addExternalReferences(pkg, format),
};
let compScope = pkg.scope;
if (allImports) {
const impPkgs = Object.keys(allImports);
if (
impPkgs.includes(name) ||
impPkgs.includes(group + "/" + name) ||
impPkgs.includes("@" + group + "/" + name) ||
impPkgs.includes(group) ||
impPkgs.includes("@" + group)
) {
compScope = "required";
} else if (impPkgs.length) {
compScope = "optional";
}
}
if (compScope) {
component["scope"] = compScope;
}
if (format === "xml") {
component["@type"] = determinePackageType(pkg);
component["@bom-ref"] = purlString;
component["description"] = { "#cdata": pkg.description };
} else {
component["type"] = determinePackageType(pkg);
component["bom-ref"] = purlString;
component["description"] = pkg.description;
}
if (
component.externalReferences === undefined ||
component.externalReferences.length === 0
) {
delete component.externalReferences;
}
processHashes(pkg, component, format);
if (list[component.purl]) return; //remove cycles
list[component.purl] = component;
}
if (pkg.dependencies) {
Object.keys(pkg.dependencies)
.map((x) => pkg.dependencies[x])
.filter((x) => typeof x !== "string") //remove cycles
.map((x) => addComponent(allImports, x, ptype, list, false, format));
}
}
/**
* If the author has described the module as a 'framework', the take their
* word for it, otherwise, identify the module as a 'library'.
*/
function determinePackageType(pkg) {
if (pkg.hasOwnProperty("keywords")) {
for (let keyword of pkg.keywords) {
if (keyword.toLowerCase() === "framework") {
return "framework";
}
}
}
return "library";
}
/**
* Uses the SHA1 shasum (if present) otherwise utilizes Subresource Integrity
* of the package with support for multiple hashing algorithms.
*/
function processHashes(pkg, component, format = "xml") {
if (pkg._shasum) {
let ahash = { "@alg": "SHA-1", "#text": pkg._shasum };
if (format === "json") {
ahash = { alg: "SHA-1", content: pkg._shasum };
component.hashes.push(ahash);
} else {
component.hashes.push({
hash: ahash,
});
}
} else if (pkg._integrity) {
let integrity = ssri.parse(pkg._integrity) || {};
// Components may have multiple hashes with various lengths. Check each one
// that is supported by the CycloneDX specification.
if (integrity.hasOwnProperty("sha512")) {
addComponentHash(
"SHA-512",
integrity.sha512[0].digest,
component,
format
);
}
if (integrity.hasOwnProperty("sha384")) {
addComponentHash(
"SHA-384",
integrity.sha384[0].digest,
component,
format
);
}
if (integrity.hasOwnProperty("sha256")) {
addComponentHash(
"SHA-256",
integrity.sha256[0].digest,
component,
format
);
}
if (integrity.hasOwnProperty("sha1")) {
addComponentHash("SHA-1", integrity.sha1[0].digest, component, format);
}
}
if (component.hashes.length === 0) {
delete component.hashes; // If no hashes exist, delete the hashes node (it's optional)
}
}
/**
* Adds a hash to component.
*/
function addComponentHash(alg, digest, component, format = "xml") {
let hash = "";
// If it is a valid hash simply use it
if (new RegExp(HASH_PATTERN).test(digest)) {
hash = digest;
} else {
// Check if base64 encoded
const isBase64Encoded =
Buffer.from(digest, "base64").toString("base64") === digest;
hash = isBase64Encoded
? Buffer.from(digest, "base64").toString("hex")
: digest;
}
let ahash = { "@alg": alg, "#text": hash };
if (format === "json") {
ahash = { alg: alg, content: hash };
component.hashes.push(ahash);
} else {
component.hashes.push({ hash: ahash });
}
}
const buildBomString = (
{ deterministicForTests, pkgInfo, ptype, context },
callback
) => {
let bom = builder
.create("bom", { encoding: "utf-8", separateArrayItems: true })
.att("xmlns", "http://cyclonedx.org/schema/bom/1.2");
const serialNum = "urn:uuid:" + uuidv4();
if (!deterministicForTests) {
bom.att("serialNumber", serialNum);
}
bom.att("version", 1);
let ctxFilename = !deterministicForTests ? context.filename : '/some/full/path';
if (context && context.src && context.filename) {
bom
.ele("externalReferences")
.ele(addGlobalReferences(context.src, ctxFilename));
}
let allImports = {};
if (context && context.allImports) {
allImports = context.allImports;
}
const nsMapping = context.nsMapping || {};
const metadata = addMetadata(deterministicForTests);
bom.ele("metadata").ele(metadata);
const components = listComponents(allImports, pkgInfo, ptype, "xml");
if (components && components.length) {
bom.ele("components").ele(components);
let bomString = bom.end({
pretty: true,
indent: " ",
newline: "\n",
width: 0,
allowEmpty: false,
spacebeforeslash: "",
});
// CycloneDX 1.2 Json Template
let jsonTpl = {
bomFormat: "CycloneDX",
specVersion: "1.2",
serialNumber: serialNum,
version: 1,
metadata: metadata,
components: listComponents(allImports, pkgInfo, ptype, "json"),
};
callback(null, bomString, JSON.stringify(jsonTpl, null, 2), nsMapping);
} else {
callback();
}
};
/**
* Function to create bom string for Java projects
*
* @param deterministicForTests If true, hardcode BOM serial number and timestamp
* @param path to the project
* @param options Parse options from the cli
* @param callback Function callback
*/
const createJavaBom = async (
deterministicForTests,
path,
options,
callback
) => {
let jarNSMapping = {};
let pkgList = [];
// war/ear mode
if (path.endsWith(".war")) {
// Check if the file exists
if (fs.existsSync(path)) {
utils.debug(`Retrieving packages from ${path}`);
let tempDir = fs.mkdtempSync(pathLib.join(os.tmpdir(), "war-deps-"));
try {
pkgList = utils.extractJarArchive(path, tempDir);
if (pkgList.length) {
pkgList = await utils.getMvnMetadata(pkgList);
}
// Should we attempt to resolve class names
if (options.resolveClass) {
console.log(
"Creating class names list based on available jars. This might take a few mins ..."
);
jarNSMapping = utils.collectJarNS(tempDir);
}
} finally {
// Clean up
if (tempDir && tempDir.startsWith(os.tmpdir())) {
console.log(`Cleaning up ${tempDir}`);
fs.rmdirSync(tempDir, { recursive: true });
}
}
} else {
console.log(`${path} doesn't exist`);
}
buildBomString(
{
deterministicForTests,
pkgInfo: pkgList,
ptype: "maven",
context: {
src: pathLib.dirname(path),
filename: path,
nsMapping: jarNSMapping,
},
},
callback
);
} else {
// maven - pom.xml
const pomFiles = utils.getAllFiles(path, "pom.xml");
if (pomFiles && pomFiles.length) {
let mvnArgs = [
"org.cyclonedx:cyclonedx-maven-plugin:2.4.0:makeAggregateBom",
];
// Support for passing additional settings and profile to maven
if (process.env.MVN_ARGS) {
const addArgs = process.env.MVN_ARGS.split(" ");
mvnArgs = mvnArgs.concat(addArgs);
}
for (let i in pomFiles) {
const f = pomFiles[i];
const basePath = pathLib.dirname(f);
// Should we attempt to resolve class names
if (options.resolveClass) {
console.log(
"Creating class names list based on available jars. This might take a few mins ..."
);
jarNSMapping = utils.collectMvnDependencies(MVN_CMD, basePath);
}
console.log(`Executing '${MVN_CMD} ${mvnArgs.join(" ")}' in`, basePath);
result = spawnSync(MVN_CMD, mvnArgs, {
cwd: basePath,
shell: true,
encoding: "utf-8",
timeout: TIMEOUT_MS,
});
if (result.status == 1 || result.error) {
let tempDir = fs.mkdtempSync(pathLib.join(os.tmpdir(), "cdxmvn-"));
try {
let tempMvnTree = pathLib.join(tempDir, "mvn-tree.txt");
let mvnTreeArgs = ["dependency:tree", "-DoutputFile=" + tempMvnTree];
if (process.env.MVN_ARGS) {
const addArgs = process.env.MVN_ARGS.split(" ");
mvnTreeArgs = mvnTreeArgs.concat(addArgs);
}
console.log(
`Fallback to executing ${MVN_CMD} ${mvnTreeArgs.join(" ")}`
);
result = spawnSync(MVN_CMD, mvnTreeArgs, {
cwd: basePath,
shell: true,
encoding: "utf-8",
timeout: TIMEOUT_MS,
});
if (result.status == 1 || result.error) {
console.error(result.stdout, result.stderr);
console.log(
"Resolve the above maven error. This could be due to the following:\n"
);
console.log(
"1. Java version requirement - Scan or the CI build agent could be using an incompatible version"
);
console.log(
"2. Private maven repository is not serving all the required maven plugins correctly. Refer to your registry documentation to add support for jitpack.io"
);
console.log(
"3. Check if all required environment variables including any maven profile arguments are passed correctly to this tool"
);
console.log(
"\nFalling back to manual pom.xml parsing. The result would be incomplete!"
);
const dlist = utils.parsePom(f);
if (dlist && dlist.length) {
pkgList = pkgList.concat(dlist);
}
} else {
if (fs.existsSync(tempMvnTree)) {
const mvnTreeString = fs.readFileSync(tempMvnTree, {
encoding: "utf-8",
});
const dlist = utils.parseMavenTree(mvnTreeString);
if (dlist && dlist.length) {
pkgList = pkgList.concat(dlist);
}
fs.unlinkSync(tempMvnTree);
}
}
} finally {
// Clean up
if (tempDir && tempDir.startsWith(os.tmpdir())) {
console.log(`Cleaning up ${tempDir}`);
fs.rmdirSync(tempDir, { recursive: true });
}
}
pkgList = await utils.getMvnMetadata(pkgList);
options.accessSync;
return buildBomString(
{
deterministicForTests,
pkgInfo: pkgList,
ptype: "maven",
context: {
src: path,
filename: "pom.xml",
nsMapping: jarNSMapping,
},
},
callback
);
}
} // for
const firstPath = pathLib.dirname(pomFiles[0]);
if (fs.existsSync(pathLib.join(firstPath, "target", "bom.xml"))) {
const bomString = fs.readFileSync(
pathLib.join(firstPath, "target", "bom.xml"),
{ encoding: "utf-8" }
);
let bomJonString = "";
if (fs.existsSync(pathLib.join(firstPath, "target", "bom.json"))) {
bomJonString = fs.readFileSync(
pathLib.join(firstPath, "target", "bom.json"),
{ encoding: "utf-8" }
);
}
callback(null, bomString, bomJonString, jarNSMapping);
} else {
const bomFiles = utils.getAllFiles(path, "bom.xml");
const bomJsonFiles = utils.getAllFiles(path, "bom.json");
callback(null, bomFiles, bomJsonFiles, jarNSMapping);
}
}
// gradle
let gradleFiles = utils.getAllFiles(
path,
(options.multiProject ? "**/" : "") + "build.gradle*"
);
if (gradleFiles && gradleFiles.length) {
let GRADLE_CMD = "gradle";
if (process.env.GRADLE_HOME) {
GRADLE_CMD = pathLib.join(process.env.GRADLE_HOME, "bin", "gradle");
}
// Use local gradle wrapper if available
if (fs.existsSync(path, "gradlew")) {
// Enable execute permission
try {
fs.chmodSync(pathLib.join(path, "gradlew"), 0o775);
} catch (e) {}
GRADLE_CMD = pathLib.join(path, "gradlew");
}
// Support for multi-project applications
if (process.env.GRADLE_MULTI_PROJECT_MODE) {
console.log("Executing", GRADLE_CMD, "projects in", path);
const result = spawnSync(
GRADLE_CMD,
["projects", "-q", "--console", "plain"],
{ cwd: path, encoding: "utf-8", timeout: TIMEOUT_MS }
);
if (result.status == 1 || result.error) {
console.error(result.stdout, result.stderr);
if (DEBUG_MODE) {
console.log(
"1. Check if the correct version of java and gradle are installed and available in PATH. For example, some project might require Java 11 with gradle 7."
);
}
}
const stdout = result.stdout;
if (stdout) {
const cmdOutput = Buffer.from(stdout).toString();
const allProjects = utils.parseGradleProjects(cmdOutput);
if (!allProjects) {
console.log(
"No projects found. Is this a gradle multi-project application?"
);
} else {
console.log("Found", allProjects.length, "gradle sub-projects");
for (let sp of allProjects) {
console.log(
"Executing",
GRADLE_CMD,
sp + ":dependencies in",
path
);
const sresult = spawnSync(
GRADLE_CMD,
[sp + ":dependencies", "-q", "--console", "plain"],
{ cwd: path, encoding: "utf-8", timeout: TIMEOUT_MS }
);
if (sresult.status == 1 || sresult.error) {
if (DEBUG_MODE) {
console.error(sresult.stdout, sresult.stderr);
}
}
const sstdout = sresult.stdout;
if (sstdout) {
const cmdOutput = Buffer.from(sstdout).toString();
const dlist = utils.parseGradleDep(cmdOutput);
if (dlist && dlist.length) {
if (DEBUG_MODE) {
console.log(
"Found",
dlist.length,
"packages in gradle project",
sp
);
}
pkgList = pkgList.concat(dlist);
} else {
if (DEBUG_MODE) {
console.log("No packages were found in gradle project", sp);
}
}
}
}
if (pkgList.length) {
console.log(
"Obtained",
pkgList.length,
"from this gradle multi-project"
);
} else {
console.log(
"No packages found. Unset the environment variable GRADLE_MULTI_PROJECT_MODE and try again."
);
}
}
}
} else {
for (let i in gradleFiles) {
const f = gradleFiles[i];
const basePath = pathLib.dirname(f);
console.log("Executing", GRADLE_CMD, "dependencies in", basePath);
const result = spawnSync(
GRADLE_CMD,
["dependencies", "-q", "--console", "plain"],
{ cwd: basePath, encoding: "utf-8", timeout: TIMEOUT_MS }
);
if (result.status == 1 || result.error) {
console.error(result.stdout, result.stderr);
if (DEBUG_MODE) {
console.log(
"1. Check if the correct version of java and gradle are installed and available in PATH. For example, some project might require Java 11 with gradle 7."
);
}
}
const stdout = result.stdout;
if (stdout) {
const cmdOutput = Buffer.from(stdout).toString();
const dlist = utils.parseGradleDep(cmdOutput);
if (dlist && dlist.length) {
pkgList = pkgList.concat(dlist);
} else {
if (DEBUG_MODE) {
console.log(
"No packages were detected. If this is a multi-project gradle application set the environment variable GRADLE_MULTI_PROJECT_MODE to true and try again."
);
}
}
}
}
}
pkgList = await utils.getMvnMetadata(pkgList);
// Should we attempt to resolve class names
if (options.resolveClass) {
console.log(
"Creating class names list based on available jars. This might take a few mins ..."
);
jarNSMapping = utils.collectJarNS(GRADLE_CACHE_DIR);
}
buildBomString(
{
deterministicForTests,
pkgInfo: pkgList,
ptype: "maven",
context: {
src: path,
filename: "build.gradle",
nsMapping: jarNSMapping,
},
},
callback
);
}
// scala sbt
// Identify sbt projects via its `project` directory:
// - all SBT project _should_ define build.properties file with sbt version info
// - SBT projects _typically_ have some configs/plugins defined in .sbt files
// - SBT projects that are still on 0.13.x, can still use the old approach,
// where configs are defined via Scala files
// Detecting one of those should be enough to determine an SBT project.
let sbtProjectFiles = utils.getAllFiles(
path,
(options.multiProject ? "**/" : "") + "project/{build.properties,*.sbt,*.scala}"
);
let sbtProjects = [];
for (let i in sbtProjectFiles) {
// parent dir of sbtProjectFile is the `project` directory
// parent dir of `project` is the sbt root project directory
const baseDir = pathLib.dirname(pathLib.dirname(sbtProjectFiles[i]));
sbtProjects = sbtProjects.concat(baseDir)
}
// Fallback in case sbt's project directory is non-existent
if (!sbtProjects.length) {
sbtProjectFiles = utils.getAllFiles(
path,
(options.multiProject ? "**/" : "") + "*.sbt"
);
for (let i in sbtProjectFiles) {
const baseDir = pathLib.dirname(sbtProjectFiles[i]);
sbtProjects = sbtProjects.concat(baseDir)
}
}
sbtProjects = [...new Set(sbtProjects)] // eliminate duplicates
let sbtLockFiles = utils.getAllFiles(
path,
(options.multiProject ? "**/" : "") + "build.sbt.lock"
);
if (sbtProjects && sbtProjects.length) {
let pkgList = [];
// If the project use sbt lock files
if (sbtLockFiles && sbtLockFiles.length) {
for (let i in sbtLockFiles) {
const f = sbtLockFiles[i];
const dlist = sbtUtils.parseSbtLock(f);
if (dlist && dlist.length) {
pkgList = pkgList.concat(dlist);
}
}
} else {
const sbtInvoker = sbtUtils.sbtInvoker(DEBUG_MODE, path, resourcesManager);
for (let i in sbtProjects) {
const basePath = sbtProjects[i];
const commandPrefix = options.subprojectName ? `${options.subprojectName}/` : "";
const cmdOutput = sbtInvoker.invokeDependencyList(commandPrefix, basePath, TIMEOUT_MS);
if (cmdOutput != '') {
utils.debug(`sbt dependencyList result read from: ${cmdOutput}`);
const dlist = sbtUtils.parseKVDep(cmdOutput);
pkgList = pkgList.concat(dlist);
} else {
utils.debug(`sbt dependencyList did not yield any result`);
}
}
} // else
if (DEBUG_MODE) {
console.log(`Found ${pkgList.length} packages`);
}
pkgList = await utils.getMvnMetadata(pkgList);
// Should we attempt to resolve class names
if (options.resolveClass) {
console.log(
"Creating class names list based on available jars. This might take a few mins ..."
);
jarNSMapping = utils.collectJarNS(SBT_CACHE_DIR);
}
// TODO: Should we sort for other langs / build tools as well?
pkgList = utils.sortPkgs(pkgList);
buildBomString(
{
deterministicForTests,
pkgInfo: pkgList,
ptype: "maven",
context: {
src: path,
filename: sbtProjects.join(", "),
nsMapping: jarNSMapping,
},
},
callback
);
}
}
};
/**
* Function to create bom string for Node.js projects
*
* @param deterministicForTests If true, hardcode BOM serial number and timestamp
* @param path to the project
* @param options Parse options from the cli
* @param callback Function callback
*/
const createNodejsBom = async (
deterministicForTests,
path,
options,
callback
) => {
const yarnLockFiles = utils.getAllFiles(
path,
(options.multiProject ? "**/" : "") + "yarn.lock"
);
const pkgLockFiles = utils.getAllFiles(
path,
(options.multiProject ? "**/" : "") + "package-lock.json"
);
const pnpmLockFiles = utils.getAllFiles(
path,
(options.multiProject ? "**/" : "") + "pnpm-lock.yaml"
);
const { allImports } = await findJSImports(path);
if (pnpmLockFiles && pnpmLockFiles.length) {
let pkgList = [];
for (let i in pnpmLockFiles) {
const f = pnpmLockFiles[i];
const dlist = utils.parsePnpmLock(f);
if (dlist && dlist.length) {
pkgList = pkgList.concat(dlist);
}
}
return buildBomString(
{
deterministicForTests,
pkgInfo: pkgList,
ptype: "npm",
context: { allImports, src: path, filename: "pnpm-lock.yaml" },
},
callback
);
} else if (pkgLockFiles && pkgLockFiles.length) {
let pkgList = [];
for (let i in pkgLockFiles) {
const f = pkgLockFiles[i];
// Parse package-lock.json if available
const dlist = await utils.parsePkgLock(f);
if (dlist && dlist.length) {
pkgList = pkgList.concat(dlist);
}
}
return buildBomString(
{
deterministicForTests,
pkgInfo: pkgList,
ptype: "npm",
context: { allImports, src: path, filename: "package-lock.json" },
},
callback
);
} else if (fs.existsSync(pathLib.join(path, "node_modules"))) {
readInstalled(path, options, (err, pkgInfo) => {
buildBomString(
{
deterministicForTests,
pkgInfo,
ptype: "npm",
context: { allImports, src: path, filename: "package.json" },
},
callback
);
});
} else if (fs.existsSync(pathLib.join(path, "rush.json"))) {
// Rush.js creates node_modules inside common/temp directory
const nmDir = pathLib.join(path, "common", "temp", "node_modules");
// Do rush install if we don't have node_modules directory
if (!fs.existsSync(nmDir)) {
console.log("Executing 'rush install --no-link'", path);
result = spawnSync("rush", ["install", "--no-link", "--bypass-policy"], {
cwd: path,
encoding: "utf-8",
});
}
// Look for shrinkwrap file
const swFile = pathLib.join(
path,
"tools",
"build-tasks",
".rush",
"temp",
"shrinkwrap-deps.json"
);
const pnpmLock = pathLib.join(
path,
"common",
"config",
"rush",
"pnpm-lock.yaml"
);
if (fs.existsSync(swFile)) {
const pkgList = await utils.parseNodeShrinkwrap(swFile);
return buildBomString(
{
deterministicForTests,
pkgInfo: pkgList,
ptype: "npm",
context: { allImports, src: path, filename: "shrinkwrap-deps.json" },
},
callback
);
} else if (fs.existsSync(pnpmLock)) {
const pkgList = await utils.parsePnpmLock(pnpmLock);
return buildBomString(
{
deterministicForTests,
pkgInfo: pkgList,
ptype: "npm",
context: { allImports, src: path, filename: "pnpm-lock.yaml" },
},
callback
);
} else {
console.log(
"Neither shrinkwrap file: ",
swFile,
" nor pnpm lockfile",
pnpmLock,
"was found!"
);
}
} else if (yarnLockFiles && yarnLockFiles.length) {
let pkgList = [];
for (let i in yarnLockFiles) {
const f = yarnLockFiles[i];
// Parse yarn.lock if available. This check is after rush.json since
// rush.js could include yarn.lock :(
const dlist = await utils.parseYarnLock(f);
if (dlist && dlist.length) {
pkgList = pkgList.concat(dlist);
}
}
return buildBomString(
{
deterministicForTests,
pkgInfo: pkgList,
ptype: "npm",
context: { allImports, src: path, filename: "yarn.lock" },
},
callback
);