-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathhttp.test.ts
425 lines (350 loc) · 13.1 KB
/
http.test.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
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import * as http from 'http';
import { createGunzip } from 'zlib';
import { createTransport } from '@sentry/core';
import { addItemToEnvelope, createAttachmentEnvelopeItem, createEnvelope, serializeEnvelope } from '@sentry/core';
import type { EventEnvelope, EventItem } from '@sentry/core';
import { type Mock, afterEach, describe, expect, it, vi } from 'vitest';
import { makeNodeTransport } from '../../src/transports';
vi.mock('@sentry/core', async () => {
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const actualCore = (await vi.importActual('@sentry/core')) as typeof import('@sentry/core');
return {
...actualCore,
createTransport: vi.fn().mockImplementation(actualCore.createTransport),
};
});
vi.mock('node:http', async () => {
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const original = (await vi.importActual('node:http')) as typeof import('node:http');
return {
...original,
request: original.request,
};
});
import * as httpProxyAgent from '../../src/proxy';
const SUCCESS = 200;
const RATE_LIMIT = 429;
const INVALID = 400;
const FAILED = 500;
interface TestServerOptions {
statusCode: number;
responseHeaders?: Record<string, string | string[] | undefined>;
}
let testServer: http.Server | undefined;
function setupTestServer(
options: TestServerOptions,
requestInspector?: (req: http.IncomingMessage, body: string, raw: Uint8Array) => void,
) {
testServer = http.createServer((req, res) => {
const chunks: Buffer[] = [];
const stream = req.headers['content-encoding'] === 'gzip' ? req.pipe(createGunzip({})) : req;
stream.on('data', data => {
chunks.push(data);
});
stream.on('end', () => {
requestInspector?.(req, chunks.join(), Buffer.concat(chunks));
});
res.writeHead(options.statusCode, options.responseHeaders);
res.end();
// also terminate socket because keepalive hangs connection a bit
// eslint-disable-next-line deprecation/deprecation
res.connection?.end();
});
testServer.listen(18101);
return new Promise(resolve => {
testServer?.on('listening', resolve);
});
}
const TEST_SERVER_URL = 'http://localhost:18101';
const EVENT_ENVELOPE = createEnvelope<EventEnvelope>({ event_id: 'aa3ff046696b4bc6b609ce6d28fde9e2', sent_at: '123' }, [
[{ type: 'event' }, { event_id: 'aa3ff046696b4bc6b609ce6d28fde9e2' }] as EventItem,
]);
const SERIALIZED_EVENT_ENVELOPE = serializeEnvelope(EVENT_ENVELOPE);
const ATTACHMENT_ITEM = createAttachmentEnvelopeItem({ filename: 'empty-file.bin', data: new Uint8Array(50_000) });
const EVENT_ATTACHMENT_ENVELOPE = addItemToEnvelope(EVENT_ENVELOPE, ATTACHMENT_ITEM);
const SERIALIZED_EVENT_ATTACHMENT_ENVELOPE = serializeEnvelope(EVENT_ATTACHMENT_ENVELOPE) as Uint8Array;
const defaultOptions = {
url: TEST_SERVER_URL,
recordDroppedEvent: () => undefined,
};
// empty function to keep test output clean
const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
afterEach(
() =>
new Promise<void>(done => {
vi.clearAllMocks();
if (testServer?.listening) {
testServer.close(() => done());
} else {
done();
}
}),
);
describe('makeNewHttpTransport()', () => {
describe('.send()', () => {
it('should correctly send envelope to server', async () => {
await setupTestServer({ statusCode: SUCCESS }, (req, body) => {
expect(req.method).toBe('POST');
expect(body).toBe(SERIALIZED_EVENT_ENVELOPE);
});
const transport = makeNodeTransport(defaultOptions);
await transport.send(EVENT_ENVELOPE);
});
it('allows overriding keepAlive', async () => {
await setupTestServer({ statusCode: SUCCESS }, req => {
expect(req.headers).toEqual(
expect.objectContaining({
// node http module lower-cases incoming headers
connection: 'keep-alive',
}),
);
});
const transport = makeNodeTransport({ keepAlive: true, ...defaultOptions });
await transport.send(EVENT_ENVELOPE);
});
it('should correctly send user-provided headers to server', async () => {
await setupTestServer({ statusCode: SUCCESS }, req => {
expect(req.headers).toEqual(
expect.objectContaining({
// node http module lower-cases incoming headers
'x-some-custom-header-1': 'value1',
'x-some-custom-header-2': 'value2',
}),
);
});
const transport = makeNodeTransport({
...defaultOptions,
headers: {
'X-Some-Custom-Header-1': 'value1',
'X-Some-Custom-Header-2': 'value2',
},
});
await transport.send(EVENT_ENVELOPE);
});
it.each([RATE_LIMIT, INVALID, FAILED])(
'should resolve on bad server response (status %i)',
async serverStatusCode => {
await setupTestServer({ statusCode: serverStatusCode });
const transport = makeNodeTransport(defaultOptions);
await expect(transport.send(EVENT_ENVELOPE)).resolves.toEqual(
expect.objectContaining({ statusCode: serverStatusCode }),
);
},
);
it('should resolve when server responds with rate limit header and status code 200', async () => {
await setupTestServer({
statusCode: SUCCESS,
responseHeaders: {
'Retry-After': '2700',
'X-Sentry-Rate-Limits': '60::organization, 2700::organization',
},
});
const transport = makeNodeTransport(defaultOptions);
await expect(transport.send(EVENT_ENVELOPE)).resolves.toEqual({
statusCode: SUCCESS,
headers: {
'retry-after': '2700',
'x-sentry-rate-limits': '60::organization, 2700::organization',
},
});
});
});
describe('compression', () => {
it('small envelopes should not be compressed', async () => {
await setupTestServer(
{
statusCode: SUCCESS,
responseHeaders: {},
},
(req, body) => {
expect(req.headers['content-encoding']).toBeUndefined();
expect(body).toBe(SERIALIZED_EVENT_ENVELOPE);
},
);
const transport = makeNodeTransport(defaultOptions);
await transport.send(EVENT_ENVELOPE);
});
it('large envelopes should be compressed', async () => {
await setupTestServer(
{
statusCode: SUCCESS,
responseHeaders: {},
},
(req, _, raw) => {
expect(req.headers['content-encoding']).toEqual('gzip');
expect(raw.buffer).toStrictEqual(SERIALIZED_EVENT_ATTACHMENT_ENVELOPE.buffer);
},
);
const transport = makeNodeTransport(defaultOptions);
await transport.send(EVENT_ATTACHMENT_ENVELOPE);
});
});
describe('proxy', () => {
const proxyAgentSpy = vi
.spyOn(httpProxyAgent, 'HttpsProxyAgent')
// @ts-expect-error using http agent as https proxy agent
.mockImplementation(() => new http.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 }));
it('can be configured through option', () => {
makeNodeTransport({
...defaultOptions,
url: 'http://[email protected]:8989/mysubpath/50622',
proxy: 'http://example.com',
});
expect(proxyAgentSpy).toHaveBeenCalledTimes(1);
expect(proxyAgentSpy).toHaveBeenCalledWith('http://example.com');
});
it('can be configured through env variables option', () => {
process.env.http_proxy = 'http://example.com';
makeNodeTransport({
...defaultOptions,
url: 'http://[email protected]:8989/mysubpath/50622',
});
expect(proxyAgentSpy).toHaveBeenCalledTimes(1);
expect(proxyAgentSpy).toHaveBeenCalledWith('http://example.com');
delete process.env.http_proxy;
});
it('client options have priority over env variables', () => {
process.env.http_proxy = 'http://foo.com';
makeNodeTransport({
...defaultOptions,
url: 'http://[email protected]:8989/mysubpath/50622',
proxy: 'http://bar.com',
});
expect(proxyAgentSpy).toHaveBeenCalledTimes(1);
expect(proxyAgentSpy).toHaveBeenCalledWith('http://bar.com');
delete process.env.http_proxy;
});
it('no_proxy allows for skipping specific hosts', () => {
process.env.no_proxy = 'sentry.io';
makeNodeTransport({
...defaultOptions,
url: 'http://[email protected]:8989/mysubpath/50622',
proxy: 'http://example.com',
});
expect(proxyAgentSpy).not.toHaveBeenCalled();
delete process.env.no_proxy;
});
it('no_proxy works with a port', () => {
process.env.http_proxy = 'http://example.com:8080';
process.env.no_proxy = 'sentry.io:8989';
makeNodeTransport({
...defaultOptions,
url: 'http://[email protected]:8989/mysubpath/50622',
});
expect(proxyAgentSpy).not.toHaveBeenCalled();
delete process.env.no_proxy;
delete process.env.http_proxy;
});
it('no_proxy works with multiple comma-separated hosts', () => {
process.env.http_proxy = 'http://example.com:8080';
process.env.no_proxy = 'example.com,sentry.io,wat.com:1337';
makeNodeTransport({
...defaultOptions,
url: 'http://[email protected]:8989/mysubpath/50622',
});
expect(proxyAgentSpy).not.toHaveBeenCalled();
delete process.env.no_proxy;
delete process.env.http_proxy;
});
});
describe('should register TransportRequestExecutor that returns the correct object from server response', () => {
it('rate limit', async () => {
await setupTestServer({
statusCode: RATE_LIMIT,
responseHeaders: {},
});
makeNodeTransport(defaultOptions);
const registeredRequestExecutor = (createTransport as Mock).mock.calls[0]?.[1];
const executorResult = registeredRequestExecutor({
body: serializeEnvelope(EVENT_ENVELOPE),
category: 'error',
});
await expect(executorResult).resolves.toEqual(
expect.objectContaining({
statusCode: RATE_LIMIT,
}),
);
});
it('OK', async () => {
await setupTestServer({
statusCode: SUCCESS,
});
makeNodeTransport(defaultOptions);
const registeredRequestExecutor = (createTransport as Mock).mock.calls[0]?.[1];
const executorResult = registeredRequestExecutor({
body: serializeEnvelope(EVENT_ENVELOPE),
category: 'error',
});
await expect(executorResult).resolves.toEqual(
expect.objectContaining({
statusCode: SUCCESS,
headers: {
'retry-after': null,
'x-sentry-rate-limits': null,
},
}),
);
});
it('OK with rate-limit headers', async () => {
await setupTestServer({
statusCode: SUCCESS,
responseHeaders: {
'Retry-After': '2700',
'X-Sentry-Rate-Limits': '60::organization, 2700::organization',
},
});
makeNodeTransport(defaultOptions);
const registeredRequestExecutor = (createTransport as Mock).mock.calls[0]?.[1];
const executorResult = registeredRequestExecutor({
body: serializeEnvelope(EVENT_ENVELOPE),
category: 'error',
});
await expect(executorResult).resolves.toEqual(
expect.objectContaining({
statusCode: SUCCESS,
headers: {
'retry-after': '2700',
'x-sentry-rate-limits': '60::organization, 2700::organization',
},
}),
);
});
it('NOK with rate-limit headers', async () => {
await setupTestServer({
statusCode: RATE_LIMIT,
responseHeaders: {
'Retry-After': '2700',
'X-Sentry-Rate-Limits': '60::organization, 2700::organization',
},
});
makeNodeTransport(defaultOptions);
const registeredRequestExecutor = (createTransport as Mock).mock.calls[0]?.[1];
const executorResult = registeredRequestExecutor({
body: serializeEnvelope(EVENT_ENVELOPE),
category: 'error',
});
await expect(executorResult).resolves.toEqual(
expect.objectContaining({
statusCode: RATE_LIMIT,
headers: {
'retry-after': '2700',
'x-sentry-rate-limits': '60::organization, 2700::organization',
},
}),
);
});
});
it('should create a noop transport if an invalid url is passed', async () => {
const requestSpy = vi.spyOn(http, 'request');
const transport = makeNodeTransport({ ...defaultOptions, url: 'foo' });
await transport.send(EVENT_ENVELOPE);
expect(requestSpy).not.toHaveBeenCalled();
});
it('should warn if an invalid url is passed', async () => {
const transport = makeNodeTransport({ ...defaultOptions, url: 'invalid url' });
await transport.send(EVENT_ENVELOPE);
expect(consoleWarnSpy).toHaveBeenCalledWith(
'[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.',
);
});
});