forked from guacsec/trustify-da-javascript-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalysis.js
More file actions
264 lines (237 loc) · 10.4 KB
/
analysis.js
File metadata and controls
264 lines (237 loc) · 10.4 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
import fs from "node:fs";
import path from "node:path";
import { EOL } from "os";
import { runLicenseCheck } from "./license/index.js";
import { generateImageSBOM, parseImageRef } from "./oci_image/utils.js";
import { addProxyAgent, getCustom, getTokenHeaders , TRUSTIFY_DA_OPERATION_TYPE_HEADER, TRUSTIFY_DA_PACKAGE_MANAGER_HEADER } from "./tools.js";
/** Media type for CycloneDX JSON batch payloads (batch-analysis API). */
export const CYCLONEDX_JSON_MEDIA_TYPE = 'application/vnd.cyclonedx+json'
export default { requestComponent, requestStack, requestStackBatch, requestImages, validateToken }
/**
* Send a stack analysis request and get the report as 'text/html' or 'application/json'.
* @param {import('./provider').Provider} provider - the provided data for constructing the request
* @param {string} manifest - path for the manifest
* @param {string} url - the backend url to send the request to
* @param {boolean} [html=false] - true will return 'text/html', false will return 'application/json'
* @param {import("index.js").Options} [opts={}] - optional various options to pass along the application
* @returns {Promise<string|import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>}
*/
async function requestStack(provider, manifest, url, html = false, opts = {}) {
opts["source-manifest"] = Buffer.from(fs.readFileSync(manifest).toString()).toString('base64')
opts["manifest-type"] = path.parse(manifest).base
let provided = await provider.provideStack(manifest, opts) // throws error if content providing failed
opts["source-manifest"] = ""
opts[TRUSTIFY_DA_OPERATION_TYPE_HEADER.toUpperCase().replaceAll("-", "_")] = "stack-analysis"
let startTime = new Date()
let endTime
if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
console.log("Starting time of sending stack analysis request to the dependency analytics server= " + startTime)
}
opts[TRUSTIFY_DA_PACKAGE_MANAGER_HEADER.toUpperCase().replaceAll("-", "_")] = provided.ecosystem
const fetchOptions = addProxyAgent({
method: 'POST',
headers: {
'Accept': html ? 'text/html' : 'application/json',
'Content-Type': provided.contentType,
...getTokenHeaders(opts),
},
body: provided.content
}, opts);
const finalUrl = new URL(`${url}/api/v5/analysis`);
if (opts['TRUSTIFY_DA_RECOMMENDATIONS_ENABLED'] === 'false') {
finalUrl.searchParams.append('recommend', 'false');
}
let resp = await fetch(finalUrl, fetchOptions)
let result
if (resp.status === 200) {
if (!html) {
result = await resp.json()
} else {
result = await resp.text()
}
if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
let exRequestId = resp.headers.get("ex-request-id");
if (exRequestId) {
console.log("Unique Identifier associated with this request - ex-request-id=" + exRequestId)
}
endTime = new Date()
console.log("Response body received from Trustify DA backend server : " + EOL + EOL)
console.log(console.log(JSON.stringify(result, null, 4)))
console.log("Ending time of sending stack analysis request to Trustify DA backend server= " + endTime)
let time = (endTime - startTime) / 1000
console.log("Total Time in seconds: " + time)
}
} else {
throw new Error(`Got error response from Trustify DA backend - http return code : ${resp.status}, error message => ${await resp.text()}`)
}
return Promise.resolve(result)
}
/**
* Send a component analysis request and get the report as 'application/json'.
* @param {import('./provider').Provider} provider - the provided data for constructing the request
* @param {string} manifest - path for the manifest
* @param {string} url - the backend url to send the request to
* @param {import("index.js").Options} [opts={}] - optional various options to pass along the application
* @returns {Promise<import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>}
*/
async function requestComponent(provider, manifest, url, opts = {}) {
opts["source-manifest"] = Buffer.from(fs.readFileSync(manifest).toString()).toString('base64')
let provided = await provider.provideComponent(manifest, opts) // throws error if content providing failed
opts["source-manifest"] = ""
opts[TRUSTIFY_DA_OPERATION_TYPE_HEADER.toUpperCase().replaceAll("-", "_")] = "component-analysis"
if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
console.log("Starting time of sending component analysis request to Trustify DA backend server= " + new Date())
}
opts[TRUSTIFY_DA_PACKAGE_MANAGER_HEADER.toUpperCase().replaceAll("-", "_")] = provided.ecosystem
const fetchOptions = addProxyAgent({
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': provided.contentType,
...getTokenHeaders(opts),
},
body: provided.content
}, opts);
const finalUrl = new URL(`${url}/api/v5/analysis`);
if (opts['TRUSTIFY_DA_RECOMMENDATIONS_ENABLED'] === 'false') {
finalUrl.searchParams.append('recommend', 'false');
}
let resp = await fetch(finalUrl, fetchOptions)
let result
if (resp.status === 200) {
result = await resp.json()
if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
let exRequestId = resp.headers.get("ex-request-id");
if (exRequestId) {
console.log("Unique Identifier associated with this request - ex-request-id=" + exRequestId)
}
console.log("Response body received from Trustify DA backend server : " + EOL + EOL)
console.log(JSON.stringify(result, null, 4))
console.log("Ending time of sending component analysis request to Trustify DA backend server= " + new Date())
}
const licenseCheckEnabled = getCustom('TRUSTIFY_DA_LICENSE_CHECK', 'true', opts) !== 'false' && opts.licenseCheck !== false
if (licenseCheckEnabled) {
try {
result.licenseSummary = await runLicenseCheck(provided.content, manifest, url, opts, result)
} catch (licenseErr) {
result.licenseSummary = { error: licenseErr.message }
}
}
} else {
throw new Error(`Got error response from Trustify DA backend - http return code : ${resp.status}, ex-request-id: ${resp.headers.get("ex-request-id")} error message => ${await resp.text()}`)
}
return Promise.resolve(result)
}
/**
* Send a batch stack analysis request for multiple manifests (SBOMs keyed by purl).
* @param {Object.<string, object>} sbomByPurl - Map of root purl to CycloneDX SBOM object
* @param {string} url - the backend url
* @param {boolean} [html=false] - true returns HTML, false returns JSON
* @param {import("index.js").Options} [opts={}]
* @returns {Promise<string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>>}
*/
async function requestStackBatch(sbomByPurl, url, html = false, opts = {}) {
const finalUrl = new URL(`${url}/api/v5/batch-analysis`)
if (opts['TRUSTIFY_DA_RECOMMENDATIONS_ENABLED'] === 'false') {
finalUrl.searchParams.append('recommend', 'false')
}
const fetchOptions = addProxyAgent({
method: 'POST',
headers: {
'Accept': html ? 'text/html' : 'application/json',
'Content-Type': CYCLONEDX_JSON_MEDIA_TYPE,
...getTokenHeaders(opts)
},
body: JSON.stringify(sbomByPurl)
}, opts)
const resp = await fetch(finalUrl, fetchOptions)
if (resp.status === 200) {
let result
if (!html) {
result = await resp.json()
} else {
result = await resp.text()
}
if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
const exRequestId = resp.headers.get("ex-request-id")
if (exRequestId) {
console.log("Unique Identifier associated with this request - ex-request-id=" + exRequestId)
}
console.log("Response body received from Trustify DA backend server : " + EOL + EOL)
console.log(JSON.stringify(result, null, 4))
console.log("Ending time of sending batch stack analysis request to Trustify DA backend server= " + new Date())
}
return result
} else {
throw new Error(`Got error response from Trustify DA backend - http return code : ${resp.status}, ex-request-id: ${resp.headers.get("ex-request-id")} error message => ${await resp.text()}`)
}
}
/**
*
* @param {Array<string>} imageRefs
* @param {string} url
* @param {import("index.js").Options} [opts={}] - optional various options to pass along the application
* @returns {Promise<string|Object.<string, import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport>>}
*/
async function requestImages(imageRefs, url, html = false, opts = {}) {
const imageSboms = {}
for (const image of imageRefs) {
const parsedImageRef = parseImageRef(image, opts)
imageSboms[parsedImageRef.getPackageURL().toString()] = generateImageSBOM(parsedImageRef, opts)
}
const finalUrl = new URL(`${url}/api/v5/batch-analysis`);
if (opts['TRUSTIFY_DA_RECOMMENDATIONS_ENABLED'] === 'false') {
finalUrl.searchParams.append('recommend', 'false');
}
const resp = await fetch(finalUrl, {
method: 'POST',
headers: {
'Accept': html ? 'text/html' : 'application/json',
'Content-Type': CYCLONEDX_JSON_MEDIA_TYPE,
...getTokenHeaders(opts)
},
body: JSON.stringify(imageSboms),
})
if (resp.status === 200) {
let result;
if (!html) {
result = await resp.json()
} else {
result = await resp.text()
}
if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
let exRequestId = resp.headers.get("ex-request-id");
if (exRequestId) {
console.log("Unique Identifier associated with this request - ex-request-id=" + exRequestId)
}
console.log("Response body received from Trustify DA backend server : " + EOL + EOL)
console.log(JSON.stringify(result, null, 4))
console.log("Ending time of sending component analysis request to Trustify DA backend server= " + new Date())
}
return result
} else {
throw new Error(`Got error response from Trustify DA backend - http return code : ${resp.status}, ex-request-id: ${resp.headers.get("ex-request-id")} error message => ${await resp.text()}`)
}
}
/**
*
* @param url the backend url to send the request to
* @param {import("index.js").Options} [opts={}] - optional various options to pass headers for t he validateToken Request
* @return {Promise<number>} return the HTTP status Code of the response from the validate token request.
*/
async function validateToken(url, opts = {}) {
const fetchOptions = addProxyAgent({
method: 'GET',
headers: {
...getTokenHeaders(opts),
}
}, opts);
let resp = await fetch(`${url}/api/v5/token`, fetchOptions)
if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
let exRequestId = resp.headers.get("ex-request-id");
if (exRequestId) {
console.log("Unique Identifier associated with this request - ex-request-id=" + exRequestId)
}
}
return resp.status
}