forked from CycloneDX/cdxgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
215 lines (199 loc) · 5.49 KB
/
server.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
import { spawnSync } from "node:child_process";
import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import process from "node:process";
import url from "node:url";
import bodyParser from "body-parser";
import connect from "connect";
import { createBom, submitBom } from "./index.js";
import { postProcess } from "./postgen.js";
import compression from "compression";
// Timeout milliseconds. Default 10 mins
const TIMEOUT_MS =
Number.parseInt(process.env.CDXGEN_SERVER_TIMEOUT_MS) || 10 * 60 * 1000;
const app = connect();
app.use(
bodyParser.json({
deflate: true,
limit: "1mb",
}),
);
app.use(compression());
const gitClone = (repoUrl, branch = null) => {
const tempDir = fs.mkdtempSync(
path.join(os.tmpdir(), path.basename(repoUrl)),
);
if (branch == null) {
console.log("Cloning Repo", "to", tempDir);
const result = spawnSync(
"git",
["clone", repoUrl, "--depth", "1", tempDir],
{
encoding: "utf-8",
shell: false,
},
);
if (result.status !== 0 || result.error) {
console.log(result.error);
}
} else {
console.log("Cloning repo with optional branch", "to", tempDir);
const result = spawnSync(
"git",
["clone", repoUrl, "--branch", branch, "--depth", "1", tempDir],
{
encoding: "utf-8",
shell: false,
},
);
if (result.status !== 0 || result.error) {
console.log(result.error);
}
}
return tempDir;
};
const parseQueryString = (q, body, options = {}) => {
if (body && Object.keys(body).length) {
options = Object.assign(options, body);
}
const queryParams = [
"type",
"multiProject",
"requiredOnly",
"noBabel",
"installDeps",
"projectId",
"projectName",
"projectGroup",
"projectVersion",
"parentUUID",
"serverUrl",
"apiKey",
"specVersion",
"filter",
"only",
"autoCompositions",
"gitBranch",
"lifecycle",
"deep",
"profile",
"exclude",
"includeFormulation",
"includeCrypto",
"standard",
];
for (const param of queryParams) {
if (q[param]) {
let value = q[param];
// Convert string to boolean
if (value === "true") {
value = true;
} else if (value === "false") {
value = false;
}
options[param] = value;
}
}
options.projectType = options.type?.split(",");
delete options.type;
if (options.lifecycle === "pre-build") {
options.installDeps = false;
}
if (options.profile) {
applyProfileOptions(options);
}
return options;
};
const applyProfileOptions = (options) => {
switch (options.profile) {
case "appsec":
options.deep = true;
break;
case "research":
options.deep = true;
options.evidence = true;
options.includeCrypto = true;
break;
default:
break;
}
};
const configureServer = (cdxgenServer) => {
cdxgenServer.headersTimeout = TIMEOUT_MS;
cdxgenServer.requestTimeout = TIMEOUT_MS;
cdxgenServer.timeout = 0;
cdxgenServer.keepAliveTimeout = 0;
};
const start = (options) => {
console.log("Listening on", options.serverHost, options.serverPort);
const cdxgenServer = http
.createServer(app)
.listen(options.serverPort, options.serverHost);
configureServer(cdxgenServer);
app.use("/health", (_req, res) => {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ status: "OK" }, null, 2));
});
app.use("/sbom", async (req, res) => {
const q = url.parse(req.url, true).query;
let cleanup = false;
const reqOptions = parseQueryString(
q,
req.body,
Object.assign({}, options),
);
const filePath = q.path || q.url || req.body.path || req.body.url;
if (!filePath) {
res.writeHead(500, { "Content-Type": "application/json" });
return res.end(
JSON.stringify({
error: "path or url is required.",
}),
);
}
let srcDir = filePath;
if (filePath.startsWith("http") || filePath.startsWith("git")) {
srcDir = gitClone(filePath, reqOptions.gitBranch);
cleanup = true;
}
console.log("Generating SBOM for", srcDir);
let bomNSData = (await createBom(srcDir, reqOptions)) || {};
bomNSData = postProcess(bomNSData, reqOptions);
if (reqOptions.serverUrl && reqOptions.apiKey) {
console.log(
`Publishing SBOM ${reqOptions.projectName} to Dependency Track`,
reqOptions.serverUrl,
);
const response = await submitBom(reqOptions, bomNSData.bomJson);
const errorMessages = response?.errors;
if (errorMessages) {
res.writeHead(500, { "Content-Type": "application/json" });
return res.end(
JSON.stringify({
error: `Unable to submit the SBOM ${reqOptions.projectName} to the Dependency Track server ${reqOptions.serverUrl}`,
details: errorMessages,
}),
);
}
}
res.writeHead(200, { "Content-Type": "application/json" });
if (bomNSData.bomJson) {
if (
typeof bomNSData.bomJson === "string" ||
bomNSData.bomJson instanceof String
) {
res.write(bomNSData.bomJson);
} else {
res.write(JSON.stringify(bomNSData.bomJson, null, null));
}
}
res.end("\n");
if (cleanup && srcDir && srcDir.startsWith(os.tmpdir()) && fs.rmSync) {
console.log(`Cleaning up ${srcDir}`);
fs.rmSync(srcDir, { recursive: true, force: true });
}
});
};
export { configureServer, start };