-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
request-manager.js
332 lines (310 loc) · 10.6 KB
/
request-manager.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
/* @flow */
/* eslint max-len: 0 */
import {OneTimePasswordError} from '../../src/errors.js';
import {Reporter} from '../../src/reporters/index.js';
import Config from '../../src/config.js';
import * as fs from '../../src/util/fs.js';
jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;
const net = require('net');
const http = require('http');
const https = require('https');
const path = require('path');
test('RequestManager.request with cafile', async () => {
let body;
const options = {
key: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-key.pem')),
cert: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-cert.pem')),
};
const server = https.createServer(options, (req, res) => {
res.end('ok');
});
try {
server.listen(0);
const config = await Config.create({
cafile: path.join(__dirname, '..', 'fixtures', 'certificates', 'cacerts.pem'),
});
const port = server.address().port;
body = await config.requestManager.request({
url: `https://localhost:${port}/?nocache`,
headers: {Connection: 'close'},
});
} finally {
server.close();
}
expect(body).toBe('ok');
});
test('RequestManager.request with ca (string)', async () => {
let body;
const options = {
key: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-key.pem')),
cert: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-cert.pem')),
};
const server = https.createServer(options, (req, res) => {
res.end('ok');
});
try {
server.listen(0);
const bundle = await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'cacerts.pem'));
const hasPemPrefix = block => block.startsWith('-----BEGIN ');
const caCerts = bundle.split(/(-----BEGIN .*\r?\n[^-]+\r?\n--.*)/).filter(hasPemPrefix);
// the 2nd cert is valid one
const config = await Config.create({ca: caCerts[1]});
const port = server.address().port;
body = await config.requestManager.request({
url: `https://localhost:${port}/?nocache`,
headers: {Connection: 'close'},
});
} finally {
server.close();
}
expect(body).toBe('ok');
});
test('RequestManager.request with ca (array)', async () => {
let body;
const options = {
key: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-key.pem')),
cert: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-cert.pem')),
};
const server = https.createServer(options, (req, res) => {
res.end('ok');
});
try {
server.listen(0);
const bundle = await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'cacerts.pem'));
const hasPemPrefix = block => block.startsWith('-----BEGIN ');
const caCerts = bundle.split(/(-----BEGIN .*\r?\n[^-]+\r?\n--.*)/).filter(hasPemPrefix);
const config = await Config.create({ca: caCerts});
const port = server.address().port;
body = await config.requestManager.request({
url: `https://localhost:${port}/?nocache`,
headers: {Connection: 'close'},
});
} finally {
server.close();
}
expect(body).toBe('ok');
});
test('RequestManager.request with mutual TLS', async () => {
let body;
const options = {
key: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-key.pem')),
cert: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-cert.pem')),
ca: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-ca-cert.pem')),
requestCert: true,
rejectUnauthorized: true,
};
const server = https.createServer(options, (req, res) => {
res.end('ok');
});
try {
server.listen(0);
const config = await Config.create({
cafile: path.join(__dirname, '..', 'fixtures', 'certificates', 'server-ca-cert.pem'),
key: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'client-key.pem')),
cert: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'client-cert.pem')),
});
const port = server.address().port;
body = await config.requestManager.request({
url: `https://localhost:${port}/?nocache`,
headers: {Connection: 'close'},
});
} finally {
server.close();
}
expect(body).toBe('ok');
});
test('RequestManager.execute timeout error with maxRetryAttempts=1', async () => {
jest.useFakeTimers();
const LIMIT = 1;
let counter = 0;
const server = net.createServer(c => {
counter += 1;
// Trigger our offline retry queue which has a fixed 3 sec delay
if (counter < LIMIT) {
c.on('close', jest.runOnlyPendingTimers.bind(jest));
}
// emulate TCP server that never closes the connection by not
// doing anything
});
try {
server.listen(0);
const config = await Config.create({networkTimeout: 50});
config.requestManager.setOptions({maxRetryAttempts: LIMIT});
const port = server.address().port;
await config.requestManager.request({
url: `http://localhost:${port}/?nocache`,
});
} catch (err) {
expect(err.message).toContain('TIMEDOUT');
expect(counter).toEqual(LIMIT);
} finally {
await server.close();
jest.useRealTimers();
}
});
test('RequestManager.execute timeout error with default maxRetryAttempts', async () => {
jest.useFakeTimers();
const LIMIT = 5;
let counter = 0;
const server = http.createServer(req => {
counter += 1;
// Trigger our offline retry queue which has a fixed 3 sec delay
if (counter < LIMIT) {
req.on('aborted', jest.runOnlyPendingTimers.bind(jest));
}
// emulate HTTP server that never closes the connection by not
// doing anything
});
try {
server.listen(0);
const config = await Config.create({networkTimeout: 50});
const port = server.address().port;
await config.requestManager.request({
url: `http://localhost:${port}/?nocache`,
});
} catch (err) {
expect(err.message).toContain('TIMEDOUT');
expect(counter).toEqual(LIMIT);
} finally {
await server.close();
jest.useRealTimers();
}
});
for (const statusCode of [403, 442]) {
test(`RequestManager.execute Request ${statusCode} error`, async () => {
jest.resetModules();
// The await await is just to silence Flow - https://github.com/facebook/flow/issues/6064
const config = await await Config.create({}, new Reporter());
const mockStatusCode = statusCode;
jest.mock('request', factory => options => {
options.callback('', {statusCode: mockStatusCode}, '');
return {
on: () => {},
};
});
await config.requestManager.execute({
params: {
url: `https://localhost:port/?nocache`,
headers: {Connection: 'close'},
},
resolve: body => {},
reject: err => {
expect(err.message).toBe(
`https://localhost:port/?nocache: Request "https://localhost:port/?nocache" returned a ${statusCode}`,
);
},
});
});
}
test('RequestManager.execute propagates non HTTP errors', async () => {
jest.resetModules();
jest.mock('request', factory => options => {
options.callback(new Error('bad stuff happened'), {}, '');
return {
on: () => {},
};
});
const config = await await Config.create({}, new Reporter());
await config.requestManager.execute({
params: {
url: `https://localhost:port/?nocache`,
headers: {Connection: 'close'},
},
resolve: body => {},
reject: err => {
expect(err.message).toBe('https://localhost:port/?nocache: bad stuff happened');
},
});
});
test('RequestManager.execute one time password error on npm request', async () => {
jest.resetModules();
jest.mock('request', factory => options => {
options.callback(
'',
{statusCode: 401, headers: {'www-authenticate': 'otp'}},
{error: 'You must provide a one-time pass. Upgrade your client to npm@latest in order to use 2FA.'},
);
return {
on: () => {},
};
});
try {
const config = await Config.create({});
await config.requestManager.request({
url: 'https://registry.npmjs.org/yarn',
});
} catch (err) {
expect(err).toBeInstanceOf(OneTimePasswordError);
}
});
test('RequestManager.execute one time password error on npm login request', async () => {
jest.resetModules();
jest.mock('request', factory => options => {
options.callback('', {statusCode: 401, headers: {'www-authenticate': 'otp'}}, {ok: false});
return {
on: () => {},
};
});
try {
const config = await Config.create({});
await config.requestManager.request({
url: 'https://registry.npmjs.org/-/user/org.couchdb.user:user',
});
} catch (err) {
expect(err).toBeInstanceOf(OneTimePasswordError);
}
});
// Cloudflare will occasionally return an html response with a 500 status code on some calls
for (const statusCode of [408, 500, 542]) {
test(`RequestManager.execute retries on ${statusCode} error`, async () => {
jest.resetModules();
// The await await is just to silence Flow - https://github.com/facebook/flow/issues/6064
const config = await await Config.create({}, new Reporter());
const mockStatusCode = statusCode;
jest.mock('request', factory => {
let retryCount = 2;
return options => {
if (retryCount-- > 0) {
options.callback(
'',
{statusCode: mockStatusCode},
`<!DOCTYPE html><title>Rendering error | registry.yarnpkg.com | Cloudflare</title>...`,
);
} else {
options.callback('', {statusCode: 200}, '');
}
return {
on: () => {},
};
};
});
await config.requestManager.execute({
params: {
url: `https://localhost:port/?nocache`,
headers: {Connection: 'close'},
},
resolve: body => {
expect(body).not.toEqual(false);
},
});
});
}
test('RequestManager.request with offlineNoRequests', async () => {
const config = await Config.create({offline: true}, new Reporter());
try {
await config.requestManager.request({
url: `https://localhost:port/?nocache`,
headers: {Connection: 'close'},
});
} catch (err) {
expect(err.message).toBe('Can\'t make a request in offline mode ("https://localhost:port/?nocache")');
}
});
test('RequestManager.saveHar no captureHar error message', async () => {
const config = await Config.create({captureHar: false}, new Reporter());
try {
config.requestManager.saveHar('testFile');
} catch (err) {
expect(err.message).toBe('RequestManager was not setup to capture HAR files');
}
});