-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
95 lines (85 loc) · 2.7 KB
/
index.ts
File metadata and controls
95 lines (85 loc) · 2.7 KB
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
/* eslint-disable @typescript-eslint/ban-ts-comment */
// https://www.npmjs.com/package/@opentelemetry/instrumentation-http
// https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation-http
import {
IncomingMessage,
ServerResponse,
ClientRequest,
OutgoingHttpHeaders,
} from 'http';
import { Span } from '@opentelemetry/api';
import { HttpInstrumentationConfig } from '@opentelemetry/instrumentation-http';
export class HttpHandler {
constructor(private secretValues?: string[]) {}
maskSecrets(value: string, secretValues: string[] = this.secretValues) {
if (!secretValues) {
return value;
}
try {
const regexp = new RegExp(secretValues.join('|'), 'g');
return value.replace(regexp, '*****');
} catch {
console.warn('Imposible to mask', value);
}
}
onRequestBody(span: Span, body: any) {
span.setAttributes({
'http.request.body': this.maskSecrets(body.toString()),
});
}
onRequestHeaders(span: Span, headers: OutgoingHttpHeaders) {
span.setAttributes({
['http.request.headers']: this.maskSecrets(JSON.stringify(headers)),
});
}
onResponseBody(span: Span, body: any) {
span.setAttributes({
['http.response.body']: this.maskSecrets(body),
});
}
onResponseHeaders(span: Span, headers: OutgoingHttpHeaders) {
span.setAttributes({
['http.response.headers']: this.maskSecrets(JSON.stringify(headers)),
});
}
requestHook(span: Span, request: ClientRequest) {
span.updateName(`HTTP ${request.method} - ${request.host}`);
this.onRequestHeaders(span, request.getHeaders());
const oldWrite = request.write.bind(request);
request.write = (data: any) => {
this.onRequestBody(span, data);
return oldWrite(data);
};
}
responseHook(
span: Span,
response: IncomingMessage | ServerResponse<IncomingMessage>,
) {
let body = '';
response.on('data', (chunk) => (body += chunk));
response.on('end', () => {
this.onResponseBody(span, body);
// @ts-ignore
this.onResponseHeaders(span, response.headers);
});
}
}
export class HttpInstrumentation {
static withPayloadDetails(
config: HttpInstrumentationConfig = {},
secretValues?: string[],
httpHandler?: HttpHandler,
): {
'@opentelemetry/instrumentation-http': HttpInstrumentationConfig;
} {
const httpInstrumentation = httpHandler || new HttpHandler(secretValues);
return {
'@opentelemetry/instrumentation-http': {
responseHook:
httpInstrumentation.responseHook.bind(httpInstrumentation),
requestHook: httpInstrumentation.requestHook.bind(httpInstrumentation),
...config,
},
};
}
}