-
Notifications
You must be signed in to change notification settings - Fork 533
/
request.ts
186 lines (157 loc) · 5.12 KB
/
request.ts
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
import { debug as debugModule } from 'debug';
import * as needle from 'needle';
import { parse, format } from 'url';
import * as querystring from 'querystring';
import * as zlib from 'zlib';
import config from '../config';
import { getProxyForUrl } from 'proxy-from-env';
import { bootstrap } from 'global-agent';
import { Global } from '../../cli/args';
import { Payload } from './types';
import { getVersion } from '../version';
import * as https from 'https';
import * as http from 'http';
import { jsonStringifyLargeObject } from '../json';
const debug = debugModule('snyk:req');
const snykDebug = debugModule('snyk');
declare const global: Global;
function setupRequest(payload: Payload) {
// This ensures we support lowercase http(s)_proxy values as well
// The weird IF around it ensures we don't create an envvar with a value of undefined, which throws error when trying to use it as a proxy
if (process.env.HTTP_PROXY || process.env.http_proxy) {
process.env.HTTP_PROXY = process.env.HTTP_PROXY || process.env.http_proxy;
}
if (process.env.HTTPS_PROXY || process.env.https_proxy) {
process.env.HTTPS_PROXY =
process.env.HTTPS_PROXY || process.env.https_proxy;
}
const versionNumber = getVersion();
const body = payload.body;
let data = body;
delete payload.body;
if (!payload.headers) {
payload.headers = {};
}
payload.headers['x-snyk-cli-version'] = versionNumber;
const noCompression = payload.noCompression;
if (body && !noCompression) {
debug('compressing request body');
const json = JSON.stringify(body);
if (json.length < 1e4) {
debug(json);
}
// always compress going upstream
data = zlib.gzipSync(json, { level: 9 });
snykDebug('sending request to:', payload.url);
snykDebug('request body size:', json.length);
snykDebug('gzipped request body size:', data.length);
let callGraphLength: number | null = null;
if (body.callGraph) {
callGraphLength = jsonStringifyLargeObject(body.callGraph).length;
snykDebug('call graph size:', callGraphLength);
}
payload.headers['content-encoding'] = 'gzip';
payload.headers['content-length'] = data.length;
}
const parsedUrl = parse(payload.url);
if (
parsedUrl.protocol === 'http:' &&
parsedUrl.hostname !== 'localhost' &&
process.env.SNYK_HTTP_PROTOCOL_UPGRADE !== '0'
) {
debug('forcing api request to https');
parsedUrl.protocol = 'https:';
payload.url = format(parsedUrl);
}
// prefer config timeout unless payload specified
if (!payload.hasOwnProperty('timeout')) {
payload.timeout = config.timeout * 1000; // s -> ms
}
try {
debug('request payload: ', jsonStringifyLargeObject(payload));
} catch (e) {
debug('request payload is too big to log', e);
}
const method = (
payload.method || 'get'
).toLowerCase() as needle.NeedleHttpVerbs;
let url = payload.url;
if (payload.qs) {
// Parse the URL and append the search part - this will take care of adding the '/?' part if it's missing
const urlObject = new URL(url);
urlObject.search = querystring.stringify(payload.qs);
url = urlObject.toString();
delete payload.qs;
}
const agent =
parsedUrl.protocol === 'http:'
? new http.Agent({ keepAlive: true })
: new https.Agent({ keepAlive: true });
const options: needle.NeedleOptions = {
use_proxy_from_env_var: false,
json: payload.json,
parse: payload.parse,
headers: payload.headers,
timeout: payload.timeout,
follow_max: 5,
family: payload.family,
agent,
};
const proxyUri = getProxyForUrl(url);
if (proxyUri) {
snykDebug('using proxy:', proxyUri);
bootstrap({
environmentVariableNamespace: '',
});
} else {
snykDebug('not using proxy');
}
if (global.ignoreUnknownCA) {
debug('Using insecure mode (ignore unknown certificate authority)');
options.rejectUnauthorized = false;
}
return { method, url, data, options };
}
export async function makeRequest(
payload: Payload,
): Promise<{ res: needle.NeedleResponse; body: any }> {
const { method, url, data, options } = setupRequest(payload);
return new Promise((resolve, reject) => {
needle.request(method, url, data, options, (err, res, respBody) => {
debug(err);
debug(
'response (%s): ',
(res || {}).statusCode,
jsonStringifyLargeObject(respBody),
);
if (err) {
return reject(err);
}
resolve({ res, body: respBody });
});
});
}
export async function streamRequest(
payload: Payload,
): Promise<needle.ReadableStream> {
const { method, url, data, options } = setupRequest(payload);
try {
const result = await needle.request(method, url, data, options);
const statusCode = await getStatusCode(result);
debug('response (%s): <stream>', statusCode);
return result;
} catch (e) {
debug(e);
throw e;
}
}
async function getStatusCode(stream: needle.ReadableStream): Promise<number> {
return new Promise((resolve, reject) => {
stream.on('header', (statusCode: number) => {
resolve(statusCode);
});
stream.on('err', (err: Error) => {
reject(err);
});
});
}