-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathrequestdata.test.ts
584 lines (493 loc) · 18.6 KB
/
requestdata.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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
/* eslint-disable deprecation/deprecation */
/* Note: These tests (except for the ones related to cookies) should eventually live in `@sentry/utils`, and can be
* moved there once the the backwards-compatibility-preserving wrappers in `handlers.ts` are removed.
*/
// TODO (v8 / #5257): Remove everything above
import { Event, TransactionSource, User } from '@sentry/types';
import {
addRequestDataToEvent,
AddRequestDataToEventOptions,
CrossPlatformRequest,
extractPathForTransaction,
extractRequestData as newExtractRequestData,
} from '@sentry/utils';
import * as cookie from 'cookie';
import * as net from 'net';
import * as url from 'url';
import {
ExpressRequest,
extractRequestData as oldExtractRequestData,
parseRequest,
} from '../src/requestDataDeprecated';
const mockCookieModule = { parse: jest.fn() };
// TODO (v8 / #5257): Remove `describe.each` wrapper, remove `formatArgs` wrapper, reformat args in tests, use only
// `addRequestDataToEvent`, and move these tests to @sentry/utils
describe.each([parseRequest, addRequestDataToEvent])(
'backwards compatibility of `parseRequest` rename and move',
fn => {
/** Rearrage and cast args correctly for each version of the function */
function formatArgs(
fn: typeof parseRequest | typeof addRequestDataToEvent,
event: Event,
req: any,
include?: AddRequestDataToEventOptions['include'],
): Parameters<typeof parseRequest> | Parameters<typeof addRequestDataToEvent> {
if (fn.name === 'parseRequest') {
return [event, req as ExpressRequest, include];
} else {
return [
event,
req as CrossPlatformRequest,
{
include,
deps: {
cookie: mockCookieModule,
url,
},
},
];
}
}
describe(fn, () => {
let mockEvent: Event;
let mockReq: { [key: string]: any };
beforeEach(() => {
mockEvent = {};
mockReq = {
baseUrl: '/routerMountPath',
body: 'foo',
cookies: { test: 'test' },
headers: {
host: 'mattrobenolt.com',
},
method: 'POST',
originalUrl: '/routerMountPath/subpath/specificValue?querystringKey=querystringValue',
path: '/subpath/specificValue',
query: {
querystringKey: 'querystringValue',
},
route: {
path: '/subpath/:parameterName',
stack: [
{
name: 'parameterNameRouteHandler',
},
],
},
url: '/subpath/specificValue?querystringKey=querystringValue',
user: {
custom_property: 'foo',
email: '[email protected]',
id: 123,
username: 'tobias',
},
};
});
describe(`${fn.name}.user properties`, () => {
const DEFAULT_USER_KEYS = ['id', 'username', 'email'];
const CUSTOM_USER_KEYS = ['custom_property'];
test(`${fn.name}.user only contains the default properties from the user`, () => {
const [event, req, options] = formatArgs(fn, mockEvent, mockReq);
const parsedRequest: Event = fn(event, req, options);
expect(Object.keys(parsedRequest.user as User)).toEqual(DEFAULT_USER_KEYS);
});
test(`${fn.name}.user only contains the custom properties specified in the options.user array`, () => {
const optionsWithCustomUserKeys = {
user: CUSTOM_USER_KEYS,
};
const [event, req, options] = formatArgs(fn, mockEvent, mockReq, optionsWithCustomUserKeys);
const parsedRequest: Event = fn(event, req, options);
expect(Object.keys(parsedRequest.user as User)).toEqual(CUSTOM_USER_KEYS);
});
test(`${fn.name}.user doesnt blow up when someone passes non-object value`, () => {
const reqWithUser = {
...mockReq,
// @ts-ignore user is not assignable to object
user: 'wat',
};
const [event, req, options] = formatArgs(fn, mockEvent, reqWithUser);
const parsedRequest: Event = fn(event, req, options);
expect(parsedRequest.user).toBeUndefined();
});
});
describe(`${fn.name}.ip property`, () => {
test('can be extracted from req.ip', () => {
const mockReqWithIP = {
...mockReq,
ip: '123',
};
const optionsWithIP = {
ip: true,
};
const [event, req, options] = formatArgs(fn, mockEvent, mockReqWithIP, optionsWithIP);
const parsedRequest: Event = fn(event, req, options);
expect(parsedRequest.user!.ip_address).toEqual('123');
});
test('can extract from req.socket.remoteAddress', () => {
const reqWithIPInSocket = {
...mockReq,
socket: {
remoteAddress: '321',
} as net.Socket,
};
const optionsWithIP = {
ip: true,
};
const [event, req, options] = formatArgs(fn, mockEvent, reqWithIPInSocket, optionsWithIP);
const parsedRequest: Event = fn(event, req, options);
expect(parsedRequest.user!.ip_address).toEqual('321');
});
});
describe(`${fn.name}.request properties`, () => {
test(`${fn.name}.request only contains the default set of properties from the request`, () => {
const DEFAULT_REQUEST_PROPERTIES = ['cookies', 'data', 'headers', 'method', 'query_string', 'url'];
const [event, req, options] = formatArgs(fn, mockEvent, mockReq);
const parsedRequest: Event = fn(event, req, options);
expect(Object.keys(parsedRequest.request!)).toEqual(DEFAULT_REQUEST_PROPERTIES);
});
test(`${fn.name}.request only contains the specified properties in the options.request array`, () => {
const INCLUDED_PROPERTIES = ['data', 'headers', 'query_string', 'url'];
const optionsWithRequestIncludes = {
request: INCLUDED_PROPERTIES,
};
const [event, req, options] = formatArgs(fn, mockEvent, mockReq, optionsWithRequestIncludes);
const parsedRequest: Event = fn(event, req, options);
expect(Object.keys(parsedRequest.request!)).toEqual(INCLUDED_PROPERTIES);
});
test.each([
[undefined, true],
['GET', false],
['HEAD', false],
])(
`${fn.name}.request skips \`body\` property for GET and HEAD requests - %s method`,
(method, shouldIncludeBodyData) => {
const reqWithMethod = { ...mockReq, method };
const [event, req, options] = formatArgs(fn, mockEvent, reqWithMethod);
const parsedRequest: Event = fn(event, req, options);
if (shouldIncludeBodyData) {
expect(parsedRequest.request).toHaveProperty('data');
} else {
expect(parsedRequest.request).not.toHaveProperty('data');
}
},
);
});
describe(`${fn.name}.transaction property`, () => {
test('extracts method and full route path by default`', () => {
const [event, req, options] = formatArgs(fn, mockEvent, mockReq);
const parsedRequest: Event = fn(event, req, options);
expect(parsedRequest.transaction).toEqual('POST /routerMountPath/subpath/:parameterName');
});
test('extracts method and full path by default when mountpoint is `/`', () => {
mockReq.originalUrl = mockReq.originalUrl.replace('/routerMountpath', '');
mockReq.baseUrl = '';
const [event, req, options] = formatArgs(fn, mockEvent, mockReq);
const parsedRequest: Event = fn(event, req, options);
// `subpath/` is the full path here, because there's no router mount path
expect(parsedRequest.transaction).toEqual('POST /subpath/:parameterName');
});
test('fallback to method and `originalUrl` if route is missing', () => {
delete mockReq.route;
const [event, req, options] = formatArgs(fn, mockEvent, mockReq);
const parsedRequest: Event = fn(event, req, options);
expect(parsedRequest.transaction).toEqual('POST /routerMountPath/subpath/specificValue');
});
test('can extract path only instead if configured', () => {
const optionsWithPathTransaction = { transaction: 'path' } as const;
const [event, req, options] = formatArgs(fn, mockEvent, mockReq, optionsWithPathTransaction);
const parsedRequest: Event = fn(event, req, options);
expect(parsedRequest.transaction).toEqual('/routerMountPath/subpath/:parameterName');
});
test('can extract handler name instead if configured', () => {
const optionsWithHandlerTransaction = { transaction: 'handler' } as const;
const [event, req, options] = formatArgs(fn, mockEvent, mockReq, optionsWithHandlerTransaction);
const parsedRequest: Event = fn(event, req, options);
expect(parsedRequest.transaction).toEqual('parameterNameRouteHandler');
});
});
});
},
);
// TODO (v8 / #5257): Remove `describe.each` wrapper, remove `formatArgs` wrapper, reformat args in tests, use only
// `newExtractRequestData`, rename `newExtractRequestData` to just `extractRequestData`, and move these tests (except
// the ones involving cookies) to @sentry/utils (use `mockCookieModule` for others)
Object.defineProperty(oldExtractRequestData, 'name', {
value: 'oldExtractRequestData',
});
Object.defineProperty(newExtractRequestData, 'name', {
value: 'newExtractRequestData',
});
describe.each([oldExtractRequestData, newExtractRequestData])(
'backwards compatibility of `extractRequestData` move',
fn => {
/** Rearrage and cast args correctly for each version of the function */
function formatArgs(
fn: typeof oldExtractRequestData | typeof newExtractRequestData,
req: any,
include?: string[],
): Parameters<typeof oldExtractRequestData> | Parameters<typeof newExtractRequestData> {
if (fn.name === 'oldExtractRequestData') {
return [req as ExpressRequest, include] as Parameters<typeof oldExtractRequestData>;
} else {
return [
req as CrossPlatformRequest,
{
include,
deps: {
cookie: include?.includes('cookies') ? cookie : mockCookieModule,
url,
},
},
] as Parameters<typeof newExtractRequestData>;
}
}
describe(fn, () => {
describe('default behaviour', () => {
test('node', () => {
const mockReq = {
headers: { host: 'example.com' },
method: 'GET',
socket: { encrypted: true },
originalUrl: '/',
};
const [req, options] = formatArgs(fn, mockReq);
expect(fn(req, options as any)).toEqual({
cookies: {},
headers: {
host: 'example.com',
},
method: 'GET',
query_string: undefined,
url: 'https://example.com/',
});
});
test('degrades gracefully without request data', () => {
const mockReq = {};
const [req, options] = formatArgs(fn, mockReq);
expect(fn(req, options as any)).toEqual({
cookies: {},
headers: {},
method: undefined,
query_string: undefined,
url: 'http://<no host>',
});
});
});
describe('cookies', () => {
it('uses `req.cookies` if available', () => {
const mockReq = {
cookies: { foo: 'bar' },
};
const optionsWithCookies = ['cookies'];
const [req, options] = formatArgs(fn, mockReq, optionsWithCookies);
expect(fn(req, options as any)).toEqual({
cookies: { foo: 'bar' },
});
});
it('parses the cookie header', () => {
const mockReq = {
headers: {
cookie: 'foo=bar;',
},
};
const optionsWithCookies = ['cookies'];
const [req, options] = formatArgs(fn, mockReq, optionsWithCookies);
expect(fn(req, options as any)).toEqual({
cookies: { foo: 'bar' },
});
});
it('falls back if no cookies are defined', () => {
const mockReq = {};
const optionsWithCookies = ['cookies'];
const [req, options] = formatArgs(fn, mockReq, optionsWithCookies);
expect(fn(req, options as any)).toEqual({
cookies: {},
});
});
});
describe('data', () => {
it('includes data from `req.body` if available', () => {
const mockReq = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'foo=bar',
};
const optionsWithData = ['data'];
const [req, options] = formatArgs(fn, mockReq, optionsWithData);
expect(fn(req, options as any)).toEqual({
data: 'foo=bar',
});
});
it('encodes JSON body contents back to a string', () => {
const mockReq = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: { foo: 'bar' },
};
const optionsWithData = ['data'];
const [req, options] = formatArgs(fn, mockReq, optionsWithData);
expect(fn(req, options as any)).toEqual({
data: '{"foo":"bar"}',
});
});
});
describe('query_string', () => {
it('parses the query parms from the url', () => {
const mockReq = {
headers: { host: 'example.com' },
secure: true,
originalUrl: '/?foo=bar',
};
const optionsWithQueryString = ['query_string'];
const [req, options] = formatArgs(fn, mockReq, optionsWithQueryString);
expect(fn(req, options as any)).toEqual({
query_string: 'foo=bar',
});
});
it('gracefully degrades if url cannot be determined', () => {
const mockReq = {};
const optionsWithQueryString = ['query_string'];
const [req, options] = formatArgs(fn, mockReq, optionsWithQueryString);
expect(fn(req, options as any)).toEqual({
query_string: undefined,
});
});
});
describe('url', () => {
test('express/koa', () => {
const mockReq = {
host: 'example.com',
protocol: 'https',
url: '/',
};
const optionsWithURL = ['url'];
const [req, options] = formatArgs(fn, mockReq, optionsWithURL);
expect(fn(req, options as any)).toEqual({
url: 'https://example.com/',
});
});
test('node', () => {
const mockReq = {
headers: { host: 'example.com' },
socket: { encrypted: true },
originalUrl: '/',
};
const optionsWithURL = ['url'];
const [req, options] = formatArgs(fn, mockReq, optionsWithURL);
expect(fn(req, options as any)).toEqual({
url: 'https://example.com/',
});
});
});
describe('custom key', () => {
it('includes the custom key if present', () => {
const mockReq = {
httpVersion: '1.1',
};
const optionsWithCustomKey = ['httpVersion'];
const [req, options] = formatArgs(fn, mockReq, optionsWithCustomKey);
expect(fn(req, options as any)).toEqual({
httpVersion: '1.1',
});
});
it('gracefully degrades if the custom key is missing', () => {
const mockReq = {};
const optionsWithCustomKey = ['httpVersion'];
const [req, options] = formatArgs(fn, mockReq, optionsWithCustomKey);
expect(fn(req, options as any)).toEqual({});
});
});
});
},
);
describe('extractPathForTransaction', () => {
it.each([
[
'extracts a parameterized route and method if available',
{
method: 'get',
baseUrl: '/api/users',
route: { path: '/:id/details' },
originalUrl: '/api/users/123/details',
} as CrossPlatformRequest,
{ path: true, method: true },
'GET /api/users/:id/details',
'route' as TransactionSource,
],
[
'ignores the method if specified',
{
method: 'get',
baseUrl: '/api/users',
route: { path: '/:id/details' },
originalUrl: '/api/users/123/details',
} as CrossPlatformRequest,
{ path: true, method: false },
'/api/users/:id/details',
'route' as TransactionSource,
],
[
'ignores the path if specified',
{
method: 'get',
baseUrl: '/api/users',
route: { path: '/:id/details' },
originalUrl: '/api/users/123/details',
} as CrossPlatformRequest,
{ path: false, method: true },
'GET',
'route' as TransactionSource,
],
[
'returns an empty string if everything should be ignored',
{
method: 'get',
baseUrl: '/api/users',
route: { path: '/:id/details' },
originalUrl: '/api/users/123/details',
} as CrossPlatformRequest,
{ path: false, method: false },
'',
'route' as TransactionSource,
],
[
'falls back to the raw URL if no parameterized route is available',
{
method: 'get',
baseUrl: '/api/users',
originalUrl: '/api/users/123/details',
} as CrossPlatformRequest,
{ path: true, method: true },
'GET /api/users/123/details',
'url' as TransactionSource,
],
])(
'%s',
(
_: string,
req: CrossPlatformRequest,
options: { path?: boolean; method?: boolean },
expectedRoute: string,
expectedSource: TransactionSource,
) => {
const [route, source] = extractPathForTransaction(req, options);
expect(route).toEqual(expectedRoute);
expect(source).toEqual(expectedSource);
},
);
it('overrides the requests information with a custom route if specified', () => {
const req = {
method: 'get',
baseUrl: '/api/users',
route: { path: '/:id/details' },
originalUrl: '/api/users/123/details',
} as CrossPlatformRequest;
const [route, source] = extractPathForTransaction(req, {
path: true,
method: true,
customRoute: '/other/path/:id/details',
});
expect(route).toEqual('GET /other/path/:id/details');
expect(source).toEqual('route');
});
});