-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
handlers.ts
422 lines (381 loc) · 11 KB
/
handlers.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
import { Span } from '@sentry/apm';
import { captureException, getCurrentHub, withScope } from '@sentry/core';
import { Event } from '@sentry/types';
import { forget, isString, logger, normalize } from '@sentry/utils';
import * as cookie from 'cookie';
import * as domain from 'domain';
import * as http from 'http';
import * as os from 'os';
import * as url from 'url';
import { NodeClient } from './client';
import { flush } from './sdk';
const DEFAULT_SHUTDOWN_TIMEOUT = 2000;
/**
* Express compatible tracing handler.
* @see Exposed as `Handlers.tracingHandler`
*/
export function tracingHandler(): (
req: http.IncomingMessage,
res: http.ServerResponse,
next: (error?: any) => void,
) => void {
return function sentryTracingMiddleware(
req: http.IncomingMessage,
res: http.ServerResponse,
next: (error?: any) => void,
): void {
// TODO: At this point req.route.path we use in `extractTransaction` is not available
// but `req.path` or `req.url` should do the job as well. We could unify this here.
const reqMethod = (req.method || '').toUpperCase();
const reqUrl = req.url;
const hub = getCurrentHub();
const transaction = hub.startSpan({
op: 'http.server',
transaction: `${reqMethod} ${reqUrl}`,
});
hub.configureScope(scope => {
scope.setSpan(transaction);
});
res.once('finish', () => {
transaction.setHttpStatus(res.statusCode);
transaction.finish();
});
next();
};
}
type TransactionTypes = 'path' | 'methodPath' | 'handler';
/** JSDoc */
function extractTransaction(req: { [key: string]: any }, type: boolean | TransactionTypes): string | undefined {
try {
// Express.js shape
const request = req as {
method: string;
route: {
path: string;
stack: [
{
name: string;
}
];
};
};
switch (type) {
case 'path': {
return request.route.path;
}
case 'handler': {
return request.route.stack[0].name;
}
case 'methodPath':
default: {
const method = request.method.toUpperCase();
const path = request.route.path;
return `${method}|${path}`;
}
}
} catch (_oO) {
return undefined;
}
}
/** Default request keys that'll be used to extract data from the request */
const DEFAULT_REQUEST_KEYS = ['cookies', 'data', 'headers', 'method', 'query_string', 'url'];
/** JSDoc */
function extractRequestData(req: { [key: string]: any }, keys: boolean | string[]): { [key: string]: string } {
const request: { [key: string]: any } = {};
const attributes = Array.isArray(keys) ? keys : DEFAULT_REQUEST_KEYS;
// headers:
// node, express: req.headers
// koa: req.header
const headers = (req.headers || req.header || {}) as {
host?: string;
cookie?: string;
};
// method:
// node, express, koa: req.method
const method = req.method;
// host:
// express: req.hostname in > 4 and req.host in < 4
// koa: req.host
// node: req.headers.host
const host = req.hostname || req.host || headers.host || '<no host>';
// protocol:
// node: <n/a>
// express, koa: req.protocol
const protocol =
req.protocol === 'https' || req.secure || ((req.socket || {}) as { encrypted?: boolean }).encrypted
? 'https'
: 'http';
// url (including path and query string):
// node, express: req.originalUrl
// koa: req.url
const originalUrl = (req.originalUrl || req.url) as string;
// absolute url
const absoluteUrl = `${protocol}://${host}${originalUrl}`;
attributes.forEach(key => {
switch (key) {
case 'headers':
request.headers = headers;
break;
case 'method':
request.method = method;
break;
case 'url':
request.url = absoluteUrl;
break;
case 'cookies':
// cookies:
// node, express, koa: req.headers.cookie
request.cookies = cookie.parse(headers.cookie || '');
break;
case 'query_string':
// query string:
// node: req.url (raw)
// express, koa: req.query
request.query_string = url.parse(originalUrl || '', false).query;
break;
case 'data':
if (method === 'GET' || method === 'HEAD') {
break;
}
// body data:
// node, express, koa: req.body
if (req.body !== undefined) {
request.data = isString(req.body) ? req.body : JSON.stringify(normalize(req.body));
}
break;
default:
if ({}.hasOwnProperty.call(req, key)) {
request[key] = (req as { [key: string]: any })[key];
}
}
});
return request;
}
/** Default user keys that'll be used to extract data from the request */
const DEFAULT_USER_KEYS = ['id', 'username', 'email'];
/** JSDoc */
function extractUserData(
user: {
[key: string]: any;
},
keys: boolean | string[],
): { [key: string]: any } {
const extractedUser: { [key: string]: any } = {};
const attributes = Array.isArray(keys) ? keys : DEFAULT_USER_KEYS;
attributes.forEach(key => {
if (user && key in user) {
extractedUser[key] = user[key];
}
});
return extractedUser;
}
/**
* Options deciding what parts of the request to use when enhancing an event
*/
interface ParseRequestOptions {
ip?: boolean;
request?: boolean | string[];
serverName?: boolean;
transaction?: boolean | TransactionTypes;
user?: boolean | string[];
version?: boolean;
}
/**
* Enriches passed event with request data.
*
* @param event Will be mutated and enriched with req data
* @param req Request object
* @param options object containing flags to enable functionality
* @hidden
*/
export function parseRequest(
event: Event,
req: {
[key: string]: any;
user?: {
[key: string]: any;
};
ip?: string;
connection?: {
remoteAddress?: string;
};
},
options?: ParseRequestOptions,
): Event {
// tslint:disable-next-line:no-parameter-reassignment
options = {
ip: false,
request: true,
serverName: true,
transaction: true,
user: true,
version: true,
...options,
};
if (options.version) {
event.contexts = {
...event.contexts,
runtime: {
name: 'node',
version: global.process.version,
},
};
}
if (options.request) {
event.request = {
...event.request,
...extractRequestData(req, options.request),
};
}
if (options.serverName && !event.server_name) {
event.server_name = global.process.env.SENTRY_NAME || os.hostname();
}
if (options.user) {
const extractedUser = req.user ? extractUserData(req.user, options.user) : {};
if (Object.keys(extractedUser)) {
event.user = {
...event.user,
...extractedUser,
};
}
}
// client ip:
// node: req.connection.remoteAddress
// express, koa: req.ip
if (options.ip) {
const ip = req.ip || (req.connection && req.connection.remoteAddress);
if (ip) {
event.user = {
...event.user,
ip_address: ip,
};
}
}
if (options.transaction && !event.transaction) {
const transaction = extractTransaction(req, options.transaction);
if (transaction) {
event.transaction = transaction;
}
}
return event;
}
/**
* Express compatible request handler.
* @see Exposed as `Handlers.requestHandler`
*/
export function requestHandler(
options?: ParseRequestOptions & {
flushTimeout?: number;
},
): (req: http.IncomingMessage, res: http.ServerResponse, next: (error?: any) => void) => void {
return function sentryRequestMiddleware(
req: http.IncomingMessage,
res: http.ServerResponse,
next: (error?: any) => void,
): void {
if (options && options.flushTimeout && options.flushTimeout > 0) {
// tslint:disable-next-line: no-unbound-method
const _end = res.end;
res.end = function(chunk?: any | (() => void), encoding?: string | (() => void), cb?: () => void): void {
flush(options.flushTimeout)
.then(() => {
_end.call(this, chunk, encoding, cb);
})
.then(null, e => {
logger.error(e);
});
};
}
const local = domain.create();
local.add(req);
local.add(res);
local.on('error', next);
local.run(() => {
getCurrentHub().configureScope(scope =>
scope.addEventProcessor((event: Event) => parseRequest(event, req, options)),
);
next();
});
};
}
/** JSDoc */
interface MiddlewareError extends Error {
status?: number | string;
statusCode?: number | string;
status_code?: number | string;
output?: {
statusCode?: number | string;
};
}
/** JSDoc */
function getStatusCodeFromResponse(error: MiddlewareError): number {
const statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode);
return statusCode ? parseInt(statusCode as string, 10) : 500;
}
/** Returns true if response code is internal server error */
function defaultShouldHandleError(error: MiddlewareError): boolean {
const status = getStatusCodeFromResponse(error);
return status >= 500;
}
/**
* Express compatible error handler.
* @see Exposed as `Handlers.errorHandler`
*/
export function errorHandler(options?: {
/**
* Callback method deciding whether error should be captured and sent to Sentry
* @param error Captured middleware error
*/
shouldHandleError?(error: MiddlewareError): boolean;
}): (
error: MiddlewareError,
req: http.IncomingMessage,
res: http.ServerResponse,
next: (error: MiddlewareError) => void,
) => void {
return function sentryErrorMiddleware(
error: MiddlewareError,
req: http.IncomingMessage,
res: http.ServerResponse,
next: (error: MiddlewareError) => void,
): void {
const shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError;
if (shouldHandleError(error)) {
withScope(scope => {
if (req.headers && isString(req.headers['sentry-trace'])) {
const span = Span.fromTraceparent(req.headers['sentry-trace'] as string);
scope.setSpan(span);
}
const eventId = captureException(error);
(res as any).sentry = eventId;
next(error);
});
return;
}
next(error);
};
}
/**
* @hidden
*/
export function logAndExitProcess(error: Error): void {
console.error(error && error.stack ? error.stack : error);
const client = getCurrentHub().getClient<NodeClient>();
if (client === undefined) {
logger.warn('No NodeClient was defined, we are exiting the process now.');
global.process.exit(1);
return;
}
const options = client.getOptions();
const timeout =
(options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) ||
DEFAULT_SHUTDOWN_TIMEOUT;
forget(
client.close(timeout).then((result: boolean) => {
if (!result) {
logger.warn('We reached the timeout for emptying the request buffer, still exiting now!');
}
global.process.exit(1);
}),
);
}