-
Notifications
You must be signed in to change notification settings - Fork 6
/
analysis.js
189 lines (176 loc) · 6.93 KB
/
analysis.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
import fs from "node:fs";
import path from "node:path";
import {EOL} from "os";
import {RegexNotToBeLogged, getCustom} from "./tools.js";
export default { requestComponent, requestStack, validateToken }
const rhdaTokenHeader = "rhda-token";
const rhdaSourceHeader = "rhda-source"
const rhdaOperationTypeHeader = "rhda-operation-type"
/**
* Send a stack analysis request and get the report as 'text/html' or 'application/json'.
* @param {import('./provider').Provider | import('./providers/base_java.js').default } 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 {{}} [opts={}] - optional various options to pass along the application
* @returns {Promise<string|import('../generated/backend/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 = provider.provideStack(manifest, opts) // throws error if content providing failed
opts["source-manifest"]= ""
opts[rhdaOperationTypeHeader.toUpperCase().replaceAll("-","_")] = "stack-analysis"
let startTime = new Date()
let EndTime
if (process.env["EXHORT_DEBUG"] === "true") {
console.log("Starting time of sending stack analysis request to exhort server= " + startTime)
}
let resp = await fetch(`${url}/api/v4/analysis`, {
method: 'POST',
headers: {
'Accept': html ? 'text/html' : 'application/json',
'Content-Type': provided.contentType,
...getTokenHeaders(opts)
},
body: provided.content
})
let result
if(resp.status === 200) {
if (!html) {
result = await resp.json()
} else {
result = await resp.text()
}
if (process.env["EXHORT_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 exhort server : " + EOL + EOL)
console.log(console.log(JSON.stringify(result, null, 4)))
console.log("Ending time of sending stack analysis request to exhort server= " + EndTime)
let time = (EndTime - startTime) / 1000
console.log("Total Time in seconds: " + time)
}
} else {
throw new Error(`Got error response from exhort 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} data - the content or the path of the manifest
* @param {string} url - the backend url to send the request to
* @param {{}} [opts={}] - optional various options to pass along the application
* @returns {Promise<import('../generated/backend/AnalysisReport').AnalysisReport>}
*/
async function requestComponent(provider, data, url, opts = {}, path = '') {
if(data.trim() !== "") {
opts["source-manifest"]= Buffer.from(data).toString('base64')
// for gradle component analysis is an exception and requires only path exclusively, and not data content.
}else {
opts["source-manifest"]= Buffer.from(fs.readFileSync(path).toString()).toString('base64')
}
let provided = provider.provideComponent(data, opts,path) // throws error if content providing failed
opts["source-manifest"]= ""
opts[rhdaOperationTypeHeader.toUpperCase().replaceAll("-","_")] = "component-analysis"
if (process.env["EXHORT_DEBUG"] === "true") {
console.log("Starting time of sending component analysis request to exhort server= " + new Date())
}
let resp = await fetch(`${url}/api/v4/analysis`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': provided.contentType,
...getTokenHeaders(opts),
},
body: provided.content
})
let result
if(resp.status === 200) {
result = await resp.json()
if (process.env["EXHORT_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 exhort server : " + EOL + EOL)
console.log(JSON.stringify(result, null, 4))
console.log("Ending time of sending component analysis request to exhort server= " + new Date())
}
} else {
throw new Error(`Got error response from exhort backend - http return code : ${resp.status}, ex-request-id: ${resp.headers.get("ex-request-id")} error message => ${await resp.text()}`)
}
return Promise.resolve(result)
}
/**
*
* @param url the backend url to send the request to
* @param {{}} [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 = {}) {
let resp = await fetch(`${url}/api/v4/token`, {
method: 'GET',
headers: {
// 'Accept': 'text/plain',
...getTokenHeaders(opts),
}
})
if (process.env["EXHORT_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
}
/**
*
* @param {string} headerName - the header name to populate in request
* @param headers
* @param {{}} [opts={}] - optional various options to pass along the application
* @private
*/
function setRhdaHeader(headerName,headers,opts) {
let rhdaHeaderValue = getCustom(headerName.toUpperCase().replaceAll("-", "_"), null, opts);
if (rhdaHeaderValue) {
headers[headerName] = rhdaHeaderValue
}
}
/**
* Utility function for fetching vendor tokens
* @param {{}} [opts={}] - optional various options to pass along the application
* @returns {{}}
*/
function getTokenHeaders(opts = {}) {
let supportedTokens = ['snyk','oss-index']
let headers = {}
supportedTokens.forEach(vendor => {
let token = getCustom(`EXHORT_${vendor.replace("-","_").toUpperCase()}_TOKEN`, null, opts);
if (token) {
headers[`ex-${vendor}-token`] = token
}
let user = getCustom(`EXHORT_${vendor.replace("-","_").toUpperCase()}_USER`, null, opts);
if (user) {
headers[`ex-${vendor}-user`] = user
}
})
setRhdaHeader(rhdaTokenHeader,headers, opts);
setRhdaHeader(rhdaSourceHeader,headers, opts);
setRhdaHeader(rhdaOperationTypeHeader, headers,opts);
if (process.env["EXHORT_DEBUG"] === "true")
{
console.log("Headers Values to be sent to exhort:" + EOL)
for (const headerKey in headers) {
if(!headerKey.match(RegexNotToBeLogged))
{
console.log(`${headerKey}: ${headers[headerKey]}`)
}
}
}
return headers
}