@opentelemetry/instrumentation-http 0.221.0 → 0.222.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -64,8 +64,50 @@ Options | Type
64
64
  `serverName` | `string` | **Deprecated.** No longer used. Stable HTTP semantic conventions do not include the `http.server_name` attribute; this option has no effect.
65
65
  `requireParentforOutgoingSpans` | Boolean | Require that is a parent span to create new span for outgoing requests.
66
66
  `requireParentforIncomingSpans` | Boolean | Require that is a parent span to create new span for incoming requests.
67
+ `redactedQueryParams` | `string[]` | **Experimental.** Query parameter names whose values are redacted on outgoing (client) spans. Replaces the built-in list. See [Query parameter redaction](#query-parameter-redaction).
68
+ `redactedQueryParamsServer` | `string[]` | **Experimental.** Query parameter names whose values are redacted on incoming (server) spans. Replaces the built-in list. See [Query parameter redaction](#query-parameter-redaction).
67
69
  `headersToSpanAttributes` | `object` | Specify which HTTP headers should be captured as span attributes. This is an object of the form `{client: {requestHeaders: [...], responseHeaders: [...]}, server: {requestHeaders: [...], responseHeaders: [...]}}`, where each `[...]` is an array of HTTP header names (case-insensitive) to capture. Client (outgoing requests, incoming responses) and server (incoming requests, outgoing responses) headers will be converted to span attributes in the form of `http.{request,response}.header.$header_name`, e.g. `http.response.header.content_length`. By default hyphens in header names are converted to underscore. However, if stable semantic conventions are selected (see next section), then, hyphens in header names are not changed, e.g. `http.response.header.content-length`.
68
70
 
71
+ #### Query parameter redaction
72
+
73
+ Query parameters that commonly carry credentials are redacted before URLs are recorded as span attributes. On client spans the redacted URL is recorded as `url.full`; on server spans the redacted query string is recorded as `url.query`. Matching values are replaced with the literal string `REDACTED`.
74
+
75
+ By default both sides redact the following parameters:
76
+
77
+ ```text
78
+ sig, Signature, AWSAccessKeyId, X-Goog-Signature,
79
+ X-Amz-Signature, X-Amz-Credential, X-Amz-Security-Token
80
+ ```
81
+
82
+ `redactedQueryParams` controls the client side and `redactedQueryParamsServer` controls the server side, independently. For each option:
83
+
84
+ - Omit it to use the built-in list above.
85
+ - Supply an array to **replace** the built-in list entirely. The arrays are not merged, so include any built-in parameters you still want redacted.
86
+ - Supply an empty array to disable redaction on that side.
87
+
88
+ The two options do not fall back to each other: when `redactedQueryParamsServer` is omitted, server spans use the built-in list, *not* the value of `redactedQueryParams`. Setting `redactedQueryParams` alone therefore leaves custom parameters unredacted on server spans. To redact the same custom parameters on both sides, set both options to the same array.
89
+
90
+ Parameter names are matched exactly and are case-sensitive, which is why the built-in list contains both `sig` and `Signature`.
91
+
92
+ ```js
93
+ // The built-in list plus an application-specific parameter, applied to both sides.
94
+ const redacted = [
95
+ 'sig',
96
+ 'Signature',
97
+ 'AWSAccessKeyId',
98
+ 'X-Goog-Signature',
99
+ 'X-Amz-Signature',
100
+ 'X-Amz-Credential',
101
+ 'X-Amz-Security-Token',
102
+ 'api_key',
103
+ ];
104
+
105
+ new HttpInstrumentation({
106
+ redactedQueryParams: redacted,
107
+ redactedQueryParamsServer: redacted,
108
+ });
109
+ ```
110
+
69
111
  #### Hook function signatures
70
112
 
71
113
  Hook type | Parameters | Return value
@@ -80,63 +122,39 @@ Hook type | Parameters
80
122
 
81
123
  ## Semantic Conventions
82
124
 
83
- Prior to version `0.54.0`, this instrumentation created spans targeting an experimental semantic convention [Version 1.7.0](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.7.0/semantic_conventions/README.md).
84
-
85
- HTTP semantic conventions (semconv) were stabilized in v1.23.0, and a [migration process](https://github.com/open-telemetry/semantic-conventions/blob/main/docs/non-normative/http-migration.md#http-semantic-convention-stability-migration) was defined.
86
- `instrumentation-http` versions 0.54.0 - XXXX include support for migrating to stable HTTP semantic conventions, as described below.
87
- The intent is to provide an approximate 6 month time window for users of this instrumentation to migrate to the new HTTP semconv, after which a new minor version will use the *new* semconv by default and drop support for the old semconv.
88
- See the [HTTP semconv migration plan for OpenTelemetry JS instrumentations](https://github.com/open-telemetry/opentelemetry-js/issues/5646).
89
-
90
- To select which semconv version(s) is emitted from this instrumentation, use the `OTEL_SEMCONV_STABILITY_OPT_IN` environment variable.
91
-
92
- - `http`: emit the new (stable) v1.23.0+ semantics
93
- - `http/dup`: emit **both** the old v1.7.0 and the new (stable) v1.23.0+ semantics
94
- - By default, if `OTEL_SEMCONV_STABILITY_OPT_IN` includes neither of the above tokens, the old v1.7.0 semconv is used.
95
-
96
- `instrumentation-http` versions XXX and later emit the stable v1.23.0+ semantics only.
97
-
98
- ### Attributes collected
99
-
100
- v1.7.0 semconv | v1.23.0 semconv | Short Description
101
- ------------------------------------------- | ----------------------------------- | -----
102
- `http.client_ip` | `client.address` | The IP address of the original client behind all proxies, if known
103
- `http.flavor` | `network.protocol.version` | Kind of HTTP protocol used
104
- `http.host` | `server.address` | The value of the HTTP host header
105
- `http.method` | `http.request.method` | HTTP request method
106
- `http.request_content_length` | (opt-in, `headersToSpanAttributes`) | The size of the request payload body in bytes. For newer semconv, use the `headersToSpanAttributes` option to capture this as `http.request.header.content-length`.
107
- `http.request_content_length_uncompressed` | (not included) | The size of the uncompressed request payload body after transport decoding. (In semconv v1.23.0 this is defined by `http.request.body.size`, which is experimental and opt-in.)
108
- `http.response_content_length` | (opt-in, `headersToSpanAttributes`) | The size of the response payload body in bytes. For newer semconv, use the `headersToSpanAttributes` option to capture this as `http.response.header.content-length`.
109
- `http.response_content_length_uncompressed` | (not included) | The size of the uncompressed response payload body after transport decoding. (In semconv v1.23.0 this is defined by `http.response.body.size`, which is experimental and opt-in.)
110
- `http.route` | no change | The matched route (path template).
111
- `http.scheme` | `url.scheme` | The URI scheme identifying the used protocol
112
- `http.server_name` | `server.address` | The primary server name of the matched virtual host
113
- `http.status_code` | `http.response.status_code` | HTTP response status code
114
- `http.target` | `url.path` and `url.query` | The URI path and query component
115
- `http.url` | `url.full` | Full HTTP request URL in the form `scheme://host[:port]/path?query[#fragment]`
116
- `http.user_agent` | `user_agent.original` | Value of the HTTP User-Agent header sent by the client
117
- `net.host.ip` | `network.local.address` | Like net.peer.ip but for the host IP. Useful in case of a multi-IP host
118
- `net.host.name` | `server.address` | Local hostname or similar
119
- `net.host.port` | `server.port` | Like net.peer.port but for the host port
120
- `net.peer.ip` | `network.peer.address` | Remote address of the peer (dotted decimal for IPv4 or RFC5952 for IPv6)
121
- `net.peer.name` | `server.address` | Server domain name if available without reverse DNS lookup
122
- `net.peer.port` | `server.port` | Server port number
123
- `net.transport` | `network.transport` | Transport protocol used
124
-
125
- Metrics Exported:
125
+ **Span attributes:**
126
+
127
+ v1.23.0 semconv | Short Description
128
+ ----------------------------------- | -----
129
+ `client.address` | The IP address of the original client behind all proxies, if known
130
+ `network.protocol.version` | Kind of HTTP protocol used
131
+ `server.address` | The value of the HTTP host header
132
+ `http.request.method` | HTTP request method
133
+ (opt-in, `headersToSpanAttributes`) | The size of the request payload body in bytes. For newer semconv, use the `headersToSpanAttributes` option to capture this as `http.request.header.content-length`.
134
+ (not included) | The size of the uncompressed request payload body after transport decoding. (In semconv v1.23.0 this is defined by `http.request.body.size`, which is experimental and opt-in.)
135
+ (opt-in, `headersToSpanAttributes`) | The size of the response payload body in bytes. For newer semconv, use the `headersToSpanAttributes` option to capture this as `http.response.header.content-length`.
136
+ (not included) | The size of the uncompressed response payload body after transport decoding. (In semconv v1.23.0 this is defined by `http.response.body.size`, which is experimental and opt-in.)
137
+ no change | The matched route (path template).
138
+ `url.scheme` | The URI scheme identifying the used protocol
139
+ `server.address` | The primary server name of the matched virtual host
140
+ `http.response.status_code` | HTTP response status code
141
+ `url.path` and `url.query` | The URI path and query component
142
+ `url.full` | Full HTTP request URL in the form `scheme://host[:port]/path?query[#fragment]`
143
+ `user_agent.original` | Value of the HTTP User-Agent header sent by the client
144
+ `network.local.address` | Like net.peer.ip but for the host IP. Useful in case of a multi-IP host
145
+ `server.address` | Local hostname or similar
146
+ `server.port` | Like net.peer.port but for the host port
147
+ `network.peer.address` | Remote address of the peer (dotted decimal for IPv4 or RFC5952 for IPv6)
148
+ `server.address` | Server domain name if available without reverse DNS lookup
149
+ `server.port` | Server port number
150
+ `network.transport` | Transport protocol used
151
+
152
+ **Metrics:**
126
153
 
127
154
  - [`http.server.request.duration`](https://github.com/open-telemetry/semantic-conventions/blob/v1.27.0/docs/http/http-metrics.md#metric-httpserverrequestduration)
128
155
  - [`http.client.request.duration`](https://github.com/open-telemetry/semantic-conventions/blob/v1.27.0/docs/http/http-metrics.md#metric-httpclientrequestduration)
129
156
 
130
- ### Upgrading Semantic Conventions
131
-
132
- When upgrading to the new semantic conventions, it is recommended to do so in the following order:
133
-
134
- 1. Upgrade `@opentelemetry/instrumentation-http` to the latest version
135
- 2. Set `OTEL_SEMCONV_STABILITY_OPT_IN=http/dup` to emit both old and new semantic conventions
136
- 3. Modify alerts, dashboards, metrics, and other processes to expect the new semantic conventions
137
- 4. Set `OTEL_SEMCONV_STABILITY_OPT_IN=http` to emit only the new semantic conventions
138
-
139
- This will cause both the old and new semantic conventions to be emitted during the transition period.
157
+ Versions of `@opentelemetry/instrumentation-http` to 0.221.0 used semantic conventions [v1.7.0](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.7.0/semantic_conventions/README.md) by default. Versions 0.54.0 - 0.220.0 supported [the `OTEL_SEMCONV_STABILITY_OPT_IN` environment variable for migrating from old to stable semantic conventions](https://opentelemetry.io/docs/specs/semconv/non-normative/http-migration/).
140
158
 
141
159
  ## Useful links
142
160
 
package/build/src/http.js CHANGED
@@ -13,6 +13,7 @@ const instrumentation_1 = require("@opentelemetry/instrumentation");
13
13
  const events_1 = require("events");
14
14
  const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
15
15
  const utils_1 = require("./utils");
16
+ const internal_types_1 = require("./internal-types");
16
17
  /**
17
18
  * `node:http` and `node:https` instrumentation for OpenTelemetry
18
19
  */
@@ -321,6 +322,8 @@ class HttpInstrumentation extends instrumentation_1.InstrumentationBase {
321
322
  component: component,
322
323
  hookAttributes: instrumentation._callStartSpanHook(request, instrumentation.getConfig().startIncomingSpanHook),
323
324
  enableSyntheticSourceDetection: instrumentation.getConfig().enableSyntheticSourceDetection || false,
325
+ redactedQueryParams: instrumentation.getConfig().redactedQueryParamsServer ??
326
+ Array.from(internal_types_1.DEFAULT_QUERY_STRINGS_TO_REDACT),
324
327
  }, instrumentation._diag);
325
328
  Object.assign(spanAttributes, instrumentation._headerCapture.server.captureRequestHeaders(header => request.headers[header]));
326
329
  const spanOptions = {
@@ -1 +1 @@
1
- {"version":3,"file":"http.js","sourceRoot":"","sources":["../../src/http.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAUH,4CAS4B;AAE5B,8CAO6B;AAI7B,2BAA2B;AAE3B,uCAAoC;AACpC,oEAIwC;AACxC,mCAAsC;AACtC,8EAW6C;AAC7C,mCAaiB;AAGjB;;GAEG;AACH,MAAa,mBAAoB,SAAQ,qCAA8C;IACrF,oCAAoC;IACnB,aAAa,GAAkB,IAAI,OAAO,EAAQ,CAAC;IAC5D,cAAc,CAAC;IACf,YAAY,GAAY,KAAK,CAAC;IAC9B,aAAa,GAAY,KAAK,CAAC;IAIvC,YAAY,SAAoC,EAAE;QAChD,KAAK,CAAC,qCAAqC,EAAE,iBAAO,EAAE,MAAM,CAAC,CAAC;QAC9D,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,oBAAoB,EAAE,CAAC;IACpD,CAAC;IAEkB,wBAAwB;QACzC,IAAI,CAAC,4BAA4B,GAAG,IAAI,CAAC,KAAK,CAAC,eAAe,CAC5D,0DAAmC,EACnC;YACE,WAAW,EAAE,mCAAmC;YAChD,IAAI,EAAE,GAAG;YACT,SAAS,EAAE,eAAS,CAAC,MAAM;YAC3B,MAAM,EAAE;gBACN,wBAAwB,EAAE;oBACxB,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC;oBAChE,GAAG,EAAE,EAAE;iBACR;aACF;SACF,CACF,CAAC;QACF,IAA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G,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,EACvB,GAAG,EAAE,GAAE,CAAC,EACR,IAAI,CACL,CAAC;SACH;IACH,CAAC;IAEO,oBAAoB;QAC1B,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;QAEhC,OAAO;YACL,MAAM,EAAE;gBACN,qBAAqB,EAAE,IAAA,qBAAa,EAClC,SAAS,EACT,MAAM,CAAC,uBAAuB,EAAE,MAAM,EAAE,cAAc,IAAI,EAAE,CAC7D;gBACD,sBAAsB,EAAE,IAAA,qBAAa,EACnC,UAAU,EACV,MAAM,CAAC,uBAAuB,EAAE,MAAM,EAAE,eAAe,IAAI,EAAE,CAC9D;aACF;YACD,MAAM,EAAE;gBACN,qBAAqB,EAAE,IAAA,qBAAa,EAClC,SAAS,EACT,MAAM,CAAC,uBAAuB,EAAE,MAAM,EAAE,cAAc,IAAI,EAAE,CAC7D;gBACD,sBAAsB,EAAE,IAAA,qBAAa,EACnC,UAAU,EACV,MAAM,CAAC,uBAAuB,EAAE,MAAM,EAAE,eAAe,IAAI,EAAE,CAC9D;aACF;SACF,CAAC;IACJ,CAAC;CACF;AAl4BD,kDAk4BC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n HrTime,\n Span,\n SpanOptions,\n SpanStatus,\n Histogram,\n Attributes,\n} from '@opentelemetry/api';\nimport {\n context,\n INVALID_SPAN_CONTEXT,\n propagation,\n ROOT_CONTEXT,\n SpanKind,\n SpanStatusCode,\n trace,\n ValueType,\n} from '@opentelemetry/api';\nimport type { RPCMetadata } from '@opentelemetry/core';\nimport {\n hrTime,\n hrTimeDuration,\n hrTimeToMilliseconds,\n suppressTracing,\n RPCType,\n setRPCMetadata,\n} from '@opentelemetry/core';\nimport type * as http from 'http';\nimport type * as https from 'https';\nimport type { Socket } from 'net';\nimport * as url from 'url';\nimport type { HttpInstrumentationConfig } from './types';\nimport { VERSION } from './version';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { errorMonitor } from 'events';\nimport {\n ATTR_ERROR_TYPE,\n ATTR_HTTP_REQUEST_METHOD,\n ATTR_HTTP_RESPONSE_STATUS_CODE,\n ATTR_NETWORK_PROTOCOL_VERSION,\n ATTR_HTTP_ROUTE,\n ATTR_SERVER_ADDRESS,\n ATTR_SERVER_PORT,\n ATTR_URL_SCHEME,\n METRIC_HTTP_CLIENT_REQUEST_DURATION,\n METRIC_HTTP_SERVER_REQUEST_DURATION,\n} from '@opentelemetry/semantic-conventions';\nimport {\n extractHostnameAndPort,\n getIncomingRequestAttributes,\n getIncomingRequestAttributesOnResponse,\n getIncomingStableRequestMetricAttributesOnResponse,\n getOutgoingRequestAttributes,\n getOutgoingRequestAttributesOnResponse,\n getOutgoingStableRequestMetricAttributesOnResponse,\n getRequestInfo,\n headerCapture,\n isValidOptionsType,\n parseResponseStatus,\n setSpanWithError,\n} from './utils';\nimport type { Err, Func, Http, HttpRequestArgs, Https } from './internal-types';\n\n/**\n * `node:http` and `node:https` instrumentation for OpenTelemetry\n */\nexport class HttpInstrumentation extends InstrumentationBase<HttpInstrumentationConfig> {\n /** keep track on spans not ended */\n private readonly _spanNotEnded: WeakSet<Span> = new WeakSet<Span>();\n private _headerCapture;\n private _httpPatched: boolean = false;\n private _httpsPatched: boolean = false;\n declare private _httpServerDurationHistogram: Histogram;\n declare private _httpClientDurationHistogram: Histogram;\n\n constructor(config: HttpInstrumentationConfig = {}) {\n super('@opentelemetry/instrumentation-http', VERSION, config);\n this._headerCapture = this._createHeaderCapture();\n }\n\n protected override _updateMetricInstruments() {\n this._httpServerDurationHistogram = this.meter.createHistogram(\n METRIC_HTTP_SERVER_REQUEST_DURATION,\n {\n description: 'Duration of HTTP server requests.',\n unit: 's',\n valueType: ValueType.DOUBLE,\n advice: {\n explicitBucketBoundaries: [\n 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5,\n 7.5, 10,\n ],\n },\n }\n );\n this._httpClientDurationHistogram = this.meter.createHistogram(\n METRIC_HTTP_CLIENT_REQUEST_DURATION,\n {\n description: 'Duration of HTTP client requests.',\n unit: 's',\n valueType: ValueType.DOUBLE,\n advice: {\n explicitBucketBoundaries: [\n 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5,\n 7.5, 10,\n ],\n },\n }\n );\n }\n\n private _recordServerDuration(durationMs: number, attributes: Attributes) {\n // stable histogram is counted in S\n this._httpServerDurationHistogram.record(durationMs / 1000, attributes);\n }\n\n private _recordClientDuration(durationMs: number, attributes: Attributes) {\n // stable histogram is counted in S\n this._httpClientDurationHistogram.record(durationMs / 1000, attributes);\n }\n\n override setConfig(config: HttpInstrumentationConfig = {}): void {\n super.setConfig(config);\n this._headerCapture = this._createHeaderCapture();\n }\n\n init(): [\n InstrumentationNodeModuleDefinition,\n InstrumentationNodeModuleDefinition,\n ] {\n return [this._getHttpsInstrumentation(), this._getHttpInstrumentation()];\n }\n\n private _getHttpInstrumentation() {\n return new InstrumentationNodeModuleDefinition(\n 'http',\n ['*'],\n (moduleExports: Http): Http => {\n // Guard against double-instrumentation, if loaded by both `require`\n // and `import`.\n if (this._httpPatched) {\n return moduleExports;\n }\n this._httpPatched = true;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const isESM = (moduleExports as any)[Symbol.toStringTag] === 'Module';\n\n if (!this.getConfig().disableOutgoingRequestInstrumentation) {\n const patchedRequest = this._wrap(\n moduleExports,\n 'request',\n this._getPatchOutgoingRequestFunction('http')\n ) as unknown as Func<http.ClientRequest>;\n const patchedGet = this._wrap(\n moduleExports,\n 'get',\n this._getPatchOutgoingGetFunction(patchedRequest)\n );\n if (isESM) {\n // To handle `import http from 'http'`, which returns the default\n // export, we need to set `module.default.*`.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (moduleExports as any).default.request = patchedRequest;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (moduleExports as any).default.get = patchedGet;\n }\n }\n if (!this.getConfig().disableIncomingRequestInstrumentation) {\n this._wrap(\n moduleExports.Server.prototype,\n 'emit',\n this._getPatchIncomingRequestFunction('http')\n );\n }\n return moduleExports;\n },\n (moduleExports: Http) => {\n this._httpPatched = false;\n if (moduleExports === undefined) return;\n\n if (!this.getConfig().disableOutgoingRequestInstrumentation) {\n this._unwrap(moduleExports, 'request');\n this._unwrap(moduleExports, 'get');\n }\n if (!this.getConfig().disableIncomingRequestInstrumentation) {\n this._unwrap(moduleExports.Server.prototype, 'emit');\n }\n }\n );\n }\n\n private _getHttpsInstrumentation() {\n return new InstrumentationNodeModuleDefinition(\n 'https',\n ['*'],\n (moduleExports: Https): Https => {\n // Guard against double-instrumentation, if loaded by both `require`\n // and `import`.\n if (this._httpsPatched) {\n return moduleExports;\n }\n this._httpsPatched = true;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const isESM = (moduleExports as any)[Symbol.toStringTag] === 'Module';\n\n if (!this.getConfig().disableOutgoingRequestInstrumentation) {\n const patchedRequest = this._wrap(\n moduleExports,\n 'request',\n this._getPatchHttpsOutgoingRequestFunction('https')\n ) as unknown as Func<http.ClientRequest>;\n const patchedGet = this._wrap(\n moduleExports,\n 'get',\n this._getPatchHttpsOutgoingGetFunction(patchedRequest)\n );\n if (isESM) {\n // To handle `import https from 'https'`, which returns the default\n // export, we need to set `module.default.*`.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (moduleExports as any).default.request = patchedRequest;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (moduleExports as any).default.get = patchedGet;\n }\n }\n if (!this.getConfig().disableIncomingRequestInstrumentation) {\n this._wrap(\n moduleExports.Server.prototype,\n 'emit',\n this._getPatchIncomingRequestFunction('https')\n );\n }\n return moduleExports;\n },\n (moduleExports: Https) => {\n this._httpsPatched = false;\n if (moduleExports === undefined) return;\n\n if (!this.getConfig().disableOutgoingRequestInstrumentation) {\n this._unwrap(moduleExports, 'request');\n this._unwrap(moduleExports, 'get');\n }\n if (!this.getConfig().disableIncomingRequestInstrumentation) {\n this._unwrap(moduleExports.Server.prototype, 'emit');\n }\n }\n );\n }\n\n /**\n * Creates spans for incoming requests, restoring spans' context if applied.\n */\n private _getPatchIncomingRequestFunction(component: 'http' | 'https') {\n return (\n original: (event: string, ...args: unknown[]) => boolean\n ): ((this: unknown, event: string, ...args: unknown[]) => boolean) => {\n return this._incomingRequestFunction(component, original);\n };\n }\n\n /**\n * Creates spans for outgoing requests, sending spans' context for distributed\n * tracing.\n */\n private _getPatchOutgoingRequestFunction(component: 'http' | 'https') {\n return (original: Func<http.ClientRequest>): Func<http.ClientRequest> => {\n return this._outgoingRequestFunction(component, original);\n };\n }\n\n private _getPatchOutgoingGetFunction(\n clientRequest: (\n options: http.RequestOptions | string | url.URL,\n ...args: HttpRequestArgs\n ) => http.ClientRequest\n ) {\n return (_original: Func<http.ClientRequest>): Func<http.ClientRequest> => {\n // Re-implement http.get. This needs to be done (instead of using\n // getPatchOutgoingRequestFunction to patch it) because we need to\n // set the trace context header before the returned http.ClientRequest is\n // ended. The Node.js docs state that the only differences between\n // request and get are that (1) get defaults to the HTTP GET method and\n // (2) the returned request object is ended immediately. The former is\n // already true (at least in supported Node versions up to v10), so we\n // simply follow the latter. Ref:\n // https://nodejs.org/dist/latest/docs/api/http.html#http_http_get_options_callback\n // https://github.com/googleapis/cloud-trace-nodejs/blob/master/src/instrumentations/instrumentation-http.ts#L198\n return function outgoingGetRequest<\n T extends http.RequestOptions | string | url.URL,\n >(options: T, ...args: HttpRequestArgs): http.ClientRequest {\n const req = clientRequest(options, ...args);\n req.end();\n return req;\n };\n };\n }\n\n /** Patches HTTPS outgoing requests */\n private _getPatchHttpsOutgoingRequestFunction(component: 'http' | 'https') {\n return (original: Func<http.ClientRequest>): Func<http.ClientRequest> => {\n const instrumentation = this;\n return function httpsOutgoingRequest(\n options: https.RequestOptions | string | URL,\n ...args: HttpRequestArgs\n ): http.ClientRequest {\n // Makes sure options will have default HTTPS parameters\n if (\n component === 'https' &&\n typeof options === 'object' &&\n options?.constructor?.name !== 'URL'\n ) {\n options = Object.assign({}, options);\n instrumentation._setDefaultOptions(options);\n }\n return instrumentation._getPatchOutgoingRequestFunction(component)(\n original\n )(options, ...args);\n };\n };\n }\n\n private _setDefaultOptions(options: https.RequestOptions) {\n options.protocol = options.protocol || 'https:';\n options.port = options.port || 443;\n }\n\n /** Patches HTTPS outgoing get requests */\n private _getPatchHttpsOutgoingGetFunction(\n clientRequest: (\n options: http.RequestOptions | string | URL,\n ...args: HttpRequestArgs\n ) => http.ClientRequest\n ) {\n return (original: Func<http.ClientRequest>): Func<http.ClientRequest> => {\n const instrumentation = this;\n return function httpsOutgoingRequest(\n options: https.RequestOptions | string | URL,\n ...args: HttpRequestArgs\n ): http.ClientRequest {\n return instrumentation._getPatchOutgoingGetFunction(clientRequest)(\n original\n )(options, ...args);\n };\n };\n }\n\n /**\n * Attach event listeners to a client request to end span and add span attributes.\n *\n * @param request The original request object.\n * @param span representing the current operation\n * @param startTime representing the start time of the request to calculate duration in Metric\n * @param metricAttributes metric attributes for the request duration metric\n */\n private _traceClientRequest(\n request: http.ClientRequest,\n span: Span,\n startTime: HrTime,\n metricAttributes: Attributes\n ): http.ClientRequest {\n if (this.getConfig().requestHook) {\n this._callRequestHook(span, request);\n }\n\n /**\n * Determines if the request has errored or the response has ended/errored.\n */\n let responseFinished = false;\n\n /*\n * User 'response' event listeners can be added before our listener,\n * force our listener to be the first, so response emitter is bound\n * before any user listeners are added to it.\n */\n request.prependListener(\n 'response',\n (response: http.IncomingMessage & { aborted?: boolean }) => {\n this._diag.debug('outgoingRequest on response()');\n if (request.listenerCount('response') <= 1) {\n response.resume();\n }\n const responseAttributes =\n getOutgoingRequestAttributesOnResponse(response);\n span.setAttributes(responseAttributes);\n metricAttributes = Object.assign(\n metricAttributes,\n getOutgoingStableRequestMetricAttributesOnResponse(responseAttributes)\n );\n\n if (this.getConfig().responseHook) {\n this._callResponseHook(span, response);\n }\n\n span.setAttributes(\n this._headerCapture.client.captureRequestHeaders(header =>\n request.getHeader(header)\n )\n );\n span.setAttributes(\n this._headerCapture.client.captureResponseHeaders(\n header => response.headers[header]\n )\n );\n\n context.bind(context.active(), response);\n\n const endHandler = () => {\n this._diag.debug('outgoingRequest on end()');\n if (responseFinished) {\n return;\n }\n responseFinished = true;\n let status: SpanStatus;\n\n if (response.aborted && !response.complete) {\n status = { code: SpanStatusCode.ERROR };\n } else {\n // behaves same for new and old semconv\n status = {\n code: parseResponseStatus(SpanKind.CLIENT, response.statusCode),\n };\n }\n\n span.setStatus(status);\n\n if (this.getConfig().applyCustomAttributesOnSpan) {\n safeExecuteInTheMiddle(\n () =>\n this.getConfig().applyCustomAttributesOnSpan!(\n span,\n request,\n response\n ),\n () => {},\n true\n );\n }\n\n this._closeHttpSpan(\n span,\n SpanKind.CLIENT,\n startTime,\n metricAttributes\n );\n };\n\n response.on('end', endHandler);\n response.on(errorMonitor, (error: Err) => {\n this._diag.debug('outgoingRequest on error()', error);\n if (responseFinished) {\n return;\n }\n responseFinished = true;\n this._onOutgoingRequestError(\n span,\n metricAttributes,\n startTime,\n error\n );\n });\n }\n );\n request.on('close', () => {\n this._diag.debug('outgoingRequest on request close()');\n if (request.aborted || responseFinished) {\n return;\n }\n responseFinished = true;\n this._closeHttpSpan(span, SpanKind.CLIENT, startTime, metricAttributes);\n });\n request.on(errorMonitor, (error: Err) => {\n this._diag.debug('outgoingRequest on request error()', error);\n if (responseFinished) {\n return;\n }\n responseFinished = true;\n this._onOutgoingRequestError(span, metricAttributes, startTime, error);\n });\n\n this._diag.debug('http.ClientRequest return request');\n return request;\n }\n\n private _incomingRequestFunction(\n component: 'http' | 'https',\n original: (event: string, ...args: unknown[]) => boolean\n ) {\n const instrumentation = this;\n return function incomingRequest(\n this: unknown,\n event: string,\n ...args: unknown[]\n ): boolean {\n // Only traces request events\n if (event !== 'request') {\n return original.apply(this, [event, ...args]);\n }\n\n const request = args[0] as http.IncomingMessage;\n const response = args[1] as http.ServerResponse & { socket: Socket };\n const method = request.method || 'GET';\n\n instrumentation._diag.debug(\n `${component} instrumentation incomingRequest`\n );\n\n if (\n safeExecuteInTheMiddle(\n () =>\n instrumentation.getConfig().ignoreIncomingRequestHook?.(request),\n (e: unknown) => {\n if (e != null) {\n instrumentation._diag.error(\n 'caught ignoreIncomingRequestHook error: ',\n e\n );\n }\n },\n true\n )\n ) {\n return context.with(suppressTracing(context.active()), () => {\n context.bind(context.active(), request);\n context.bind(context.active(), response);\n return original.apply(this, [event, ...args]);\n });\n }\n\n const headers = request.headers;\n\n const spanAttributes = getIncomingRequestAttributes(\n request,\n {\n component: component,\n hookAttributes: instrumentation._callStartSpanHook(\n request,\n instrumentation.getConfig().startIncomingSpanHook\n ),\n enableSyntheticSourceDetection:\n instrumentation.getConfig().enableSyntheticSourceDetection || false,\n },\n instrumentation._diag\n );\n\n Object.assign(\n spanAttributes,\n instrumentation._headerCapture.server.captureRequestHeaders(\n header => request.headers[header]\n )\n );\n\n const spanOptions: SpanOptions = {\n kind: SpanKind.SERVER,\n attributes: spanAttributes,\n };\n\n const startTime = hrTime();\n\n // request method and url.scheme are both required span attributes\n const metricAttributes: Attributes = {\n [ATTR_HTTP_REQUEST_METHOD]: spanAttributes[ATTR_HTTP_REQUEST_METHOD],\n [ATTR_URL_SCHEME]: spanAttributes[ATTR_URL_SCHEME],\n };\n\n // recommended if and only if one was sent, same as span recommendation\n if (spanAttributes[ATTR_NETWORK_PROTOCOL_VERSION]) {\n metricAttributes[ATTR_NETWORK_PROTOCOL_VERSION] =\n spanAttributes[ATTR_NETWORK_PROTOCOL_VERSION];\n }\n\n const ctx = propagation.extract(ROOT_CONTEXT, headers);\n const span = instrumentation._startHttpSpan(method, spanOptions, ctx);\n const rpcMetadata: RPCMetadata = {\n type: RPCType.HTTP,\n span,\n };\n\n return context.with(\n setRPCMetadata(trace.setSpan(ctx, span), rpcMetadata),\n () => {\n context.bind(context.active(), request);\n context.bind(context.active(), response);\n\n if (instrumentation.getConfig().requestHook) {\n instrumentation._callRequestHook(span, request);\n }\n if (instrumentation.getConfig().responseHook) {\n instrumentation._callResponseHook(span, response);\n }\n\n // After 'error', no further events other than 'close' should be emitted.\n let hasError = false;\n response.on('close', () => {\n if (hasError) {\n return;\n }\n instrumentation._onServerResponseFinish(\n request,\n response,\n span,\n metricAttributes,\n startTime\n );\n });\n response.on(errorMonitor, (err: Err) => {\n hasError = true;\n instrumentation._onServerResponseError(\n span,\n metricAttributes,\n startTime,\n err\n );\n });\n\n return safeExecuteInTheMiddle(\n () => original.apply(this, [event, ...args]),\n error => {\n if (error) {\n instrumentation._onServerResponseError(\n span,\n metricAttributes,\n startTime,\n error\n );\n throw error;\n }\n }\n );\n }\n );\n };\n }\n\n private _outgoingRequestFunction(\n component: 'http' | 'https',\n original: Func<http.ClientRequest>\n ): Func<http.ClientRequest> {\n const instrumentation = this;\n return function outgoingRequest(\n this: unknown,\n options: url.URL | http.RequestOptions | string,\n ...args: unknown[]\n ): http.ClientRequest {\n if (!isValidOptionsType(options)) {\n return original.apply(this, [options, ...args]);\n }\n const extraOptions =\n typeof args[0] === 'object' &&\n (typeof options === 'string' || options instanceof url.URL)\n ? (args.shift() as http.RequestOptions)\n : undefined;\n const { method, invalidUrl, optionsParsed } = getRequestInfo(\n instrumentation._diag,\n options,\n extraOptions\n );\n\n if (\n safeExecuteInTheMiddle(\n () =>\n instrumentation\n .getConfig()\n .ignoreOutgoingRequestHook?.(optionsParsed),\n (e: unknown) => {\n if (e != null) {\n instrumentation._diag.error(\n 'caught ignoreOutgoingRequestHook error: ',\n e\n );\n }\n },\n true\n )\n ) {\n return original.apply(this, [optionsParsed, ...args]);\n }\n\n const { hostname, port } = extractHostnameAndPort(optionsParsed);\n const attributes = getOutgoingRequestAttributes(\n optionsParsed,\n {\n component,\n port,\n hostname,\n hookAttributes: instrumentation._callStartSpanHook(\n optionsParsed,\n instrumentation.getConfig().startOutgoingSpanHook\n ),\n redactedQueryParams: instrumentation.getConfig().redactedQueryParams, // Added config for adding custom query strings\n },\n instrumentation.getConfig().enableSyntheticSourceDetection || false\n );\n\n const startTime = hrTime();\n\n // request method, server address, and server port are both required span attributes\n const metricAttributes: Attributes = {\n [ATTR_HTTP_REQUEST_METHOD]: attributes[ATTR_HTTP_REQUEST_METHOD],\n [ATTR_SERVER_ADDRESS]: attributes[ATTR_SERVER_ADDRESS],\n [ATTR_SERVER_PORT]: attributes[ATTR_SERVER_PORT],\n };\n\n // required if and only if one was sent, same as span requirement\n if (attributes[ATTR_HTTP_RESPONSE_STATUS_CODE]) {\n metricAttributes[ATTR_HTTP_RESPONSE_STATUS_CODE] =\n attributes[ATTR_HTTP_RESPONSE_STATUS_CODE];\n }\n\n // recommended if and only if one was sent, same as span recommendation\n if (attributes[ATTR_NETWORK_PROTOCOL_VERSION]) {\n metricAttributes[ATTR_NETWORK_PROTOCOL_VERSION] =\n attributes[ATTR_NETWORK_PROTOCOL_VERSION];\n }\n\n const spanOptions: SpanOptions = {\n kind: SpanKind.CLIENT,\n attributes,\n };\n const span = instrumentation._startHttpSpan(method, spanOptions);\n\n const parentContext = context.active();\n const requestContext = trace.setSpan(parentContext, span);\n\n if (!optionsParsed.headers) {\n optionsParsed.headers = {};\n } else {\n // Make a copy of the headers object to avoid mutating an object the\n // caller might have a reference to.\n optionsParsed.headers = Object.assign({}, optionsParsed.headers);\n }\n propagation.inject(requestContext, optionsParsed.headers);\n\n return context.with(requestContext, () => {\n /*\n * The response callback is registered before ClientRequest is bound,\n * thus it is needed to bind it before the function call.\n */\n const cb = args[args.length - 1];\n if (typeof cb === 'function') {\n args[args.length - 1] = context.bind(parentContext, cb);\n }\n\n const request: http.ClientRequest = safeExecuteInTheMiddle(\n () => {\n if (invalidUrl) {\n // we know that the url is invalid, there's no point in injecting context as it will fail validation.\n // Passing in what the user provided will give the user an error that matches what they'd see without\n // the instrumentation.\n return original.apply(this, [options, ...args]);\n } else {\n return original.apply(this, [optionsParsed, ...args]);\n }\n },\n error => {\n if (error) {\n instrumentation._onOutgoingRequestError(\n span,\n metricAttributes,\n startTime,\n error\n );\n throw error;\n }\n }\n );\n\n instrumentation._diag.debug(\n `${component} instrumentation outgoingRequest`\n );\n context.bind(parentContext, request);\n return instrumentation._traceClientRequest(\n request,\n span,\n startTime,\n metricAttributes\n );\n });\n };\n }\n\n private _onServerResponseFinish(\n request: http.IncomingMessage,\n response: http.ServerResponse,\n span: Span,\n metricAttributes: Attributes,\n startTime: HrTime\n ) {\n const attributes = getIncomingRequestAttributesOnResponse(response);\n metricAttributes = Object.assign(\n metricAttributes,\n getIncomingStableRequestMetricAttributesOnResponse(attributes)\n );\n\n span.setAttributes(\n this._headerCapture.server.captureResponseHeaders(header =>\n response.getHeader(header)\n )\n );\n\n span.setAttributes(attributes).setStatus({\n code: parseResponseStatus(SpanKind.SERVER, response.statusCode),\n });\n\n const route = attributes[ATTR_HTTP_ROUTE];\n if (route) {\n span.updateName(`${request.method || 'GET'} ${route}`);\n }\n\n if (this.getConfig().applyCustomAttributesOnSpan) {\n safeExecuteInTheMiddle(\n () =>\n this.getConfig().applyCustomAttributesOnSpan!(\n span,\n request,\n response\n ),\n () => {},\n true\n );\n }\n\n this._closeHttpSpan(span, SpanKind.SERVER, startTime, metricAttributes);\n }\n\n private _onOutgoingRequestError(\n span: Span,\n metricAttributes: Attributes,\n startTime: HrTime,\n error: Err\n ) {\n setSpanWithError(span, error);\n metricAttributes[ATTR_ERROR_TYPE] = error.name;\n\n this._closeHttpSpan(span, SpanKind.CLIENT, startTime, metricAttributes);\n }\n\n private _onServerResponseError(\n span: Span,\n metricAttributes: Attributes,\n startTime: HrTime,\n error: Err\n ) {\n setSpanWithError(span, error);\n metricAttributes[ATTR_ERROR_TYPE] = error.name;\n\n this._closeHttpSpan(span, SpanKind.SERVER, startTime, metricAttributes);\n }\n\n private _startHttpSpan(\n name: string,\n options: SpanOptions,\n ctx = context.active()\n ) {\n /*\n * If a parent is required but not present, we use a `NoopSpan` to still\n * propagate context without recording it.\n */\n const requireParent =\n options.kind === SpanKind.CLIENT\n ? this.getConfig().requireParentforOutgoingSpans\n : this.getConfig().requireParentforIncomingSpans;\n\n let span: Span;\n const currentSpan = trace.getSpan(ctx);\n\n if (\n requireParent === true &&\n (!currentSpan || !trace.isSpanContextValid(currentSpan.spanContext()))\n ) {\n span = trace.wrapSpanContext(INVALID_SPAN_CONTEXT);\n } else if (requireParent === true && currentSpan?.spanContext().isRemote) {\n span = currentSpan;\n } else {\n span = this.tracer.startSpan(name, options, ctx);\n }\n this._spanNotEnded.add(span);\n return span;\n }\n\n private _closeHttpSpan(\n span: Span,\n spanKind: SpanKind,\n startTime: HrTime,\n metricAttributes: Attributes\n ) {\n if (!this._spanNotEnded.has(span)) {\n return;\n }\n\n span.end();\n this._spanNotEnded.delete(span);\n\n // Record metrics\n const duration = hrTimeToMilliseconds(hrTimeDuration(startTime, hrTime()));\n if (spanKind === SpanKind.SERVER) {\n this._recordServerDuration(duration, metricAttributes);\n } else if (spanKind === SpanKind.CLIENT) {\n this._recordClientDuration(duration, metricAttributes);\n }\n }\n\n private _callResponseHook(\n span: Span,\n response: http.IncomingMessage | http.ServerResponse\n ) {\n safeExecuteInTheMiddle(\n () => this.getConfig().responseHook!(span, response),\n () => {},\n true\n );\n }\n\n private _callRequestHook(\n span: Span,\n request: http.ClientRequest | http.IncomingMessage\n ) {\n safeExecuteInTheMiddle(\n () => this.getConfig().requestHook!(span, request),\n () => {},\n true\n );\n }\n\n private _callStartSpanHook(\n request: http.IncomingMessage | http.RequestOptions,\n hookFunc: Function | undefined\n ) {\n if (typeof hookFunc === 'function') {\n return safeExecuteInTheMiddle(\n () => hookFunc(request),\n () => {},\n true\n );\n }\n }\n\n private _createHeaderCapture() {\n const config = this.getConfig();\n\n return {\n client: {\n captureRequestHeaders: headerCapture(\n 'request',\n config.headersToSpanAttributes?.client?.requestHeaders ?? []\n ),\n captureResponseHeaders: headerCapture(\n 'response',\n config.headersToSpanAttributes?.client?.responseHeaders ?? []\n ),\n },\n server: {\n captureRequestHeaders: headerCapture(\n 'request',\n config.headersToSpanAttributes?.server?.requestHeaders ?? []\n ),\n captureResponseHeaders: headerCapture(\n 'response',\n config.headersToSpanAttributes?.server?.responseHeaders ?? []\n ),\n },\n };\n }\n}\n"]}
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../../src/http.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAUH,4CAS4B;AAE5B,8CAO6B;AAI7B,2BAA2B;AAE3B,uCAAoC;AACpC,oEAIwC;AACxC,mCAAsC;AACtC,8EAW6C;AAC7C,mCAaiB;AAEjB,qDAAmE;AAEnE;;GAEG;AACH,MAAa,mBAAoB,SAAQ,qCAA8C;IACrF,oCAAoC;IACnB,aAAa,GAAkB,IAAI,OAAO,EAAQ,CAAC;IAC5D,cAAc,CAAC;IACf,YAAY,GAAY,KAAK,CAAC;IAC9B,aAAa,GAAY,KAAK,CAAC;IAIvC,YAAY,SAAoC,EAAE;QAChD,KAAK,CAAC,qCAAqC,EAAE,iBAAO,EAAE,MAAM,CAAC,CAAC;QAC9D,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,oBAAoB,EAAE,CAAC;IACpD,CAAC;IAEkB,wBAAwB;QACzC,IAAI,CAAC,4BAA4B,GAAG,IAAI,CAAC,KAAK,CAAC,eAAe,CAC5D,0DAAmC,EACnC;YACE,WAAW,EAAE,mCAAmC;YAChD,IAAI,EAAE,GAAG;YACT,SAAS,EAAE,eAAS,CAAC,MAAM;YAC3B,MAAM,EAAE;gBACN,wBAAwB,EAAE;oBACxB,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC;oBAChE,GAAG,EAAE,EAAE;iBACR;aACF;SACF,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AC;IAEO,kBAAkB,CACxB,OAAmD,EACnD,QAA8B;QAE9B,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;YAClC,OAAO,IAAA,wCAAsB,EAC3B,GAAG,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,EACvB,GAAG,EAAE,GAAE,CAAC,EACR,IAAI,CACL,CAAC;SACH;IACH,CAAC;IAEO,oBAAoB;QAC1B,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;QAEhC,OAAO;YACL,MAAM,EAAE;gBACN,qBAAqB,EAAE,IAAA,qBAAa,EAClC,SAAS,EACT,MAAM,CAAC,uBAAuB,EAAE,MAAM,EAAE,cAAc,IAAI,EAAE,CAC7D;gBACD,sBAAsB,EAAE,IAAA,qBAAa,EACnC,UAAU,EACV,MAAM,CAAC,uBAAuB,EAAE,MAAM,EAAE,eAAe,IAAI,EAAE,CAC9D;aACF;YACD,MAAM,EAAE;gBACN,qBAAqB,EAAE,IAAA,qBAAa,EAClC,SAAS,EACT,MAAM,CAAC,uBAAuB,EAAE,MAAM,EAAE,cAAc,IAAI,EAAE,CAC7D;gBACD,sBAAsB,EAAE,IAAA,qBAAa,EACnC,UAAU,EACV,MAAM,CAAC,uBAAuB,EAAE,MAAM,EAAE,eAAe,IAAI,EAAE,CAC9D;aACF;SACF,CAAC;IACJ,CAAC;CACF;AAr4BD,kDAq4BC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n HrTime,\n Span,\n SpanOptions,\n SpanStatus,\n Histogram,\n Attributes,\n} from '@opentelemetry/api';\nimport {\n context,\n INVALID_SPAN_CONTEXT,\n propagation,\n ROOT_CONTEXT,\n SpanKind,\n SpanStatusCode,\n trace,\n ValueType,\n} from '@opentelemetry/api';\nimport type { RPCMetadata } from '@opentelemetry/core';\nimport {\n hrTime,\n hrTimeDuration,\n hrTimeToMilliseconds,\n suppressTracing,\n RPCType,\n setRPCMetadata,\n} from '@opentelemetry/core';\nimport type * as http from 'http';\nimport type * as https from 'https';\nimport type { Socket } from 'net';\nimport * as url from 'url';\nimport type { HttpInstrumentationConfig } from './types';\nimport { VERSION } from './version';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { errorMonitor } from 'events';\nimport {\n ATTR_ERROR_TYPE,\n ATTR_HTTP_REQUEST_METHOD,\n ATTR_HTTP_RESPONSE_STATUS_CODE,\n ATTR_NETWORK_PROTOCOL_VERSION,\n ATTR_HTTP_ROUTE,\n ATTR_SERVER_ADDRESS,\n ATTR_SERVER_PORT,\n ATTR_URL_SCHEME,\n METRIC_HTTP_CLIENT_REQUEST_DURATION,\n METRIC_HTTP_SERVER_REQUEST_DURATION,\n} from '@opentelemetry/semantic-conventions';\nimport {\n extractHostnameAndPort,\n getIncomingRequestAttributes,\n getIncomingRequestAttributesOnResponse,\n getIncomingStableRequestMetricAttributesOnResponse,\n getOutgoingRequestAttributes,\n getOutgoingRequestAttributesOnResponse,\n getOutgoingStableRequestMetricAttributesOnResponse,\n getRequestInfo,\n headerCapture,\n isValidOptionsType,\n parseResponseStatus,\n setSpanWithError,\n} from './utils';\nimport type { Err, Func, Http, HttpRequestArgs, Https } from './internal-types';\nimport { DEFAULT_QUERY_STRINGS_TO_REDACT } from './internal-types';\n\n/**\n * `node:http` and `node:https` instrumentation for OpenTelemetry\n */\nexport class HttpInstrumentation extends InstrumentationBase<HttpInstrumentationConfig> {\n /** keep track on spans not ended */\n private readonly _spanNotEnded: WeakSet<Span> = new WeakSet<Span>();\n private _headerCapture;\n private _httpPatched: boolean = false;\n private _httpsPatched: boolean = false;\n declare private _httpServerDurationHistogram: Histogram;\n declare private _httpClientDurationHistogram: Histogram;\n\n constructor(config: HttpInstrumentationConfig = {}) {\n super('@opentelemetry/instrumentation-http', VERSION, config);\n this._headerCapture = this._createHeaderCapture();\n }\n\n protected override _updateMetricInstruments() {\n this._httpServerDurationHistogram = this.meter.createHistogram(\n METRIC_HTTP_SERVER_REQUEST_DURATION,\n {\n description: 'Duration of HTTP server requests.',\n unit: 's',\n valueType: ValueType.DOUBLE,\n advice: {\n explicitBucketBoundaries: [\n 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5,\n 7.5, 10,\n ],\n },\n }\n );\n this._httpClientDurationHistogram = this.meter.createHistogram(\n METRIC_HTTP_CLIENT_REQUEST_DURATION,\n {\n description: 'Duration of HTTP client requests.',\n unit: 's',\n valueType: ValueType.DOUBLE,\n advice: {\n explicitBucketBoundaries: [\n 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5,\n 7.5, 10,\n ],\n },\n }\n );\n }\n\n private _recordServerDuration(durationMs: number, attributes: Attributes) {\n // stable histogram is counted in S\n this._httpServerDurationHistogram.record(durationMs / 1000, attributes);\n }\n\n private _recordClientDuration(durationMs: number, attributes: Attributes) {\n // stable histogram is counted in S\n this._httpClientDurationHistogram.record(durationMs / 1000, attributes);\n }\n\n override setConfig(config: HttpInstrumentationConfig = {}): void {\n super.setConfig(config);\n this._headerCapture = this._createHeaderCapture();\n }\n\n init(): [\n InstrumentationNodeModuleDefinition,\n InstrumentationNodeModuleDefinition,\n ] {\n return [this._getHttpsInstrumentation(), this._getHttpInstrumentation()];\n }\n\n private _getHttpInstrumentation() {\n return new InstrumentationNodeModuleDefinition(\n 'http',\n ['*'],\n (moduleExports: Http): Http => {\n // Guard against double-instrumentation, if loaded by both `require`\n // and `import`.\n if (this._httpPatched) {\n return moduleExports;\n }\n this._httpPatched = true;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const isESM = (moduleExports as any)[Symbol.toStringTag] === 'Module';\n\n if (!this.getConfig().disableOutgoingRequestInstrumentation) {\n const patchedRequest = this._wrap(\n moduleExports,\n 'request',\n this._getPatchOutgoingRequestFunction('http')\n ) as unknown as Func<http.ClientRequest>;\n const patchedGet = this._wrap(\n moduleExports,\n 'get',\n this._getPatchOutgoingGetFunction(patchedRequest)\n );\n if (isESM) {\n // To handle `import http from 'http'`, which returns the default\n // export, we need to set `module.default.*`.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (moduleExports as any).default.request = patchedRequest;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (moduleExports as any).default.get = patchedGet;\n }\n }\n if (!this.getConfig().disableIncomingRequestInstrumentation) {\n this._wrap(\n moduleExports.Server.prototype,\n 'emit',\n this._getPatchIncomingRequestFunction('http')\n );\n }\n return moduleExports;\n },\n (moduleExports: Http) => {\n this._httpPatched = false;\n if (moduleExports === undefined) return;\n\n if (!this.getConfig().disableOutgoingRequestInstrumentation) {\n this._unwrap(moduleExports, 'request');\n this._unwrap(moduleExports, 'get');\n }\n if (!this.getConfig().disableIncomingRequestInstrumentation) {\n this._unwrap(moduleExports.Server.prototype, 'emit');\n }\n }\n );\n }\n\n private _getHttpsInstrumentation() {\n return new InstrumentationNodeModuleDefinition(\n 'https',\n ['*'],\n (moduleExports: Https): Https => {\n // Guard against double-instrumentation, if loaded by both `require`\n // and `import`.\n if (this._httpsPatched) {\n return moduleExports;\n }\n this._httpsPatched = true;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const isESM = (moduleExports as any)[Symbol.toStringTag] === 'Module';\n\n if (!this.getConfig().disableOutgoingRequestInstrumentation) {\n const patchedRequest = this._wrap(\n moduleExports,\n 'request',\n this._getPatchHttpsOutgoingRequestFunction('https')\n ) as unknown as Func<http.ClientRequest>;\n const patchedGet = this._wrap(\n moduleExports,\n 'get',\n this._getPatchHttpsOutgoingGetFunction(patchedRequest)\n );\n if (isESM) {\n // To handle `import https from 'https'`, which returns the default\n // export, we need to set `module.default.*`.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (moduleExports as any).default.request = patchedRequest;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (moduleExports as any).default.get = patchedGet;\n }\n }\n if (!this.getConfig().disableIncomingRequestInstrumentation) {\n this._wrap(\n moduleExports.Server.prototype,\n 'emit',\n this._getPatchIncomingRequestFunction('https')\n );\n }\n return moduleExports;\n },\n (moduleExports: Https) => {\n this._httpsPatched = false;\n if (moduleExports === undefined) return;\n\n if (!this.getConfig().disableOutgoingRequestInstrumentation) {\n this._unwrap(moduleExports, 'request');\n this._unwrap(moduleExports, 'get');\n }\n if (!this.getConfig().disableIncomingRequestInstrumentation) {\n this._unwrap(moduleExports.Server.prototype, 'emit');\n }\n }\n );\n }\n\n /**\n * Creates spans for incoming requests, restoring spans' context if applied.\n */\n private _getPatchIncomingRequestFunction(component: 'http' | 'https') {\n return (\n original: (event: string, ...args: unknown[]) => boolean\n ): ((this: unknown, event: string, ...args: unknown[]) => boolean) => {\n return this._incomingRequestFunction(component, original);\n };\n }\n\n /**\n * Creates spans for outgoing requests, sending spans' context for distributed\n * tracing.\n */\n private _getPatchOutgoingRequestFunction(component: 'http' | 'https') {\n return (original: Func<http.ClientRequest>): Func<http.ClientRequest> => {\n return this._outgoingRequestFunction(component, original);\n };\n }\n\n private _getPatchOutgoingGetFunction(\n clientRequest: (\n options: http.RequestOptions | string | url.URL,\n ...args: HttpRequestArgs\n ) => http.ClientRequest\n ) {\n return (_original: Func<http.ClientRequest>): Func<http.ClientRequest> => {\n // Re-implement http.get. This needs to be done (instead of using\n // getPatchOutgoingRequestFunction to patch it) because we need to\n // set the trace context header before the returned http.ClientRequest is\n // ended. The Node.js docs state that the only differences between\n // request and get are that (1) get defaults to the HTTP GET method and\n // (2) the returned request object is ended immediately. The former is\n // already true (at least in supported Node versions up to v10), so we\n // simply follow the latter. Ref:\n // https://nodejs.org/dist/latest/docs/api/http.html#http_http_get_options_callback\n // https://github.com/googleapis/cloud-trace-nodejs/blob/master/src/instrumentations/instrumentation-http.ts#L198\n return function outgoingGetRequest<\n T extends http.RequestOptions | string | url.URL,\n >(options: T, ...args: HttpRequestArgs): http.ClientRequest {\n const req = clientRequest(options, ...args);\n req.end();\n return req;\n };\n };\n }\n\n /** Patches HTTPS outgoing requests */\n private _getPatchHttpsOutgoingRequestFunction(component: 'http' | 'https') {\n return (original: Func<http.ClientRequest>): Func<http.ClientRequest> => {\n const instrumentation = this;\n return function httpsOutgoingRequest(\n options: https.RequestOptions | string | URL,\n ...args: HttpRequestArgs\n ): http.ClientRequest {\n // Makes sure options will have default HTTPS parameters\n if (\n component === 'https' &&\n typeof options === 'object' &&\n options?.constructor?.name !== 'URL'\n ) {\n options = Object.assign({}, options);\n instrumentation._setDefaultOptions(options);\n }\n return instrumentation._getPatchOutgoingRequestFunction(component)(\n original\n )(options, ...args);\n };\n };\n }\n\n private _setDefaultOptions(options: https.RequestOptions) {\n options.protocol = options.protocol || 'https:';\n options.port = options.port || 443;\n }\n\n /** Patches HTTPS outgoing get requests */\n private _getPatchHttpsOutgoingGetFunction(\n clientRequest: (\n options: http.RequestOptions | string | URL,\n ...args: HttpRequestArgs\n ) => http.ClientRequest\n ) {\n return (original: Func<http.ClientRequest>): Func<http.ClientRequest> => {\n const instrumentation = this;\n return function httpsOutgoingRequest(\n options: https.RequestOptions | string | URL,\n ...args: HttpRequestArgs\n ): http.ClientRequest {\n return instrumentation._getPatchOutgoingGetFunction(clientRequest)(\n original\n )(options, ...args);\n };\n };\n }\n\n /**\n * Attach event listeners to a client request to end span and add span attributes.\n *\n * @param request The original request object.\n * @param span representing the current operation\n * @param startTime representing the start time of the request to calculate duration in Metric\n * @param metricAttributes metric attributes for the request duration metric\n */\n private _traceClientRequest(\n request: http.ClientRequest,\n span: Span,\n startTime: HrTime,\n metricAttributes: Attributes\n ): http.ClientRequest {\n if (this.getConfig().requestHook) {\n this._callRequestHook(span, request);\n }\n\n /**\n * Determines if the request has errored or the response has ended/errored.\n */\n let responseFinished = false;\n\n /*\n * User 'response' event listeners can be added before our listener,\n * force our listener to be the first, so response emitter is bound\n * before any user listeners are added to it.\n */\n request.prependListener(\n 'response',\n (response: http.IncomingMessage & { aborted?: boolean }) => {\n this._diag.debug('outgoingRequest on response()');\n if (request.listenerCount('response') <= 1) {\n response.resume();\n }\n const responseAttributes =\n getOutgoingRequestAttributesOnResponse(response);\n span.setAttributes(responseAttributes);\n metricAttributes = Object.assign(\n metricAttributes,\n getOutgoingStableRequestMetricAttributesOnResponse(responseAttributes)\n );\n\n if (this.getConfig().responseHook) {\n this._callResponseHook(span, response);\n }\n\n span.setAttributes(\n this._headerCapture.client.captureRequestHeaders(header =>\n request.getHeader(header)\n )\n );\n span.setAttributes(\n this._headerCapture.client.captureResponseHeaders(\n header => response.headers[header]\n )\n );\n\n context.bind(context.active(), response);\n\n const endHandler = () => {\n this._diag.debug('outgoingRequest on end()');\n if (responseFinished) {\n return;\n }\n responseFinished = true;\n let status: SpanStatus;\n\n if (response.aborted && !response.complete) {\n status = { code: SpanStatusCode.ERROR };\n } else {\n // behaves same for new and old semconv\n status = {\n code: parseResponseStatus(SpanKind.CLIENT, response.statusCode),\n };\n }\n\n span.setStatus(status);\n\n if (this.getConfig().applyCustomAttributesOnSpan) {\n safeExecuteInTheMiddle(\n () =>\n this.getConfig().applyCustomAttributesOnSpan!(\n span,\n request,\n response\n ),\n () => {},\n true\n );\n }\n\n this._closeHttpSpan(\n span,\n SpanKind.CLIENT,\n startTime,\n metricAttributes\n );\n };\n\n response.on('end', endHandler);\n response.on(errorMonitor, (error: Err) => {\n this._diag.debug('outgoingRequest on error()', error);\n if (responseFinished) {\n return;\n }\n responseFinished = true;\n this._onOutgoingRequestError(\n span,\n metricAttributes,\n startTime,\n error\n );\n });\n }\n );\n request.on('close', () => {\n this._diag.debug('outgoingRequest on request close()');\n if (request.aborted || responseFinished) {\n return;\n }\n responseFinished = true;\n this._closeHttpSpan(span, SpanKind.CLIENT, startTime, metricAttributes);\n });\n request.on(errorMonitor, (error: Err) => {\n this._diag.debug('outgoingRequest on request error()', error);\n if (responseFinished) {\n return;\n }\n responseFinished = true;\n this._onOutgoingRequestError(span, metricAttributes, startTime, error);\n });\n\n this._diag.debug('http.ClientRequest return request');\n return request;\n }\n\n private _incomingRequestFunction(\n component: 'http' | 'https',\n original: (event: string, ...args: unknown[]) => boolean\n ) {\n const instrumentation = this;\n return function incomingRequest(\n this: unknown,\n event: string,\n ...args: unknown[]\n ): boolean {\n // Only traces request events\n if (event !== 'request') {\n return original.apply(this, [event, ...args]);\n }\n\n const request = args[0] as http.IncomingMessage;\n const response = args[1] as http.ServerResponse & { socket: Socket };\n const method = request.method || 'GET';\n\n instrumentation._diag.debug(\n `${component} instrumentation incomingRequest`\n );\n\n if (\n safeExecuteInTheMiddle(\n () =>\n instrumentation.getConfig().ignoreIncomingRequestHook?.(request),\n (e: unknown) => {\n if (e != null) {\n instrumentation._diag.error(\n 'caught ignoreIncomingRequestHook error: ',\n e\n );\n }\n },\n true\n )\n ) {\n return context.with(suppressTracing(context.active()), () => {\n context.bind(context.active(), request);\n context.bind(context.active(), response);\n return original.apply(this, [event, ...args]);\n });\n }\n\n const headers = request.headers;\n\n const spanAttributes = getIncomingRequestAttributes(\n request,\n {\n component: component,\n hookAttributes: instrumentation._callStartSpanHook(\n request,\n instrumentation.getConfig().startIncomingSpanHook\n ),\n enableSyntheticSourceDetection:\n instrumentation.getConfig().enableSyntheticSourceDetection || false,\n redactedQueryParams:\n instrumentation.getConfig().redactedQueryParamsServer ??\n Array.from(DEFAULT_QUERY_STRINGS_TO_REDACT),\n },\n instrumentation._diag\n );\n\n Object.assign(\n spanAttributes,\n instrumentation._headerCapture.server.captureRequestHeaders(\n header => request.headers[header]\n )\n );\n\n const spanOptions: SpanOptions = {\n kind: SpanKind.SERVER,\n attributes: spanAttributes,\n };\n\n const startTime = hrTime();\n\n // request method and url.scheme are both required span attributes\n const metricAttributes: Attributes = {\n [ATTR_HTTP_REQUEST_METHOD]: spanAttributes[ATTR_HTTP_REQUEST_METHOD],\n [ATTR_URL_SCHEME]: spanAttributes[ATTR_URL_SCHEME],\n };\n\n // recommended if and only if one was sent, same as span recommendation\n if (spanAttributes[ATTR_NETWORK_PROTOCOL_VERSION]) {\n metricAttributes[ATTR_NETWORK_PROTOCOL_VERSION] =\n spanAttributes[ATTR_NETWORK_PROTOCOL_VERSION];\n }\n\n const ctx = propagation.extract(ROOT_CONTEXT, headers);\n const span = instrumentation._startHttpSpan(method, spanOptions, ctx);\n const rpcMetadata: RPCMetadata = {\n type: RPCType.HTTP,\n span,\n };\n\n return context.with(\n setRPCMetadata(trace.setSpan(ctx, span), rpcMetadata),\n () => {\n context.bind(context.active(), request);\n context.bind(context.active(), response);\n\n if (instrumentation.getConfig().requestHook) {\n instrumentation._callRequestHook(span, request);\n }\n if (instrumentation.getConfig().responseHook) {\n instrumentation._callResponseHook(span, response);\n }\n\n // After 'error', no further events other than 'close' should be emitted.\n let hasError = false;\n response.on('close', () => {\n if (hasError) {\n return;\n }\n instrumentation._onServerResponseFinish(\n request,\n response,\n span,\n metricAttributes,\n startTime\n );\n });\n response.on(errorMonitor, (err: Err) => {\n hasError = true;\n instrumentation._onServerResponseError(\n span,\n metricAttributes,\n startTime,\n err\n );\n });\n\n return safeExecuteInTheMiddle(\n () => original.apply(this, [event, ...args]),\n error => {\n if (error) {\n instrumentation._onServerResponseError(\n span,\n metricAttributes,\n startTime,\n error\n );\n throw error;\n }\n }\n );\n }\n );\n };\n }\n\n private _outgoingRequestFunction(\n component: 'http' | 'https',\n original: Func<http.ClientRequest>\n ): Func<http.ClientRequest> {\n const instrumentation = this;\n return function outgoingRequest(\n this: unknown,\n options: url.URL | http.RequestOptions | string,\n ...args: unknown[]\n ): http.ClientRequest {\n if (!isValidOptionsType(options)) {\n return original.apply(this, [options, ...args]);\n }\n const extraOptions =\n typeof args[0] === 'object' &&\n (typeof options === 'string' || options instanceof url.URL)\n ? (args.shift() as http.RequestOptions)\n : undefined;\n const { method, invalidUrl, optionsParsed } = getRequestInfo(\n instrumentation._diag,\n options,\n extraOptions\n );\n\n if (\n safeExecuteInTheMiddle(\n () =>\n instrumentation\n .getConfig()\n .ignoreOutgoingRequestHook?.(optionsParsed),\n (e: unknown) => {\n if (e != null) {\n instrumentation._diag.error(\n 'caught ignoreOutgoingRequestHook error: ',\n e\n );\n }\n },\n true\n )\n ) {\n return original.apply(this, [optionsParsed, ...args]);\n }\n\n const { hostname, port } = extractHostnameAndPort(optionsParsed);\n const attributes = getOutgoingRequestAttributes(\n optionsParsed,\n {\n component,\n port,\n hostname,\n hookAttributes: instrumentation._callStartSpanHook(\n optionsParsed,\n instrumentation.getConfig().startOutgoingSpanHook\n ),\n redactedQueryParams: instrumentation.getConfig().redactedQueryParams, // Added config for adding custom query strings\n },\n instrumentation.getConfig().enableSyntheticSourceDetection || false\n );\n\n const startTime = hrTime();\n\n // request method, server address, and server port are both required span attributes\n const metricAttributes: Attributes = {\n [ATTR_HTTP_REQUEST_METHOD]: attributes[ATTR_HTTP_REQUEST_METHOD],\n [ATTR_SERVER_ADDRESS]: attributes[ATTR_SERVER_ADDRESS],\n [ATTR_SERVER_PORT]: attributes[ATTR_SERVER_PORT],\n };\n\n // required if and only if one was sent, same as span requirement\n if (attributes[ATTR_HTTP_RESPONSE_STATUS_CODE]) {\n metricAttributes[ATTR_HTTP_RESPONSE_STATUS_CODE] =\n attributes[ATTR_HTTP_RESPONSE_STATUS_CODE];\n }\n\n // recommended if and only if one was sent, same as span recommendation\n if (attributes[ATTR_NETWORK_PROTOCOL_VERSION]) {\n metricAttributes[ATTR_NETWORK_PROTOCOL_VERSION] =\n attributes[ATTR_NETWORK_PROTOCOL_VERSION];\n }\n\n const spanOptions: SpanOptions = {\n kind: SpanKind.CLIENT,\n attributes,\n };\n const span = instrumentation._startHttpSpan(method, spanOptions);\n\n const parentContext = context.active();\n const requestContext = trace.setSpan(parentContext, span);\n\n if (!optionsParsed.headers) {\n optionsParsed.headers = {};\n } else {\n // Make a copy of the headers object to avoid mutating an object the\n // caller might have a reference to.\n optionsParsed.headers = Object.assign({}, optionsParsed.headers);\n }\n propagation.inject(requestContext, optionsParsed.headers);\n\n return context.with(requestContext, () => {\n /*\n * The response callback is registered before ClientRequest is bound,\n * thus it is needed to bind it before the function call.\n */\n const cb = args[args.length - 1];\n if (typeof cb === 'function') {\n args[args.length - 1] = context.bind(parentContext, cb);\n }\n\n const request: http.ClientRequest = safeExecuteInTheMiddle(\n () => {\n if (invalidUrl) {\n // we know that the url is invalid, there's no point in injecting context as it will fail validation.\n // Passing in what the user provided will give the user an error that matches what they'd see without\n // the instrumentation.\n return original.apply(this, [options, ...args]);\n } else {\n return original.apply(this, [optionsParsed, ...args]);\n }\n },\n error => {\n if (error) {\n instrumentation._onOutgoingRequestError(\n span,\n metricAttributes,\n startTime,\n error\n );\n throw error;\n }\n }\n );\n\n instrumentation._diag.debug(\n `${component} instrumentation outgoingRequest`\n );\n context.bind(parentContext, request);\n return instrumentation._traceClientRequest(\n request,\n span,\n startTime,\n metricAttributes\n );\n });\n };\n }\n\n private _onServerResponseFinish(\n request: http.IncomingMessage,\n response: http.ServerResponse,\n span: Span,\n metricAttributes: Attributes,\n startTime: HrTime\n ) {\n const attributes = getIncomingRequestAttributesOnResponse(response);\n metricAttributes = Object.assign(\n metricAttributes,\n getIncomingStableRequestMetricAttributesOnResponse(attributes)\n );\n\n span.setAttributes(\n this._headerCapture.server.captureResponseHeaders(header =>\n response.getHeader(header)\n )\n );\n\n span.setAttributes(attributes).setStatus({\n code: parseResponseStatus(SpanKind.SERVER, response.statusCode),\n });\n\n const route = attributes[ATTR_HTTP_ROUTE];\n if (route) {\n span.updateName(`${request.method || 'GET'} ${route}`);\n }\n\n if (this.getConfig().applyCustomAttributesOnSpan) {\n safeExecuteInTheMiddle(\n () =>\n this.getConfig().applyCustomAttributesOnSpan!(\n span,\n request,\n response\n ),\n () => {},\n true\n );\n }\n\n this._closeHttpSpan(span, SpanKind.SERVER, startTime, metricAttributes);\n }\n\n private _onOutgoingRequestError(\n span: Span,\n metricAttributes: Attributes,\n startTime: HrTime,\n error: Err\n ) {\n setSpanWithError(span, error);\n metricAttributes[ATTR_ERROR_TYPE] = error.name;\n\n this._closeHttpSpan(span, SpanKind.CLIENT, startTime, metricAttributes);\n }\n\n private _onServerResponseError(\n span: Span,\n metricAttributes: Attributes,\n startTime: HrTime,\n error: Err\n ) {\n setSpanWithError(span, error);\n metricAttributes[ATTR_ERROR_TYPE] = error.name;\n\n this._closeHttpSpan(span, SpanKind.SERVER, startTime, metricAttributes);\n }\n\n private _startHttpSpan(\n name: string,\n options: SpanOptions,\n ctx = context.active()\n ) {\n /*\n * If a parent is required but not present, we use a `NoopSpan` to still\n * propagate context without recording it.\n */\n const requireParent =\n options.kind === SpanKind.CLIENT\n ? this.getConfig().requireParentforOutgoingSpans\n : this.getConfig().requireParentforIncomingSpans;\n\n let span: Span;\n const currentSpan = trace.getSpan(ctx);\n\n if (\n requireParent === true &&\n (!currentSpan || !trace.isSpanContextValid(currentSpan.spanContext()))\n ) {\n span = trace.wrapSpanContext(INVALID_SPAN_CONTEXT);\n } else if (requireParent === true && currentSpan?.spanContext().isRemote) {\n span = currentSpan;\n } else {\n span = this.tracer.startSpan(name, options, ctx);\n }\n this._spanNotEnded.add(span);\n return span;\n }\n\n private _closeHttpSpan(\n span: Span,\n spanKind: SpanKind,\n startTime: HrTime,\n metricAttributes: Attributes\n ) {\n if (!this._spanNotEnded.has(span)) {\n return;\n }\n\n span.end();\n this._spanNotEnded.delete(span);\n\n // Record metrics\n const duration = hrTimeToMilliseconds(hrTimeDuration(startTime, hrTime()));\n if (spanKind === SpanKind.SERVER) {\n this._recordServerDuration(duration, metricAttributes);\n } else if (spanKind === SpanKind.CLIENT) {\n this._recordClientDuration(duration, metricAttributes);\n }\n }\n\n private _callResponseHook(\n span: Span,\n response: http.IncomingMessage | http.ServerResponse\n ) {\n safeExecuteInTheMiddle(\n () => this.getConfig().responseHook!(span, response),\n () => {},\n true\n );\n }\n\n private _callRequestHook(\n span: Span,\n request: http.ClientRequest | http.IncomingMessage\n ) {\n safeExecuteInTheMiddle(\n () => this.getConfig().requestHook!(span, request),\n () => {},\n true\n );\n }\n\n private _callStartSpanHook(\n request: http.IncomingMessage | http.RequestOptions,\n hookFunc: Function | undefined\n ) {\n if (typeof hookFunc === 'function') {\n return safeExecuteInTheMiddle(\n () => hookFunc(request),\n () => {},\n true\n );\n }\n }\n\n private _createHeaderCapture() {\n const config = this.getConfig();\n\n return {\n client: {\n captureRequestHeaders: headerCapture(\n 'request',\n config.headersToSpanAttributes?.client?.requestHeaders ?? []\n ),\n captureResponseHeaders: headerCapture(\n 'response',\n config.headersToSpanAttributes?.client?.responseHeaders ?? []\n ),\n },\n server: {\n captureRequestHeaders: headerCapture(\n 'request',\n config.headersToSpanAttributes?.server?.requestHeaders ?? []\n ),\n captureResponseHeaders: headerCapture(\n 'response',\n config.headersToSpanAttributes?.server?.responseHeaders ?? []\n ),\n },\n };\n }\n}\n"]}
@@ -38,5 +38,5 @@ export declare const STR_REDACTED = "REDACTED";
38
38
  /**
39
39
  * List of URL query keys that are considered sensitive and whose value should be redacted.
40
40
  */
41
- export declare const DEFAULT_QUERY_STRINGS_TO_REDACT: readonly ["sig", "Signature", "AWSAccessKeyId", "X-Goog-Signature"];
41
+ export declare const DEFAULT_QUERY_STRINGS_TO_REDACT: readonly ["sig", "Signature", "AWSAccessKeyId", "X-Goog-Signature", "X-Amz-Signature", "X-Amz-Credential", "X-Amz-Security-Token"];
42
42
  //# sourceMappingURL=internal-types.d.ts.map
@@ -25,5 +25,8 @@ exports.DEFAULT_QUERY_STRINGS_TO_REDACT = [
25
25
  'Signature',
26
26
  'AWSAccessKeyId',
27
27
  'X-Goog-Signature',
28
+ 'X-Amz-Signature',
29
+ 'X-Amz-Credential',
30
+ 'X-Amz-Security-Token',
28
31
  ];
29
32
  //# sourceMappingURL=internal-types.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"internal-types.js","sourceRoot":"","sources":["../../src/internal-types.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAoCH;;GAEG;AACU,QAAA,oBAAoB,GAAG,CAAC,UAAU,CAAC,CAAC;AAEjD;;GAEG;AACU,QAAA,mBAAmB,GAAG,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;AAE5D;;GAEG;AACU,QAAA,YAAY,GAAG,UAAU,CAAC;AAEvC;;GAEG;AACU,QAAA,+BAA+B,GAAG;IAC7C,KAAK;IACL,WAAW;IACX,gBAAgB;IAChB,kBAAkB;CACV,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type * as http from 'http';\nimport type * as https from 'https';\nimport type { get, IncomingMessage, request } from 'http';\nimport type * as url from 'url';\n\nexport type IgnoreMatcher = string | RegExp | ((url: string) => boolean);\nexport type HttpCallback = (res: IncomingMessage) => void;\nexport type RequestFunction = typeof request;\nexport type GetFunction = typeof get;\n\nexport type HttpCallbackOptional = HttpCallback | undefined;\n\n// from node 10+\nexport type RequestSignature = [http.RequestOptions, HttpCallbackOptional] &\n HttpCallback;\n\nexport type HttpRequestArgs = Array<HttpCallbackOptional | RequestSignature>;\n\nexport type ParsedRequestOptions =\n | (http.RequestOptions & Partial<url.UrlWithParsedQuery>)\n | http.RequestOptions;\nexport type Http = typeof http;\nexport type Https = typeof https;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Func<T> = (...args: any[]) => T;\n\nexport interface Err extends Error {\n errno?: number;\n code?: string;\n path?: string;\n syscall?: string;\n stack?: string;\n}\n\n/**\n * Names of possible synthetic test sources.\n */\nexport const SYNTHETIC_TEST_NAMES = ['alwayson'];\n\n/**\n * Names of possible synthetic bot sources.\n */\nexport const SYNTHETIC_BOT_NAMES = ['googlebot', 'bingbot'];\n\n/**\n * REDACTED string used to replace sensitive information in URLs.\n */\nexport const STR_REDACTED = 'REDACTED';\n\n/**\n * List of URL query keys that are considered sensitive and whose value should be redacted.\n */\nexport const DEFAULT_QUERY_STRINGS_TO_REDACT = [\n 'sig',\n 'Signature',\n 'AWSAccessKeyId',\n 'X-Goog-Signature',\n] as const;\n"]}
1
+ {"version":3,"file":"internal-types.js","sourceRoot":"","sources":["../../src/internal-types.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAoCH;;GAEG;AACU,QAAA,oBAAoB,GAAG,CAAC,UAAU,CAAC,CAAC;AAEjD;;GAEG;AACU,QAAA,mBAAmB,GAAG,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;AAE5D;;GAEG;AACU,QAAA,YAAY,GAAG,UAAU,CAAC;AAEvC;;GAEG;AACU,QAAA,+BAA+B,GAAG;IAC7C,KAAK;IACL,WAAW;IACX,gBAAgB;IAChB,kBAAkB;IAClB,iBAAiB;IACjB,kBAAkB;IAClB,sBAAsB;CACd,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type * as http from 'http';\nimport type * as https from 'https';\nimport type { get, IncomingMessage, request } from 'http';\nimport type * as url from 'url';\n\nexport type IgnoreMatcher = string | RegExp | ((url: string) => boolean);\nexport type HttpCallback = (res: IncomingMessage) => void;\nexport type RequestFunction = typeof request;\nexport type GetFunction = typeof get;\n\nexport type HttpCallbackOptional = HttpCallback | undefined;\n\n// from node 10+\nexport type RequestSignature = [http.RequestOptions, HttpCallbackOptional] &\n HttpCallback;\n\nexport type HttpRequestArgs = Array<HttpCallbackOptional | RequestSignature>;\n\nexport type ParsedRequestOptions =\n | (http.RequestOptions & Partial<url.UrlWithParsedQuery>)\n | http.RequestOptions;\nexport type Http = typeof http;\nexport type Https = typeof https;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Func<T> = (...args: any[]) => T;\n\nexport interface Err extends Error {\n errno?: number;\n code?: string;\n path?: string;\n syscall?: string;\n stack?: string;\n}\n\n/**\n * Names of possible synthetic test sources.\n */\nexport const SYNTHETIC_TEST_NAMES = ['alwayson'];\n\n/**\n * Names of possible synthetic bot sources.\n */\nexport const SYNTHETIC_BOT_NAMES = ['googlebot', 'bingbot'];\n\n/**\n * REDACTED string used to replace sensitive information in URLs.\n */\nexport const STR_REDACTED = 'REDACTED';\n\n/**\n * List of URL query keys that are considered sensitive and whose value should be redacted.\n */\nexport const DEFAULT_QUERY_STRINGS_TO_REDACT = [\n 'sig',\n 'Signature',\n 'AWSAccessKeyId',\n 'X-Goog-Signature',\n 'X-Amz-Signature',\n 'X-Amz-Credential',\n 'X-Amz-Security-Token',\n] as const;\n"]}
@@ -94,12 +94,22 @@ export interface HttpInstrumentationConfig extends InstrumentationConfig {
94
94
  **/
95
95
  enableSyntheticSourceDetection?: boolean;
96
96
  /**
97
- * [Optional] Additional query parameters to redact.
97
+ * [Optional] Query parameters to redact on outgoing (client) spans.
98
98
  * Use this to specify custom query strings that contain sensitive information.
99
99
  * These will replace/overwrite the default query strings that are to be redacted.
100
- * @example default strings ['sig','Signature','AWSAccessKeyId','X-Goog-Signature']
100
+ * When omitted, defaults to a built-in list of known sensitive parameter
101
+ * names; see the package README for the current list.
102
+ * Set to an empty array to disable client-side query parameter redaction entirely.
101
103
  * @experimental
102
104
  */
103
105
  redactedQueryParams?: string[];
106
+ /**
107
+ * [Optional] Query parameters to redact on incoming (server) spans.
108
+ * When omitted, defaults to a built-in list of known sensitive parameter
109
+ * names; see the package README for the current list.
110
+ * Set to an empty array to disable server-side query parameter redaction entirely.
111
+ * @experimental
112
+ */
113
+ redactedQueryParamsServer?: string[];
104
114
  }
105
115
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { Span, Attributes } from '@opentelemetry/api';\nimport type {\n ClientRequest,\n IncomingMessage,\n ServerResponse,\n RequestOptions,\n} from 'http';\nimport type { InstrumentationConfig } from '@opentelemetry/instrumentation';\n\nexport interface HttpCustomAttributeFunction {\n (\n span: Span,\n request: ClientRequest | IncomingMessage,\n response: IncomingMessage | ServerResponse\n ): void;\n}\n\n/**\n * Called with each incoming request. Return `true` to skip creating a server\n * span for that request.\n */\nexport interface IgnoreIncomingRequestFunction {\n (request: IncomingMessage): boolean;\n}\n\n/**\n * Called with each outgoing request's parsed options. Return `true` to skip\n * creating a client span for that request.\n */\nexport interface IgnoreOutgoingRequestFunction {\n (request: RequestOptions): boolean;\n}\n\n/**\n * Called with the active span and request before the request is handled.\n */\nexport interface HttpRequestCustomAttributeFunction {\n (span: Span, request: ClientRequest | IncomingMessage): void;\n}\n\n/**\n * Called with the active span and response before the response is handled.\n */\nexport interface HttpResponseCustomAttributeFunction {\n (span: Span, response: IncomingMessage | ServerResponse): void;\n}\n\n/**\n * Called before an incoming request span is started. Returned attributes are\n * added to the new server span.\n */\nexport interface StartIncomingSpanCustomAttributeFunction {\n (request: IncomingMessage): Attributes;\n}\n\n/**\n * Called with an outgoing request's parsed options before the span is started.\n * Returned attributes are added to the new client span.\n */\nexport interface StartOutgoingSpanCustomAttributeFunction {\n (request: RequestOptions): Attributes;\n}\n\n/**\n * Options available for the HTTP instrumentation (see [documentation](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation-http#http-instrumentation-options))\n */\nexport interface HttpInstrumentationConfig extends InstrumentationConfig {\n /** Do not trace incoming requests for which this function returns `true`. */\n ignoreIncomingRequestHook?: IgnoreIncomingRequestFunction;\n /** Do not trace outgoing requests for which this function returns `true`. */\n ignoreOutgoingRequestHook?: IgnoreOutgoingRequestFunction;\n /** If set to true, incoming requests will not be instrumented at all. */\n disableIncomingRequestInstrumentation?: boolean;\n /** If set to true, outgoing requests will not be instrumented at all. */\n disableOutgoingRequestInstrumentation?: boolean;\n /** Function for adding custom attributes after response is handled */\n applyCustomAttributesOnSpan?: HttpCustomAttributeFunction;\n /** Function for adding custom attributes before request is handled */\n requestHook?: HttpRequestCustomAttributeFunction;\n /** Function for adding custom attributes before response is handled */\n responseHook?: HttpResponseCustomAttributeFunction;\n /** Function for adding custom attributes before a span is started in incomingRequest */\n startIncomingSpanHook?: StartIncomingSpanCustomAttributeFunction;\n /** Function for adding custom attributes before a span is started in outgoingRequest */\n startOutgoingSpanHook?: StartOutgoingSpanCustomAttributeFunction;\n /**\n * The primary server name of the matched virtual host.\n * @deprecated No longer used. Stable HTTP semantic conventions do not include\n * the `http.server_name` attribute; this option has no effect.\n */\n serverName?: string;\n /** Require parent to create span for outgoing requests */\n requireParentforOutgoingSpans?: boolean;\n /** Require parent to create span for incoming requests */\n requireParentforIncomingSpans?: boolean;\n /** Map the following HTTP headers to span attributes. */\n headersToSpanAttributes?: {\n client?: { requestHeaders?: string[]; responseHeaders?: string[] };\n server?: { requestHeaders?: string[]; responseHeaders?: string[] };\n };\n /**\n * Enable automatic population of synthetic source type based on the user-agent header\n * @experimental\n **/\n enableSyntheticSourceDetection?: boolean;\n /**\n * [Optional] Additional query parameters to redact.\n * Use this to specify custom query strings that contain sensitive information.\n * These will replace/overwrite the default query strings that are to be redacted.\n * @example default strings ['sig','Signature','AWSAccessKeyId','X-Goog-Signature']\n * @experimental\n */\n redactedQueryParams?: string[];\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { Span, Attributes } from '@opentelemetry/api';\nimport type {\n ClientRequest,\n IncomingMessage,\n ServerResponse,\n RequestOptions,\n} from 'http';\nimport type { InstrumentationConfig } from '@opentelemetry/instrumentation';\n\nexport interface HttpCustomAttributeFunction {\n (\n span: Span,\n request: ClientRequest | IncomingMessage,\n response: IncomingMessage | ServerResponse\n ): void;\n}\n\n/**\n * Called with each incoming request. Return `true` to skip creating a server\n * span for that request.\n */\nexport interface IgnoreIncomingRequestFunction {\n (request: IncomingMessage): boolean;\n}\n\n/**\n * Called with each outgoing request's parsed options. Return `true` to skip\n * creating a client span for that request.\n */\nexport interface IgnoreOutgoingRequestFunction {\n (request: RequestOptions): boolean;\n}\n\n/**\n * Called with the active span and request before the request is handled.\n */\nexport interface HttpRequestCustomAttributeFunction {\n (span: Span, request: ClientRequest | IncomingMessage): void;\n}\n\n/**\n * Called with the active span and response before the response is handled.\n */\nexport interface HttpResponseCustomAttributeFunction {\n (span: Span, response: IncomingMessage | ServerResponse): void;\n}\n\n/**\n * Called before an incoming request span is started. Returned attributes are\n * added to the new server span.\n */\nexport interface StartIncomingSpanCustomAttributeFunction {\n (request: IncomingMessage): Attributes;\n}\n\n/**\n * Called with an outgoing request's parsed options before the span is started.\n * Returned attributes are added to the new client span.\n */\nexport interface StartOutgoingSpanCustomAttributeFunction {\n (request: RequestOptions): Attributes;\n}\n\n/**\n * Options available for the HTTP instrumentation (see [documentation](https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation-http#http-instrumentation-options))\n */\nexport interface HttpInstrumentationConfig extends InstrumentationConfig {\n /** Do not trace incoming requests for which this function returns `true`. */\n ignoreIncomingRequestHook?: IgnoreIncomingRequestFunction;\n /** Do not trace outgoing requests for which this function returns `true`. */\n ignoreOutgoingRequestHook?: IgnoreOutgoingRequestFunction;\n /** If set to true, incoming requests will not be instrumented at all. */\n disableIncomingRequestInstrumentation?: boolean;\n /** If set to true, outgoing requests will not be instrumented at all. */\n disableOutgoingRequestInstrumentation?: boolean;\n /** Function for adding custom attributes after response is handled */\n applyCustomAttributesOnSpan?: HttpCustomAttributeFunction;\n /** Function for adding custom attributes before request is handled */\n requestHook?: HttpRequestCustomAttributeFunction;\n /** Function for adding custom attributes before response is handled */\n responseHook?: HttpResponseCustomAttributeFunction;\n /** Function for adding custom attributes before a span is started in incomingRequest */\n startIncomingSpanHook?: StartIncomingSpanCustomAttributeFunction;\n /** Function for adding custom attributes before a span is started in outgoingRequest */\n startOutgoingSpanHook?: StartOutgoingSpanCustomAttributeFunction;\n /**\n * The primary server name of the matched virtual host.\n * @deprecated No longer used. Stable HTTP semantic conventions do not include\n * the `http.server_name` attribute; this option has no effect.\n */\n serverName?: string;\n /** Require parent to create span for outgoing requests */\n requireParentforOutgoingSpans?: boolean;\n /** Require parent to create span for incoming requests */\n requireParentforIncomingSpans?: boolean;\n /** Map the following HTTP headers to span attributes. */\n headersToSpanAttributes?: {\n client?: { requestHeaders?: string[]; responseHeaders?: string[] };\n server?: { requestHeaders?: string[]; responseHeaders?: string[] };\n };\n /**\n * Enable automatic population of synthetic source type based on the user-agent header\n * @experimental\n **/\n enableSyntheticSourceDetection?: boolean;\n /**\n * [Optional] Query parameters to redact on outgoing (client) spans.\n * Use this to specify custom query strings that contain sensitive information.\n * These will replace/overwrite the default query strings that are to be redacted.\n * When omitted, defaults to a built-in list of known sensitive parameter\n * names; see the package README for the current list.\n * Set to an empty array to disable client-side query parameter redaction entirely.\n * @experimental\n */\n redactedQueryParams?: string[];\n /**\n * [Optional] Query parameters to redact on incoming (server) spans.\n * When omitted, defaults to a built-in list of known sensitive parameter\n * names; see the package README for the current list.\n * Set to an empty array to disable server-side query parameter redaction entirely.\n * @experimental\n */\n redactedQueryParamsServer?: string[];\n}\n"]}
@@ -4,6 +4,11 @@ import { SpanStatusCode, SpanKind } from '@opentelemetry/api';
4
4
  import type { IncomingHttpHeaders, IncomingMessage, OutgoingHttpHeaders, RequestOptions, ServerResponse } from 'http';
5
5
  import * as url from 'url';
6
6
  import type { Err, IgnoreMatcher, ParsedRequestOptions } from './internal-types';
7
+ /**
8
+ * Redacts sensitive query parameters from a query string (without leading '?').
9
+ * Returns the input unchanged if it cannot be parsed.
10
+ */
11
+ export declare const redactQueryString: (searchParams: URLSearchParams, paramsToRedact: string[]) => string;
7
12
  /**
8
13
  * Get an absolute url
9
14
  */
@@ -84,6 +89,7 @@ export declare const getIncomingRequestAttributes: (request: IncomingMessage, op
84
89
  component: 'http' | 'https';
85
90
  hookAttributes?: Attributes;
86
91
  enableSyntheticSourceDetection: boolean;
92
+ redactedQueryParams?: string[];
87
93
  }, logger: DiagLogger) => Attributes;
88
94
  /**
89
95
  * Returns incoming request attributes scoped to the response data
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.headerCapture = exports.getIncomingStableRequestMetricAttributesOnResponse = exports.getIncomingRequestAttributesOnResponse = exports.getIncomingRequestAttributes = exports.getRemoteClientAddress = exports.getOutgoingStableRequestMetricAttributesOnResponse = exports.getOutgoingRequestAttributesOnResponse = exports.getOutgoingRequestAttributes = exports.extractHostnameAndPort = exports.isValidOptionsType = exports.getRequestInfo = exports.isCompressed = exports.setSpanWithError = exports.satisfiesPattern = exports.parseResponseStatus = exports.getAbsoluteUrl = void 0;
3
+ exports.headerCapture = exports.getIncomingStableRequestMetricAttributesOnResponse = exports.getIncomingRequestAttributesOnResponse = exports.getIncomingRequestAttributes = exports.getRemoteClientAddress = exports.getOutgoingStableRequestMetricAttributesOnResponse = exports.getOutgoingRequestAttributesOnResponse = exports.getOutgoingRequestAttributes = exports.extractHostnameAndPort = exports.isValidOptionsType = exports.getRequestInfo = exports.isCompressed = exports.setSpanWithError = exports.satisfiesPattern = exports.parseResponseStatus = exports.getAbsoluteUrl = exports.redactQueryString = void 0;
4
4
  const api_1 = require("@opentelemetry/api");
5
5
  const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
6
6
  const semconv_1 = require("./semconv");
@@ -10,6 +10,21 @@ const internal_types_1 = require("./internal-types");
10
10
  const internal_types_2 = require("./internal-types");
11
11
  // eslint-disable-next-line @typescript-eslint/no-require-imports
12
12
  const forwardedParse = require("forwarded-parse");
13
+ const defaultQueryStringsToRedact = Array.from(internal_types_2.DEFAULT_QUERY_STRINGS_TO_REDACT);
14
+ /**
15
+ * Redacts sensitive query parameters from a query string (without leading '?').
16
+ * Returns the input unchanged if it cannot be parsed.
17
+ */
18
+ const redactQueryString = (searchParams, paramsToRedact) => {
19
+ const params = new URLSearchParams(searchParams);
20
+ for (const param of paramsToRedact) {
21
+ if (params.has(param)) {
22
+ params.set(param, internal_types_2.STR_REDACTED);
23
+ }
24
+ }
25
+ return params.toString();
26
+ };
27
+ exports.redactQueryString = redactQueryString;
13
28
  /**
14
29
  * Get an absolute url
15
30
  */
@@ -27,17 +42,11 @@ const getAbsoluteUrl = (requestUrl, headers, fallbackProtocol = 'http:', redacte
27
42
  port !== '443') {
28
43
  host += `:${port}`;
29
44
  }
30
- // Redact sensitive query parameters
31
45
  if (path.includes('?')) {
32
46
  try {
33
47
  const parsedUrl = new URL(path, 'http://localhost');
34
- const sensitiveParamsToRedact = redactedQueryParams || [];
35
- for (const sensitiveParam of sensitiveParamsToRedact) {
36
- if (parsedUrl.searchParams.get(sensitiveParam)) {
37
- parsedUrl.searchParams.set(sensitiveParam, internal_types_2.STR_REDACTED);
38
- }
39
- }
40
- path = `${parsedUrl.pathname}${parsedUrl.search}`;
48
+ const redacted = (0, exports.redactQueryString)(parsedUrl.searchParams, redactedQueryParams);
49
+ path = `${parsedUrl.pathname}?${redacted}`;
41
50
  }
42
51
  catch {
43
52
  // Ignore error, as the path was not a valid URL.
@@ -502,7 +511,7 @@ function getInfoFromIncomingMessage(component, request, logger) {
502
511
  * @param {{ component: string, hookAttributes?: Attributes, enableSyntheticSourceDetection: boolean }} options used to pass data needed to create attributes
503
512
  */
504
513
  const getIncomingRequestAttributes = (request, options, logger) => {
505
- const { component, enableSyntheticSourceDetection, hookAttributes } = options;
514
+ const { component, enableSyntheticSourceDetection, hookAttributes, redactedQueryParams, } = options;
506
515
  const { headers, method } = request;
507
516
  const { 'user-agent': userAgent } = headers;
508
517
  const parsedUrl = getInfoFromIncomingMessage(component, request, logger);
@@ -524,7 +533,8 @@ const getIncomingRequestAttributes = (request, options, logger) => {
524
533
  }
525
534
  if (parsedUrl.search) {
526
535
  // Remove leading '?' from URL search (https://developer.mozilla.org/en-US/docs/Web/API/URL/search).
527
- attributes[semantic_conventions_1.ATTR_URL_QUERY] = parsedUrl.search.slice(1);
536
+ const paramsToRedact = redactedQueryParams ?? defaultQueryStringsToRedact;
537
+ attributes[semantic_conventions_1.ATTR_URL_QUERY] = (0, exports.redactQueryString)(new URLSearchParams(parsedUrl.search.slice(1)), paramsToRedact);
528
538
  }
529
539
  if (remoteClientAddress != null) {
530
540
  attributes[semantic_conventions_1.ATTR_CLIENT_ADDRESS] = remoteClientAddress;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";;;AAUA,4CAAuE;AACvE,8EAiB6C;AAC7C,uCAImB;AASnB,8CAA8D;AAC9D,2BAA2B;AAM3B,qDAA6E;AAC7E,qDAG0B;AAC1B,iEAAiE;AACjE,kDAAmD;AAEnD;;GAEG;AACI,MAAM,cAAc,GAAG,CAC5B,UAAuC,EACvC,OAAkD,EAClD,gBAAgB,GAAG,OAAO,EAC1B,sBAAgC,KAAK,CAAC,IAAI,CAAC,gDAA+B,CAAC,EACnE,EAAE;IACV,MAAM,YAAY,GAAG,UAAU,IAAI,EAAE,CAAC;IACtC,MAAM,QAAQ,GAAG,YAAY,CAAC,QAAQ,IAAI,gBAAgB,CAAC;IAC3D,MAAM,IAAI,GAAG,CAAC,YAAY,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC;IAClD,IAAI,IAAI,GAAG,YAAY,CAAC,IAAI,IAAI,GAAG,CAAC;IACpC,IAAI,IAAI,GACN,YAAY,CAAC,IAAI,IAAI,YAAY,CAAC,QAAQ,IAAI,OAAO,CAAC,IAAI,IAAI,WAAW,CAAC;IAC5E,kDAAkD;IAClD,gEAAgE;IAChE,IACG,IAAe,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QACpC,IAAI;QACJ,IAAI,KAAK,IAAI;QACb,IAAI,KAAK,KAAK,EACd;QACA,IAAI,IAAI,IAAI,IAAI,EAAE,CAAC;KACpB;IACD,oCAAoC;IACpC,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;QACtB,IAAI;YACF,MAAM,SAAS,GAAG,I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,sCA+BC;AAED,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC;IAC5B,wEAAwE;IACxE,KAAK;IACL,MAAM;IACN,MAAM;IACN,KAAK;IACL,QAAQ;IACR,SAAS;IACT,SAAS;IACT,OAAO;IAEP,yDAAyD;IACzD,OAAO;IAEP,qFAAqF;IACrF,OAAO;CACR,CAAC,CAAC;AAEH,SAAS,eAAe,CAAC,MAAsB;IAC7C,IAAI,MAAM,IAAI,IAAI,EAAE;QAClB,OAAO,KAAK,CAAC;KACd;IAED,MAAM,KAAK,GAAG,MAAM,CAAC,WAAW,EAAE,CAAC;IACnC,IAAI,aAAa,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE;QAC5B,OAAO,KAAK,CAAC;KACd;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,SAAS,oBAAoB,CAAC,MAAc;IAC1C,IAAI;QACF,OAAO,cAAc,CAAC,MAAM,CAAC,CAAC;KAC/B;IAAC,MAAM;QACN,OAAO,EAAE,CAAC;KACX;AACH,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n Attributes,\n Span,\n DiagLogger,\n AttributeValue,\n} from '@opentelemetry/api';\nimport { SpanStatusCode, context, SpanKind } from '@opentelemetry/api';\nimport {\n ATTR_CLIENT_ADDRESS,\n ATTR_ERROR_TYPE,\n ATTR_HTTP_REQUEST_METHOD,\n ATTR_HTTP_REQUEST_METHOD_ORIGINAL,\n ATTR_HTTP_RESPONSE_STATUS_CODE,\n ATTR_HTTP_ROUTE,\n ATTR_NETWORK_PEER_ADDRESS,\n ATTR_NETWORK_PEER_PORT,\n ATTR_NETWORK_PROTOCOL_VERSION,\n ATTR_SERVER_ADDRESS,\n ATTR_SERVER_PORT,\n ATTR_URL_FULL,\n ATTR_URL_PATH,\n ATTR_URL_QUERY,\n ATTR_URL_SCHEME,\n ATTR_USER_AGENT_ORIGINAL,\n} from '@opentelemetry/semantic-conventions';\nimport {\n ATTR_USER_AGENT_SYNTHETIC_TYPE,\n USER_AGENT_SYNTHETIC_TYPE_VALUE_BOT,\n USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST,\n} from './semconv';\nimport type {\n IncomingHttpHeaders,\n IncomingMessage,\n OutgoingHttpHeader,\n OutgoingHttpHeaders,\n RequestOptions,\n ServerResponse,\n} from 'http';\nimport { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport * as url from 'url';\nimport type {\n Err,\n IgnoreMatcher,\n ParsedRequestOptions,\n} from './internal-types';\nimport { SYNTHETIC_BOT_NAMES, SYNTHETIC_TEST_NAMES } from './internal-types';\nimport {\n DEFAULT_QUERY_STRINGS_TO_REDACT,\n STR_REDACTED,\n} from './internal-types';\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport forwardedParse = require('forwarded-parse');\n\n/**\n * Get an absolute url\n */\nexport const getAbsoluteUrl = (\n requestUrl: ParsedRequestOptions | null,\n headers: IncomingHttpHeaders | OutgoingHttpHeaders,\n fallbackProtocol = 'http:',\n redactedQueryParams: string[] = Array.from(DEFAULT_QUERY_STRINGS_TO_REDACT)\n): string => {\n const reqUrlObject = requestUrl || {};\n const protocol = reqUrlObject.protocol || fallbackProtocol;\n const port = (reqUrlObject.port || '').toString();\n let path = reqUrlObject.path || '/';\n let host =\n reqUrlObject.host || reqUrlObject.hostname || headers.host || 'localhost';\n // if there is no port in host and there is a port\n // it should be displayed if it's not 80 and 443 (default ports)\n if (\n (host as string).indexOf(':') === -1 &&\n port &&\n port !== '80' &&\n port !== '443'\n ) {\n host += `:${port}`;\n }\n // Redact sensitive query parameters\n if (path.includes('?')) {\n try {\n const parsedUrl = new URL(path, 'http://localhost');\n const sensitiveParamsToRedact: string[] = redactedQueryParams || [];\n\n for (const sensitiveParam of sensitiveParamsToRedact) {\n if (parsedUrl.searchParams.get(sensitiveParam)) {\n parsedUrl.searchParams.set(sensitiveParam, STR_REDACTED);\n }\n }\n\n path = `${parsedUrl.pathname}${parsedUrl.search}`;\n } catch {\n // Ignore error, as the path was not a valid URL.\n }\n }\n const authPart = reqUrlObject.auth ? `${STR_REDACTED}:${STR_REDACTED}@` : '';\n return `${protocol}//${authPart}${host}${path}`;\n};\n\n/**\n * Parse status code from HTTP response. [More details](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/data-http.md#status)\n */\nexport const parseResponseStatus = (\n kind: SpanKind,\n statusCode?: number\n): SpanStatusCode => {\n const upperBound = kind === SpanKind.CLIENT ? 400 : 500;\n // 1xx, 2xx, 3xx are OK on client and server\n // 4xx is OK on server\n if (statusCode && statusCode >= 100 && statusCode < upperBound) {\n return SpanStatusCode.UNSET;\n }\n\n // All other codes are error\n return SpanStatusCode.ERROR;\n};\n\n/**\n * Check whether the given obj match pattern\n * @param constant e.g URL of request\n * @param pattern Match pattern\n */\nexport const satisfiesPattern = (\n constant: string,\n pattern: IgnoreMatcher\n): boolean => {\n if (typeof pattern === 'string') {\n return pattern === constant;\n } else if (pattern instanceof RegExp) {\n return pattern.test(constant);\n } else if (typeof pattern === 'function') {\n return pattern(constant);\n } else {\n throw new TypeError('Pattern is in unsupported datatype');\n }\n};\n\n/**\n * Sets the span with the error passed in params\n * @param {Span} span the span that need to be set\n * @param {Error} error error that will be set to span\n */\nexport const setSpanWithError = (span: Span, error: Err): void => {\n const message = error.message;\n span.setAttribute(ATTR_ERROR_TYPE, error.name);\n span.setStatus({ code: SpanStatusCode.ERROR, message });\n span.recordException(error);\n};\n\nexport const isCompressed = (\n headers: OutgoingHttpHeaders | IncomingHttpHeaders\n): boolean => {\n const encoding = headers['content-encoding'];\n\n return !!encoding && encoding !== 'identity';\n};\n\n/**\n * Mimics Node.js conversion of URL strings to RequestOptions expected by\n * `http.request` and `https.request` APIs.\n *\n * See https://github.com/nodejs/node/blob/2505e217bba05fc581b572c685c5cf280a16c5a3/lib/internal/url.js#L1415-L1437\n *\n * @param stringUrl\n * @throws TypeError if the URL is not valid.\n */\nfunction stringUrlToHttpOptions(\n stringUrl: string\n): RequestOptions & { pathname: string } {\n // This is heavily inspired by Node.js handling of the same situation, trying\n // to follow it as closely as possible while keeping in mind that we only\n // deal with string URLs, not URL objects.\n const {\n hostname,\n pathname,\n port,\n username,\n password,\n search,\n protocol,\n hash,\n href,\n origin,\n host,\n } = new URL(stringUrl);\n\n const options: RequestOptions & {\n pathname: string;\n hash: string;\n search: string;\n href: string;\n origin: string;\n } = {\n protocol: protocol,\n hostname:\n hostname && hostname[0] === '[' ? hostname.slice(1, -1) : hostname,\n hash: hash,\n search: search,\n pathname: pathname,\n path: `${pathname || ''}${search || ''}`,\n href: href,\n origin: origin,\n host: host,\n };\n if (port !== '') {\n options.port = Number(port);\n }\n if (username || password) {\n options.auth = `${decodeURIComponent(username)}:${decodeURIComponent(\n password\n )}`;\n }\n return options;\n}\n\n/**\n * Makes sure options is an url object\n * return an object with default value and parsed options\n * @param logger component logger\n * @param options original options for the request\n * @param [extraOptions] additional options for the request\n */\nexport const getRequestInfo = (\n logger: DiagLogger,\n options: url.URL | RequestOptions | string,\n extraOptions?: RequestOptions\n): {\n origin: string;\n pathname: string;\n method: string;\n invalidUrl: boolean;\n optionsParsed: RequestOptions;\n} => {\n let pathname: string;\n let origin: string;\n let optionsParsed: RequestOptions;\n let invalidUrl = false;\n if (typeof options === 'string') {\n try {\n const convertedOptions = stringUrlToHttpOptions(options);\n optionsParsed = convertedOptions;\n pathname = convertedOptions.pathname || '/';\n } catch (e) {\n invalidUrl = true;\n logger.verbose(\n 'Unable to parse URL provided to HTTP request, using fallback to determine path. Original error:',\n e\n );\n // for backward compatibility with how url.parse() behaved.\n optionsParsed = {\n path: options,\n };\n pathname = optionsParsed.path || '/';\n }\n\n origin = `${optionsParsed.protocol || 'http:'}//${optionsParsed.host}`;\n if (extraOptions !== undefined) {\n Object.assign(optionsParsed, extraOptions);\n }\n } else if (options instanceof url.URL) {\n optionsParsed = {\n protocol: options.protocol,\n hostname:\n typeof options.hostname === 'string' && options.hostname.startsWith('[')\n ? options.hostname.slice(1, -1)\n : options.hostname,\n path: `${options.pathname || ''}${options.search || ''}`,\n };\n if (options.port !== '') {\n optionsParsed.port = Number(options.port);\n }\n if (options.username || options.password) {\n optionsParsed.auth = `${options.username}:${options.password}`;\n }\n pathname = options.pathname;\n origin = options.origin;\n if (extraOptions !== undefined) {\n Object.assign(optionsParsed, extraOptions);\n }\n } else {\n optionsParsed = Object.assign(\n { protocol: options.host ? 'http:' : undefined },\n options\n );\n\n const hostname =\n optionsParsed.host ||\n (optionsParsed.port != null\n ? `${optionsParsed.hostname}${optionsParsed.port}`\n : optionsParsed.hostname);\n origin = `${optionsParsed.protocol || 'http:'}//${hostname}`;\n\n pathname = (options as url.URL).pathname;\n if (!pathname && optionsParsed.path) {\n try {\n const parsedUrl = new URL(optionsParsed.path, origin);\n pathname = parsedUrl.pathname || '/';\n } catch {\n pathname = '/';\n }\n }\n }\n\n // some packages return method in lowercase..\n // ensure upperCase for consistency\n const method = optionsParsed.method\n ? optionsParsed.method.toUpperCase()\n : 'GET';\n\n return { origin, pathname, method, optionsParsed, invalidUrl };\n};\n\n/**\n * Makes sure options is of type string or object\n * @param options for the request\n */\nexport const isValidOptionsType = (options: unknown): boolean => {\n if (!options) {\n return false;\n }\n\n const type = typeof options;\n return type === 'string' || (type === 'object' && !Array.isArray(options));\n};\n\nexport const extractHostnameAndPort = (\n requestOptions: Pick<\n ParsedRequestOptions,\n 'hostname' | 'host' | 'port' | 'protocol'\n >\n): { hostname: string; port: number | string } => {\n if (requestOptions.hostname && requestOptions.port) {\n return { hostname: requestOptions.hostname, port: requestOptions.port };\n }\n const matches = requestOptions.host?.match(/^([^:/ ]+)(:\\d{1,5})?/) || null;\n const hostname =\n requestOptions.hostname || (matches === null ? 'localhost' : matches[1]);\n let port = requestOptions.port;\n if (!port) {\n if (matches && matches[2]) {\n // remove the leading \":\". The extracted port would be something like \":8080\"\n port = matches[2].substring(1);\n } else {\n port = requestOptions.protocol === 'https:' ? '443' : '80';\n }\n }\n return { hostname, port };\n};\n\n/**\n * Returns outgoing request attributes scoped to the options passed to the request\n * @param {ParsedRequestOptions} requestOptions the same options used to make the request\n * @param {{ component: string, hostname: string, hookAttributes?: Attributes }} options used to pass data needed to create attributes\n */\nexport const getOutgoingRequestAttributes = (\n requestOptions: ParsedRequestOptions,\n options: {\n component: string;\n hostname: string;\n port: string | number;\n hookAttributes?: Attributes;\n redactedQueryParams?: string[];\n },\n enableSyntheticSourceDetection: boolean\n): Attributes => {\n const hostname = options.hostname;\n const port = options.port;\n const method = requestOptions.method ?? 'GET';\n const normalizedMethod = normalizeMethod(method);\n const headers = (requestOptions.headers || {}) as OutgoingHttpHeaders;\n const userAgent = headers['user-agent'];\n const urlFull = getAbsoluteUrl(\n requestOptions,\n headers,\n `${options.component}:`,\n options.redactedQueryParams\n );\n\n const attributes: Attributes = {\n // Required attributes\n [ATTR_HTTP_REQUEST_METHOD]: normalizedMethod,\n [ATTR_SERVER_ADDRESS]: hostname,\n [ATTR_SERVER_PORT]: Number(port),\n [ATTR_URL_FULL]: urlFull,\n [ATTR_USER_AGENT_ORIGINAL]: userAgent,\n // leaving out protocol version, it is not yet negotiated\n // leaving out protocol name, it is only required when protocol version is set\n // retries and redirects not supported\n\n // Opt-in attributes left off for now\n };\n\n // conditionally required if request method required case normalization\n if (method !== normalizedMethod) {\n attributes[ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = method;\n }\n\n if (enableSyntheticSourceDetection && userAgent) {\n attributes[ATTR_USER_AGENT_SYNTHETIC_TYPE] = getSyntheticType(userAgent);\n }\n return Object.assign(attributes, options.hookAttributes);\n};\n\n/**\n * Returns the type of synthetic source based on the user agent\n * @param {OutgoingHttpHeader} userAgent the user agent string\n */\nconst getSyntheticType = (\n userAgent: OutgoingHttpHeader\n): AttributeValue | undefined => {\n const userAgentString: string = String(userAgent).toLowerCase();\n for (const name of SYNTHETIC_TEST_NAMES) {\n if (userAgentString.includes(name)) {\n return USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST;\n }\n }\n for (const name of SYNTHETIC_BOT_NAMES) {\n if (userAgentString.includes(name)) {\n return USER_AGENT_SYNTHETIC_TYPE_VALUE_BOT;\n }\n }\n return;\n};\n\n/**\n * Returns outgoing request attributes scoped to the response data\n * @param {IncomingMessage} response the response object\n */\nexport const getOutgoingRequestAttributesOnResponse = (\n response: IncomingMessage\n): Attributes => {\n const { statusCode, socket } = response;\n const attributes: Attributes = {};\n\n if (statusCode != null) {\n attributes[ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode;\n }\n\n if (socket) {\n const { remoteAddress, remotePort } = socket;\n\n // Recommended\n attributes[ATTR_NETWORK_PEER_ADDRESS] = remoteAddress;\n attributes[ATTR_NETWORK_PEER_PORT] = remotePort;\n attributes[ATTR_NETWORK_PROTOCOL_VERSION] = response.httpVersion;\n }\n return attributes;\n};\n\n/**\n * Returns outgoing request Metric attributes scoped to the response data\n * @param {Attributes} spanAttributes the span attributes\n */\nexport const getOutgoingStableRequestMetricAttributesOnResponse = (\n spanAttributes: Attributes\n): Attributes => {\n const metricAttributes: Attributes = {};\n\n if (spanAttributes[ATTR_NETWORK_PROTOCOL_VERSION]) {\n metricAttributes[ATTR_NETWORK_PROTOCOL_VERSION] =\n spanAttributes[ATTR_NETWORK_PROTOCOL_VERSION];\n }\n\n const statusCode = spanAttributes[ATTR_HTTP_RESPONSE_STATUS_CODE];\n if (statusCode) {\n metricAttributes[ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode;\n if (\n typeof statusCode === 'number' &&\n statusCode >= 400 &&\n statusCode < 600\n ) {\n metricAttributes[ATTR_ERROR_TYPE] ??= String(statusCode);\n }\n }\n return metricAttributes;\n};\n\nfunction parseHostHeader(\n hostHeader: string,\n proto?: string\n): { host: string; port?: string } {\n const parts = hostHeader.split(':');\n\n // no semicolon implies ipv4 dotted syntax or host name without port\n // x.x.x.x\n // example.com\n if (parts.length === 1) {\n if (proto === 'http') {\n return { host: parts[0], port: '80' };\n }\n\n if (proto === 'https') {\n return { host: parts[0], port: '443' };\n }\n\n return { host: parts[0] };\n }\n\n // single semicolon implies ipv4 dotted syntax or host name with port\n // x.x.x.x:yyyy\n // example.com:yyyy\n if (parts.length === 2) {\n return {\n host: parts[0],\n port: parts[1],\n };\n }\n\n // more than 2 parts implies ipv6 syntax with multiple colons\n // [x:x:x:x:x:x:x:x]\n // [x:x:x:x:x:x:x:x]:yyyy\n if (parts[0].startsWith('[')) {\n if (parts[parts.length - 1].endsWith(']')) {\n if (proto === 'http') {\n return { host: hostHeader, port: '80' };\n }\n\n if (proto === 'https') {\n return { host: hostHeader, port: '443' };\n }\n } else if (parts[parts.length - 2].endsWith(']')) {\n return {\n host: parts.slice(0, -1).join(':'),\n port: parts[parts.length - 1],\n };\n }\n }\n\n // if nothing above matches just return the host header\n return { host: hostHeader };\n}\n\n/**\n * Get server.address and port according to http semconv 1.27\n * https://github.com/open-telemetry/semantic-conventions/blob/bf0a2c1134f206f034408b201dbec37960ed60ec/docs/http/http-spans.md#setting-serveraddress-and-serverport-attributes\n */\nfunction getServerAddress(\n request: IncomingMessage,\n component: 'http' | 'https'\n): { host: string; port?: string } | null {\n const forwardedHeader = request.headers['forwarded'];\n if (forwardedHeader) {\n for (const entry of parseForwardedHeader(forwardedHeader)) {\n if (entry.host) {\n return parseHostHeader(entry.host, entry.proto);\n }\n }\n }\n\n const xForwardedHost = request.headers['x-forwarded-host'];\n if (typeof xForwardedHost === 'string') {\n if (typeof request.headers['x-forwarded-proto'] === 'string') {\n return parseHostHeader(\n xForwardedHost,\n request.headers['x-forwarded-proto']\n );\n }\n\n if (Array.isArray(request.headers['x-forwarded-proto'])) {\n return parseHostHeader(\n xForwardedHost,\n request.headers['x-forwarded-proto'][0]\n );\n }\n\n return parseHostHeader(xForwardedHost);\n } else if (\n Array.isArray(xForwardedHost) &&\n typeof xForwardedHost[0] === 'string' &&\n xForwardedHost[0].length > 0\n ) {\n if (typeof request.headers['x-forwarded-proto'] === 'string') {\n return parseHostHeader(\n xForwardedHost[0],\n request.headers['x-forwarded-proto']\n );\n }\n\n if (Array.isArray(request.headers['x-forwarded-proto'])) {\n return parseHostHeader(\n xForwardedHost[0],\n request.headers['x-forwarded-proto'][0]\n );\n }\n\n return parseHostHeader(xForwardedHost[0]);\n }\n\n const host = request.headers['host'];\n if (typeof host === 'string' && host.length > 0) {\n return parseHostHeader(host, component);\n }\n\n return null;\n}\n\n/**\n * Get server.address and port according to http semconv 1.27\n * https://github.com/open-telemetry/semantic-conventions/blob/bf0a2c1134f206f034408b201dbec37960ed60ec/docs/http/http-spans.md#setting-serveraddress-and-serverport-attributes\n */\nexport function getRemoteClientAddress(\n request: IncomingMessage\n): string | null {\n const forwardedHeader = request.headers['forwarded'];\n if (forwardedHeader) {\n for (const entry of parseForwardedHeader(forwardedHeader)) {\n if (entry.for) {\n return removePortFromAddress(entry.for);\n }\n }\n }\n\n const xForwardedFor = request.headers['x-forwarded-for'];\n if (xForwardedFor) {\n let xForwardedForVal;\n if (typeof xForwardedFor === 'string') {\n xForwardedForVal = xForwardedFor;\n } else if (Array.isArray(xForwardedFor)) {\n xForwardedForVal = xForwardedFor[0];\n }\n\n if (typeof xForwardedForVal === 'string') {\n xForwardedForVal = xForwardedForVal.split(',')[0].trim();\n return removePortFromAddress(xForwardedForVal);\n }\n }\n\n const remote = request.socket.remoteAddress;\n if (remote) {\n return remote;\n }\n\n return null;\n}\n\nfunction removePortFromAddress(input: string): string {\n // This function can be replaced with SocketAddress.parse() once the minimum\n // supported Node.js version allows it.\n try {\n const { hostname: address } = new URL(`http://${input}`);\n\n if (address.startsWith('[') && address.endsWith(']')) {\n return address.slice(1, -1);\n }\n\n return address;\n } catch {\n return input;\n }\n}\n\nfunction getInfoFromIncomingMessage(\n component: 'http' | 'https',\n request: IncomingMessage,\n logger: DiagLogger\n): { pathname?: string; search?: string; toString: () => string } {\n try {\n if (request.headers.host) {\n return new URL(\n request.url ?? '/',\n `${component}://${request.headers.host}`\n );\n } else {\n const unsafeParsedUrl = new URL(\n request.url ?? '/',\n // using localhost as a workaround to still use the URL constructor for parsing\n `${component}://localhost`\n );\n // since we use localhost as a workaround, ensure we hide the rest of the properties to avoid\n // our workaround leaking though.\n return {\n pathname: unsafeParsedUrl.pathname,\n search: unsafeParsedUrl.search,\n toString: function () {\n // we cannot use the result of unsafeParsedUrl.toString as it's potentially wrong.\n return unsafeParsedUrl.pathname + unsafeParsedUrl.search;\n },\n };\n }\n } catch (e) {\n // something is wrong, use undefined - this *should* never happen, logging\n // for troubleshooting in case it does happen.\n logger.verbose('Unable to get URL from request', e);\n return {};\n }\n}\n\n/**\n * Returns incoming request attributes scoped to the request data\n * @param {IncomingMessage} request the request object\n * @param {{ component: string, hookAttributes?: Attributes, enableSyntheticSourceDetection: boolean }} options used to pass data needed to create attributes\n */\nexport const getIncomingRequestAttributes = (\n request: IncomingMessage,\n options: {\n component: 'http' | 'https';\n hookAttributes?: Attributes;\n enableSyntheticSourceDetection: boolean;\n },\n logger: DiagLogger\n): Attributes => {\n const { component, enableSyntheticSourceDetection, hookAttributes } = options;\n const { headers, method } = request;\n const { 'user-agent': userAgent } = headers;\n const parsedUrl = getInfoFromIncomingMessage(component, request, logger);\n\n // Stable attributes are used.\n const normalizedMethod = normalizeMethod(method);\n const serverAddress = getServerAddress(request, component);\n const remoteClientAddress = getRemoteClientAddress(request);\n\n const attributes: Attributes = {\n [ATTR_HTTP_REQUEST_METHOD]: normalizedMethod,\n [ATTR_URL_SCHEME]: component,\n [ATTR_SERVER_ADDRESS]: serverAddress?.host,\n [ATTR_NETWORK_PEER_ADDRESS]: request.socket.remoteAddress,\n [ATTR_NETWORK_PEER_PORT]: request.socket.remotePort,\n [ATTR_NETWORK_PROTOCOL_VERSION]: request.httpVersion,\n [ATTR_USER_AGENT_ORIGINAL]: userAgent,\n };\n\n if (parsedUrl.pathname != null) {\n attributes[ATTR_URL_PATH] = parsedUrl.pathname;\n }\n\n if (parsedUrl.search) {\n // Remove leading '?' from URL search (https://developer.mozilla.org/en-US/docs/Web/API/URL/search).\n attributes[ATTR_URL_QUERY] = parsedUrl.search.slice(1);\n }\n\n if (remoteClientAddress != null) {\n attributes[ATTR_CLIENT_ADDRESS] = remoteClientAddress;\n }\n\n if (serverAddress?.port != null) {\n attributes[ATTR_SERVER_PORT] = Number(serverAddress.port);\n }\n\n // Conditionally required if request method required case normalization.\n if (method !== normalizedMethod) {\n attributes[ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = method;\n }\n\n if (enableSyntheticSourceDetection && userAgent) {\n attributes[ATTR_USER_AGENT_SYNTHETIC_TYPE] = getSyntheticType(userAgent);\n }\n\n return Object.assign(attributes, hookAttributes);\n};\n\n/**\n * Returns incoming request attributes scoped to the response data\n * @param {(ServerResponse & { socket: Socket; })} response the response object\n */\nexport const getIncomingRequestAttributesOnResponse = (\n response: ServerResponse\n): Attributes => {\n const { statusCode } = response;\n\n const attributes: Attributes = {\n [ATTR_HTTP_RESPONSE_STATUS_CODE]: statusCode,\n };\n\n const rpcMetadata = getRPCMetadata(context.active());\n if (rpcMetadata?.type === RPCType.HTTP && rpcMetadata.route !== undefined) {\n attributes[ATTR_HTTP_ROUTE] = rpcMetadata.route;\n }\n\n return attributes;\n};\n\n/**\n * Returns incoming stable request Metric attributes scoped to the request data\n * @param {Attributes} spanAttributes the span attributes\n */\nexport const getIncomingStableRequestMetricAttributesOnResponse = (\n spanAttributes: Attributes\n): Attributes => {\n const metricAttributes: Attributes = {};\n if (spanAttributes[ATTR_HTTP_ROUTE] !== undefined) {\n metricAttributes[ATTR_HTTP_ROUTE] = spanAttributes[ATTR_HTTP_ROUTE];\n }\n\n // required if and only if one was sent, same as span requirement\n const statusCode = spanAttributes[ATTR_HTTP_RESPONSE_STATUS_CODE];\n if (statusCode) {\n metricAttributes[ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode;\n if (\n typeof statusCode === 'number' &&\n statusCode >= 500 &&\n statusCode < 600\n ) {\n metricAttributes[ATTR_ERROR_TYPE] ??= String(statusCode);\n }\n }\n\n return metricAttributes;\n};\n\nexport function headerCapture(type: 'request' | 'response', headers: string[]) {\n const normalizedHeaders = new Map<string, string>();\n for (let i = 0, len = headers.length; i < len; i++) {\n const capturedHeader = headers[i].toLowerCase();\n normalizedHeaders.set(capturedHeader, capturedHeader);\n }\n\n return (\n getHeader: (key: string) => undefined | string | string[] | number\n ): Attributes => {\n const attributes: Attributes = {};\n for (const capturedHeader of normalizedHeaders.keys()) {\n const value = getHeader(capturedHeader);\n\n if (value === undefined) {\n continue;\n }\n\n const normalizedHeader = normalizedHeaders.get(capturedHeader);\n const key = `http.${type}.header.${normalizedHeader}`;\n\n if (typeof value === 'string') {\n attributes[key] = [value];\n } else if (Array.isArray(value)) {\n attributes[key] = value;\n } else {\n attributes[key] = [value];\n }\n }\n return attributes;\n };\n}\n\nconst KNOWN_METHODS = new Set([\n // methods from https://www.rfc-editor.org/rfc/rfc9110.html#name-methods\n 'GET',\n 'HEAD',\n 'POST',\n 'PUT',\n 'DELETE',\n 'CONNECT',\n 'OPTIONS',\n 'TRACE',\n\n // PATCH from https://www.rfc-editor.org/rfc/rfc5789.html\n 'PATCH',\n\n // QUERY from https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/\n 'QUERY',\n]);\n\nfunction normalizeMethod(method?: string | null) {\n if (method == null) {\n return 'GET';\n }\n\n const upper = method.toUpperCase();\n if (KNOWN_METHODS.has(upper)) {\n return upper;\n }\n\n return '_OTHER';\n}\n\nfunction parseForwardedHeader(header: string): Record<string, string>[] {\n try {\n return forwardedParse(header);\n } catch {\n return [];\n }\n}\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";;;AAUA,4CAAuE;AACvE,8EAiB6C;AAC7C,uCAImB;AASnB,8CAA8D;AAC9D,2BAA2B;AAM3B,qDAA6E;AAC7E,qDAG0B;AAC1B,iEAAiE;AACjE,kDAAmD;AAEnD,MAAM,2BAA2B,GAAG,KAAK,CAAC,IAAI,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AAG,IAAI,GAAG,CAAC;IAC5B,wEAAwE;IACxE,KAAK;IACL,MAAM;IACN,MAAM;IACN,KAAK;IACL,QAAQ;IACR,SAAS;IACT,SAAS;IACT,OAAO;IAEP,yDAAyD;IACzD,OAAO;IAEP,qFAAqF;IACrF,OAAO;CACR,CAAC,CAAC;AAEH,SAAS,eAAe,CAAC,MAAsB;IAC7C,IAAI,MAAM,IAAI,IAAI,EAAE;QAClB,OAAO,KAAK,CAAC;KACd;IAED,MAAM,KAAK,GAAG,MAAM,CAAC,WAAW,EAAE,CAAC;IACnC,IAAI,aAAa,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE;QAC5B,OAAO,KAAK,CAAC;KACd;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,SAAS,oBAAoB,CAAC,MAAc;IAC1C,IAAI;QACF,OAAO,cAAc,CAAC,MAAM,CAAC,CAAC;KAC/B;IAAC,MAAM;QACN,OAAO,EAAE,CAAC;KACX;AACH,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type {\n Attributes,\n Span,\n DiagLogger,\n AttributeValue,\n} from '@opentelemetry/api';\nimport { SpanStatusCode, context, SpanKind } from '@opentelemetry/api';\nimport {\n ATTR_CLIENT_ADDRESS,\n ATTR_ERROR_TYPE,\n ATTR_HTTP_REQUEST_METHOD,\n ATTR_HTTP_REQUEST_METHOD_ORIGINAL,\n ATTR_HTTP_RESPONSE_STATUS_CODE,\n ATTR_HTTP_ROUTE,\n ATTR_NETWORK_PEER_ADDRESS,\n ATTR_NETWORK_PEER_PORT,\n ATTR_NETWORK_PROTOCOL_VERSION,\n ATTR_SERVER_ADDRESS,\n ATTR_SERVER_PORT,\n ATTR_URL_FULL,\n ATTR_URL_PATH,\n ATTR_URL_QUERY,\n ATTR_URL_SCHEME,\n ATTR_USER_AGENT_ORIGINAL,\n} from '@opentelemetry/semantic-conventions';\nimport {\n ATTR_USER_AGENT_SYNTHETIC_TYPE,\n USER_AGENT_SYNTHETIC_TYPE_VALUE_BOT,\n USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST,\n} from './semconv';\nimport type {\n IncomingHttpHeaders,\n IncomingMessage,\n OutgoingHttpHeader,\n OutgoingHttpHeaders,\n RequestOptions,\n ServerResponse,\n} from 'http';\nimport { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport * as url from 'url';\nimport type {\n Err,\n IgnoreMatcher,\n ParsedRequestOptions,\n} from './internal-types';\nimport { SYNTHETIC_BOT_NAMES, SYNTHETIC_TEST_NAMES } from './internal-types';\nimport {\n DEFAULT_QUERY_STRINGS_TO_REDACT,\n STR_REDACTED,\n} from './internal-types';\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport forwardedParse = require('forwarded-parse');\n\nconst defaultQueryStringsToRedact = Array.from(DEFAULT_QUERY_STRINGS_TO_REDACT);\n\n/**\n * Redacts sensitive query parameters from a query string (without leading '?').\n * Returns the input unchanged if it cannot be parsed.\n */\nexport const redactQueryString = (\n searchParams: URLSearchParams,\n paramsToRedact: string[]\n): string => {\n const params = new URLSearchParams(searchParams);\n for (const param of paramsToRedact) {\n if (params.has(param)) {\n params.set(param, STR_REDACTED);\n }\n }\n return params.toString();\n};\n\n/**\n * Get an absolute url\n */\nexport const getAbsoluteUrl = (\n requestUrl: ParsedRequestOptions | null,\n headers: IncomingHttpHeaders | OutgoingHttpHeaders,\n fallbackProtocol = 'http:',\n redactedQueryParams: string[] = Array.from(DEFAULT_QUERY_STRINGS_TO_REDACT)\n): string => {\n const reqUrlObject = requestUrl || {};\n const protocol = reqUrlObject.protocol || fallbackProtocol;\n const port = (reqUrlObject.port || '').toString();\n let path = reqUrlObject.path || '/';\n let host =\n reqUrlObject.host || reqUrlObject.hostname || headers.host || 'localhost';\n // if there is no port in host and there is a port\n // it should be displayed if it's not 80 and 443 (default ports)\n if (\n (host as string).indexOf(':') === -1 &&\n port &&\n port !== '80' &&\n port !== '443'\n ) {\n host += `:${port}`;\n }\n if (path.includes('?')) {\n try {\n const parsedUrl = new URL(path, 'http://localhost');\n const redacted = redactQueryString(\n parsedUrl.searchParams,\n redactedQueryParams\n );\n path = `${parsedUrl.pathname}?${redacted}`;\n } catch {\n // Ignore error, as the path was not a valid URL.\n }\n }\n const authPart = reqUrlObject.auth ? `${STR_REDACTED}:${STR_REDACTED}@` : '';\n return `${protocol}//${authPart}${host}${path}`;\n};\n\n/**\n * Parse status code from HTTP response. [More details](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/data-http.md#status)\n */\nexport const parseResponseStatus = (\n kind: SpanKind,\n statusCode?: number\n): SpanStatusCode => {\n const upperBound = kind === SpanKind.CLIENT ? 400 : 500;\n // 1xx, 2xx, 3xx are OK on client and server\n // 4xx is OK on server\n if (statusCode && statusCode >= 100 && statusCode < upperBound) {\n return SpanStatusCode.UNSET;\n }\n\n // All other codes are error\n return SpanStatusCode.ERROR;\n};\n\n/**\n * Check whether the given obj match pattern\n * @param constant e.g URL of request\n * @param pattern Match pattern\n */\nexport const satisfiesPattern = (\n constant: string,\n pattern: IgnoreMatcher\n): boolean => {\n if (typeof pattern === 'string') {\n return pattern === constant;\n } else if (pattern instanceof RegExp) {\n return pattern.test(constant);\n } else if (typeof pattern === 'function') {\n return pattern(constant);\n } else {\n throw new TypeError('Pattern is in unsupported datatype');\n }\n};\n\n/**\n * Sets the span with the error passed in params\n * @param {Span} span the span that need to be set\n * @param {Error} error error that will be set to span\n */\nexport const setSpanWithError = (span: Span, error: Err): void => {\n const message = error.message;\n span.setAttribute(ATTR_ERROR_TYPE, error.name);\n span.setStatus({ code: SpanStatusCode.ERROR, message });\n span.recordException(error);\n};\n\nexport const isCompressed = (\n headers: OutgoingHttpHeaders | IncomingHttpHeaders\n): boolean => {\n const encoding = headers['content-encoding'];\n\n return !!encoding && encoding !== 'identity';\n};\n\n/**\n * Mimics Node.js conversion of URL strings to RequestOptions expected by\n * `http.request` and `https.request` APIs.\n *\n * See https://github.com/nodejs/node/blob/2505e217bba05fc581b572c685c5cf280a16c5a3/lib/internal/url.js#L1415-L1437\n *\n * @param stringUrl\n * @throws TypeError if the URL is not valid.\n */\nfunction stringUrlToHttpOptions(\n stringUrl: string\n): RequestOptions & { pathname: string } {\n // This is heavily inspired by Node.js handling of the same situation, trying\n // to follow it as closely as possible while keeping in mind that we only\n // deal with string URLs, not URL objects.\n const {\n hostname,\n pathname,\n port,\n username,\n password,\n search,\n protocol,\n hash,\n href,\n origin,\n host,\n } = new URL(stringUrl);\n\n const options: RequestOptions & {\n pathname: string;\n hash: string;\n search: string;\n href: string;\n origin: string;\n } = {\n protocol: protocol,\n hostname:\n hostname && hostname[0] === '[' ? hostname.slice(1, -1) : hostname,\n hash: hash,\n search: search,\n pathname: pathname,\n path: `${pathname || ''}${search || ''}`,\n href: href,\n origin: origin,\n host: host,\n };\n if (port !== '') {\n options.port = Number(port);\n }\n if (username || password) {\n options.auth = `${decodeURIComponent(username)}:${decodeURIComponent(\n password\n )}`;\n }\n return options;\n}\n\n/**\n * Makes sure options is an url object\n * return an object with default value and parsed options\n * @param logger component logger\n * @param options original options for the request\n * @param [extraOptions] additional options for the request\n */\nexport const getRequestInfo = (\n logger: DiagLogger,\n options: url.URL | RequestOptions | string,\n extraOptions?: RequestOptions\n): {\n origin: string;\n pathname: string;\n method: string;\n invalidUrl: boolean;\n optionsParsed: RequestOptions;\n} => {\n let pathname: string;\n let origin: string;\n let optionsParsed: RequestOptions;\n let invalidUrl = false;\n if (typeof options === 'string') {\n try {\n const convertedOptions = stringUrlToHttpOptions(options);\n optionsParsed = convertedOptions;\n pathname = convertedOptions.pathname || '/';\n } catch (e) {\n invalidUrl = true;\n logger.verbose(\n 'Unable to parse URL provided to HTTP request, using fallback to determine path. Original error:',\n e\n );\n // for backward compatibility with how url.parse() behaved.\n optionsParsed = {\n path: options,\n };\n pathname = optionsParsed.path || '/';\n }\n\n origin = `${optionsParsed.protocol || 'http:'}//${optionsParsed.host}`;\n if (extraOptions !== undefined) {\n Object.assign(optionsParsed, extraOptions);\n }\n } else if (options instanceof url.URL) {\n optionsParsed = {\n protocol: options.protocol,\n hostname:\n typeof options.hostname === 'string' && options.hostname.startsWith('[')\n ? options.hostname.slice(1, -1)\n : options.hostname,\n path: `${options.pathname || ''}${options.search || ''}`,\n };\n if (options.port !== '') {\n optionsParsed.port = Number(options.port);\n }\n if (options.username || options.password) {\n optionsParsed.auth = `${options.username}:${options.password}`;\n }\n pathname = options.pathname;\n origin = options.origin;\n if (extraOptions !== undefined) {\n Object.assign(optionsParsed, extraOptions);\n }\n } else {\n optionsParsed = Object.assign(\n { protocol: options.host ? 'http:' : undefined },\n options\n );\n\n const hostname =\n optionsParsed.host ||\n (optionsParsed.port != null\n ? `${optionsParsed.hostname}${optionsParsed.port}`\n : optionsParsed.hostname);\n origin = `${optionsParsed.protocol || 'http:'}//${hostname}`;\n\n pathname = (options as url.URL).pathname;\n if (!pathname && optionsParsed.path) {\n try {\n const parsedUrl = new URL(optionsParsed.path, origin);\n pathname = parsedUrl.pathname || '/';\n } catch {\n pathname = '/';\n }\n }\n }\n\n // some packages return method in lowercase..\n // ensure upperCase for consistency\n const method = optionsParsed.method\n ? optionsParsed.method.toUpperCase()\n : 'GET';\n\n return { origin, pathname, method, optionsParsed, invalidUrl };\n};\n\n/**\n * Makes sure options is of type string or object\n * @param options for the request\n */\nexport const isValidOptionsType = (options: unknown): boolean => {\n if (!options) {\n return false;\n }\n\n const type = typeof options;\n return type === 'string' || (type === 'object' && !Array.isArray(options));\n};\n\nexport const extractHostnameAndPort = (\n requestOptions: Pick<\n ParsedRequestOptions,\n 'hostname' | 'host' | 'port' | 'protocol'\n >\n): { hostname: string; port: number | string } => {\n if (requestOptions.hostname && requestOptions.port) {\n return { hostname: requestOptions.hostname, port: requestOptions.port };\n }\n const matches = requestOptions.host?.match(/^([^:/ ]+)(:\\d{1,5})?/) || null;\n const hostname =\n requestOptions.hostname || (matches === null ? 'localhost' : matches[1]);\n let port = requestOptions.port;\n if (!port) {\n if (matches && matches[2]) {\n // remove the leading \":\". The extracted port would be something like \":8080\"\n port = matches[2].substring(1);\n } else {\n port = requestOptions.protocol === 'https:' ? '443' : '80';\n }\n }\n return { hostname, port };\n};\n\n/**\n * Returns outgoing request attributes scoped to the options passed to the request\n * @param {ParsedRequestOptions} requestOptions the same options used to make the request\n * @param {{ component: string, hostname: string, hookAttributes?: Attributes }} options used to pass data needed to create attributes\n */\nexport const getOutgoingRequestAttributes = (\n requestOptions: ParsedRequestOptions,\n options: {\n component: string;\n hostname: string;\n port: string | number;\n hookAttributes?: Attributes;\n redactedQueryParams?: string[];\n },\n enableSyntheticSourceDetection: boolean\n): Attributes => {\n const hostname = options.hostname;\n const port = options.port;\n const method = requestOptions.method ?? 'GET';\n const normalizedMethod = normalizeMethod(method);\n const headers = (requestOptions.headers || {}) as OutgoingHttpHeaders;\n const userAgent = headers['user-agent'];\n const urlFull = getAbsoluteUrl(\n requestOptions,\n headers,\n `${options.component}:`,\n options.redactedQueryParams\n );\n\n const attributes: Attributes = {\n // Required attributes\n [ATTR_HTTP_REQUEST_METHOD]: normalizedMethod,\n [ATTR_SERVER_ADDRESS]: hostname,\n [ATTR_SERVER_PORT]: Number(port),\n [ATTR_URL_FULL]: urlFull,\n [ATTR_USER_AGENT_ORIGINAL]: userAgent,\n // leaving out protocol version, it is not yet negotiated\n // leaving out protocol name, it is only required when protocol version is set\n // retries and redirects not supported\n\n // Opt-in attributes left off for now\n };\n\n // conditionally required if request method required case normalization\n if (method !== normalizedMethod) {\n attributes[ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = method;\n }\n\n if (enableSyntheticSourceDetection && userAgent) {\n attributes[ATTR_USER_AGENT_SYNTHETIC_TYPE] = getSyntheticType(userAgent);\n }\n return Object.assign(attributes, options.hookAttributes);\n};\n\n/**\n * Returns the type of synthetic source based on the user agent\n * @param {OutgoingHttpHeader} userAgent the user agent string\n */\nconst getSyntheticType = (\n userAgent: OutgoingHttpHeader\n): AttributeValue | undefined => {\n const userAgentString: string = String(userAgent).toLowerCase();\n for (const name of SYNTHETIC_TEST_NAMES) {\n if (userAgentString.includes(name)) {\n return USER_AGENT_SYNTHETIC_TYPE_VALUE_TEST;\n }\n }\n for (const name of SYNTHETIC_BOT_NAMES) {\n if (userAgentString.includes(name)) {\n return USER_AGENT_SYNTHETIC_TYPE_VALUE_BOT;\n }\n }\n return;\n};\n\n/**\n * Returns outgoing request attributes scoped to the response data\n * @param {IncomingMessage} response the response object\n */\nexport const getOutgoingRequestAttributesOnResponse = (\n response: IncomingMessage\n): Attributes => {\n const { statusCode, socket } = response;\n const attributes: Attributes = {};\n\n if (statusCode != null) {\n attributes[ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode;\n }\n\n if (socket) {\n const { remoteAddress, remotePort } = socket;\n\n // Recommended\n attributes[ATTR_NETWORK_PEER_ADDRESS] = remoteAddress;\n attributes[ATTR_NETWORK_PEER_PORT] = remotePort;\n attributes[ATTR_NETWORK_PROTOCOL_VERSION] = response.httpVersion;\n }\n return attributes;\n};\n\n/**\n * Returns outgoing request Metric attributes scoped to the response data\n * @param {Attributes} spanAttributes the span attributes\n */\nexport const getOutgoingStableRequestMetricAttributesOnResponse = (\n spanAttributes: Attributes\n): Attributes => {\n const metricAttributes: Attributes = {};\n\n if (spanAttributes[ATTR_NETWORK_PROTOCOL_VERSION]) {\n metricAttributes[ATTR_NETWORK_PROTOCOL_VERSION] =\n spanAttributes[ATTR_NETWORK_PROTOCOL_VERSION];\n }\n\n const statusCode = spanAttributes[ATTR_HTTP_RESPONSE_STATUS_CODE];\n if (statusCode) {\n metricAttributes[ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode;\n if (\n typeof statusCode === 'number' &&\n statusCode >= 400 &&\n statusCode < 600\n ) {\n metricAttributes[ATTR_ERROR_TYPE] ??= String(statusCode);\n }\n }\n return metricAttributes;\n};\n\nfunction parseHostHeader(\n hostHeader: string,\n proto?: string\n): { host: string; port?: string } {\n const parts = hostHeader.split(':');\n\n // no semicolon implies ipv4 dotted syntax or host name without port\n // x.x.x.x\n // example.com\n if (parts.length === 1) {\n if (proto === 'http') {\n return { host: parts[0], port: '80' };\n }\n\n if (proto === 'https') {\n return { host: parts[0], port: '443' };\n }\n\n return { host: parts[0] };\n }\n\n // single semicolon implies ipv4 dotted syntax or host name with port\n // x.x.x.x:yyyy\n // example.com:yyyy\n if (parts.length === 2) {\n return {\n host: parts[0],\n port: parts[1],\n };\n }\n\n // more than 2 parts implies ipv6 syntax with multiple colons\n // [x:x:x:x:x:x:x:x]\n // [x:x:x:x:x:x:x:x]:yyyy\n if (parts[0].startsWith('[')) {\n if (parts[parts.length - 1].endsWith(']')) {\n if (proto === 'http') {\n return { host: hostHeader, port: '80' };\n }\n\n if (proto === 'https') {\n return { host: hostHeader, port: '443' };\n }\n } else if (parts[parts.length - 2].endsWith(']')) {\n return {\n host: parts.slice(0, -1).join(':'),\n port: parts[parts.length - 1],\n };\n }\n }\n\n // if nothing above matches just return the host header\n return { host: hostHeader };\n}\n\n/**\n * Get server.address and port according to http semconv 1.27\n * https://github.com/open-telemetry/semantic-conventions/blob/bf0a2c1134f206f034408b201dbec37960ed60ec/docs/http/http-spans.md#setting-serveraddress-and-serverport-attributes\n */\nfunction getServerAddress(\n request: IncomingMessage,\n component: 'http' | 'https'\n): { host: string; port?: string } | null {\n const forwardedHeader = request.headers['forwarded'];\n if (forwardedHeader) {\n for (const entry of parseForwardedHeader(forwardedHeader)) {\n if (entry.host) {\n return parseHostHeader(entry.host, entry.proto);\n }\n }\n }\n\n const xForwardedHost = request.headers['x-forwarded-host'];\n if (typeof xForwardedHost === 'string') {\n if (typeof request.headers['x-forwarded-proto'] === 'string') {\n return parseHostHeader(\n xForwardedHost,\n request.headers['x-forwarded-proto']\n );\n }\n\n if (Array.isArray(request.headers['x-forwarded-proto'])) {\n return parseHostHeader(\n xForwardedHost,\n request.headers['x-forwarded-proto'][0]\n );\n }\n\n return parseHostHeader(xForwardedHost);\n } else if (\n Array.isArray(xForwardedHost) &&\n typeof xForwardedHost[0] === 'string' &&\n xForwardedHost[0].length > 0\n ) {\n if (typeof request.headers['x-forwarded-proto'] === 'string') {\n return parseHostHeader(\n xForwardedHost[0],\n request.headers['x-forwarded-proto']\n );\n }\n\n if (Array.isArray(request.headers['x-forwarded-proto'])) {\n return parseHostHeader(\n xForwardedHost[0],\n request.headers['x-forwarded-proto'][0]\n );\n }\n\n return parseHostHeader(xForwardedHost[0]);\n }\n\n const host = request.headers['host'];\n if (typeof host === 'string' && host.length > 0) {\n return parseHostHeader(host, component);\n }\n\n return null;\n}\n\n/**\n * Get server.address and port according to http semconv 1.27\n * https://github.com/open-telemetry/semantic-conventions/blob/bf0a2c1134f206f034408b201dbec37960ed60ec/docs/http/http-spans.md#setting-serveraddress-and-serverport-attributes\n */\nexport function getRemoteClientAddress(\n request: IncomingMessage\n): string | null {\n const forwardedHeader = request.headers['forwarded'];\n if (forwardedHeader) {\n for (const entry of parseForwardedHeader(forwardedHeader)) {\n if (entry.for) {\n return removePortFromAddress(entry.for);\n }\n }\n }\n\n const xForwardedFor = request.headers['x-forwarded-for'];\n if (xForwardedFor) {\n let xForwardedForVal;\n if (typeof xForwardedFor === 'string') {\n xForwardedForVal = xForwardedFor;\n } else if (Array.isArray(xForwardedFor)) {\n xForwardedForVal = xForwardedFor[0];\n }\n\n if (typeof xForwardedForVal === 'string') {\n xForwardedForVal = xForwardedForVal.split(',')[0].trim();\n return removePortFromAddress(xForwardedForVal);\n }\n }\n\n const remote = request.socket.remoteAddress;\n if (remote) {\n return remote;\n }\n\n return null;\n}\n\nfunction removePortFromAddress(input: string): string {\n // This function can be replaced with SocketAddress.parse() once the minimum\n // supported Node.js version allows it.\n try {\n const { hostname: address } = new URL(`http://${input}`);\n\n if (address.startsWith('[') && address.endsWith(']')) {\n return address.slice(1, -1);\n }\n\n return address;\n } catch {\n return input;\n }\n}\n\nfunction getInfoFromIncomingMessage(\n component: 'http' | 'https',\n request: IncomingMessage,\n logger: DiagLogger\n): { pathname?: string; search?: string; toString: () => string } {\n try {\n if (request.headers.host) {\n return new URL(\n request.url ?? '/',\n `${component}://${request.headers.host}`\n );\n } else {\n const unsafeParsedUrl = new URL(\n request.url ?? '/',\n // using localhost as a workaround to still use the URL constructor for parsing\n `${component}://localhost`\n );\n // since we use localhost as a workaround, ensure we hide the rest of the properties to avoid\n // our workaround leaking though.\n return {\n pathname: unsafeParsedUrl.pathname,\n search: unsafeParsedUrl.search,\n toString: function () {\n // we cannot use the result of unsafeParsedUrl.toString as it's potentially wrong.\n return unsafeParsedUrl.pathname + unsafeParsedUrl.search;\n },\n };\n }\n } catch (e) {\n // something is wrong, use undefined - this *should* never happen, logging\n // for troubleshooting in case it does happen.\n logger.verbose('Unable to get URL from request', e);\n return {};\n }\n}\n\n/**\n * Returns incoming request attributes scoped to the request data\n * @param {IncomingMessage} request the request object\n * @param {{ component: string, hookAttributes?: Attributes, enableSyntheticSourceDetection: boolean }} options used to pass data needed to create attributes\n */\nexport const getIncomingRequestAttributes = (\n request: IncomingMessage,\n options: {\n component: 'http' | 'https';\n hookAttributes?: Attributes;\n enableSyntheticSourceDetection: boolean;\n redactedQueryParams?: string[];\n },\n logger: DiagLogger\n): Attributes => {\n const {\n component,\n enableSyntheticSourceDetection,\n hookAttributes,\n redactedQueryParams,\n } = options;\n const { headers, method } = request;\n const { 'user-agent': userAgent } = headers;\n const parsedUrl = getInfoFromIncomingMessage(component, request, logger);\n\n // Stable attributes are used.\n const normalizedMethod = normalizeMethod(method);\n const serverAddress = getServerAddress(request, component);\n const remoteClientAddress = getRemoteClientAddress(request);\n\n const attributes: Attributes = {\n [ATTR_HTTP_REQUEST_METHOD]: normalizedMethod,\n [ATTR_URL_SCHEME]: component,\n [ATTR_SERVER_ADDRESS]: serverAddress?.host,\n [ATTR_NETWORK_PEER_ADDRESS]: request.socket.remoteAddress,\n [ATTR_NETWORK_PEER_PORT]: request.socket.remotePort,\n [ATTR_NETWORK_PROTOCOL_VERSION]: request.httpVersion,\n [ATTR_USER_AGENT_ORIGINAL]: userAgent,\n };\n\n if (parsedUrl.pathname != null) {\n attributes[ATTR_URL_PATH] = parsedUrl.pathname;\n }\n\n if (parsedUrl.search) {\n // Remove leading '?' from URL search (https://developer.mozilla.org/en-US/docs/Web/API/URL/search).\n const paramsToRedact = redactedQueryParams ?? defaultQueryStringsToRedact;\n attributes[ATTR_URL_QUERY] = redactQueryString(\n new URLSearchParams(parsedUrl.search.slice(1)),\n paramsToRedact\n );\n }\n\n if (remoteClientAddress != null) {\n attributes[ATTR_CLIENT_ADDRESS] = remoteClientAddress;\n }\n\n if (serverAddress?.port != null) {\n attributes[ATTR_SERVER_PORT] = Number(serverAddress.port);\n }\n\n // Conditionally required if request method required case normalization.\n if (method !== normalizedMethod) {\n attributes[ATTR_HTTP_REQUEST_METHOD_ORIGINAL] = method;\n }\n\n if (enableSyntheticSourceDetection && userAgent) {\n attributes[ATTR_USER_AGENT_SYNTHETIC_TYPE] = getSyntheticType(userAgent);\n }\n\n return Object.assign(attributes, hookAttributes);\n};\n\n/**\n * Returns incoming request attributes scoped to the response data\n * @param {(ServerResponse & { socket: Socket; })} response the response object\n */\nexport const getIncomingRequestAttributesOnResponse = (\n response: ServerResponse\n): Attributes => {\n const { statusCode } = response;\n\n const attributes: Attributes = {\n [ATTR_HTTP_RESPONSE_STATUS_CODE]: statusCode,\n };\n\n const rpcMetadata = getRPCMetadata(context.active());\n if (rpcMetadata?.type === RPCType.HTTP && rpcMetadata.route !== undefined) {\n attributes[ATTR_HTTP_ROUTE] = rpcMetadata.route;\n }\n\n return attributes;\n};\n\n/**\n * Returns incoming stable request Metric attributes scoped to the request data\n * @param {Attributes} spanAttributes the span attributes\n */\nexport const getIncomingStableRequestMetricAttributesOnResponse = (\n spanAttributes: Attributes\n): Attributes => {\n const metricAttributes: Attributes = {};\n if (spanAttributes[ATTR_HTTP_ROUTE] !== undefined) {\n metricAttributes[ATTR_HTTP_ROUTE] = spanAttributes[ATTR_HTTP_ROUTE];\n }\n\n // required if and only if one was sent, same as span requirement\n const statusCode = spanAttributes[ATTR_HTTP_RESPONSE_STATUS_CODE];\n if (statusCode) {\n metricAttributes[ATTR_HTTP_RESPONSE_STATUS_CODE] = statusCode;\n if (\n typeof statusCode === 'number' &&\n statusCode >= 500 &&\n statusCode < 600\n ) {\n metricAttributes[ATTR_ERROR_TYPE] ??= String(statusCode);\n }\n }\n\n return metricAttributes;\n};\n\nexport function headerCapture(type: 'request' | 'response', headers: string[]) {\n const normalizedHeaders = new Map<string, string>();\n for (let i = 0, len = headers.length; i < len; i++) {\n const capturedHeader = headers[i].toLowerCase();\n normalizedHeaders.set(capturedHeader, capturedHeader);\n }\n\n return (\n getHeader: (key: string) => undefined | string | string[] | number\n ): Attributes => {\n const attributes: Attributes = {};\n for (const capturedHeader of normalizedHeaders.keys()) {\n const value = getHeader(capturedHeader);\n\n if (value === undefined) {\n continue;\n }\n\n const normalizedHeader = normalizedHeaders.get(capturedHeader);\n const key = `http.${type}.header.${normalizedHeader}`;\n\n if (typeof value === 'string') {\n attributes[key] = [value];\n } else if (Array.isArray(value)) {\n attributes[key] = value;\n } else {\n attributes[key] = [value];\n }\n }\n return attributes;\n };\n}\n\nconst KNOWN_METHODS = new Set([\n // methods from https://www.rfc-editor.org/rfc/rfc9110.html#name-methods\n 'GET',\n 'HEAD',\n 'POST',\n 'PUT',\n 'DELETE',\n 'CONNECT',\n 'OPTIONS',\n 'TRACE',\n\n // PATCH from https://www.rfc-editor.org/rfc/rfc5789.html\n 'PATCH',\n\n // QUERY from https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/\n 'QUERY',\n]);\n\nfunction normalizeMethod(method?: string | null) {\n if (method == null) {\n return 'GET';\n }\n\n const upper = method.toUpperCase();\n if (KNOWN_METHODS.has(upper)) {\n return upper;\n }\n\n return '_OTHER';\n}\n\nfunction parseForwardedHeader(header: string): Record<string, string>[] {\n try {\n return forwardedParse(header);\n } catch {\n return [];\n }\n}\n"]}
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "0.221.0";
1
+ export declare const VERSION = "0.222.0";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -6,5 +6,5 @@
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  exports.VERSION = void 0;
8
8
  // this is autogenerated file, see scripts/version-update.js
9
- exports.VERSION = '0.221.0';
9
+ exports.VERSION = '0.222.0';
10
10
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,4DAA4D;AAC/C,QAAA,OAAO,GAAG,SAAS,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.221.0';\n"]}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,4DAA4D;AAC/C,QAAA,OAAO,GAAG,SAAS,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.222.0';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opentelemetry/instrumentation-http",
3
- "version": "0.221.0",
3
+ "version": "0.222.0",
4
4
  "description": "OpenTelemetry instrumentation for `node:http` and `node:https` http client and server modules",
5
5
  "main": "build/src/index.js",
6
6
  "types": "build/src/index.d.ts",
@@ -49,16 +49,16 @@
49
49
  },
50
50
  "devDependencies": {
51
51
  "@opentelemetry/api": "1.9.1",
52
- "@opentelemetry/context-async-hooks": "2.10.0",
53
- "@opentelemetry/sdk-metrics": "2.10.0",
54
- "@opentelemetry/sdk-trace": "2.10.0",
52
+ "@opentelemetry/context-async-hooks": "2.11.0",
53
+ "@opentelemetry/sdk-metrics": "2.11.0",
54
+ "@opentelemetry/sdk-trace": "2.11.0",
55
55
  "@types/mocha": "10.0.10",
56
56
  "@types/node": "18.19.130",
57
57
  "@types/request-promise-native": "1.0.21",
58
58
  "@types/sinon": "17.0.4",
59
- "@types/superagent": "8.1.10",
59
+ "@types/superagent": "8.1.11",
60
60
  "axios": "1.18.1",
61
- "mocha": "11.7.6",
61
+ "mocha": "11.8.0",
62
62
  "nock": "13.5.6",
63
63
  "nyc": "17.1.0",
64
64
  "sinon": "18.0.1",
@@ -69,12 +69,12 @@
69
69
  "@opentelemetry/api": "^1.3.0"
70
70
  },
71
71
  "dependencies": {
72
- "@opentelemetry/core": "2.10.0",
73
- "@opentelemetry/instrumentation": "0.221.0",
72
+ "@opentelemetry/core": "2.11.0",
73
+ "@opentelemetry/instrumentation": "0.222.0",
74
74
  "@opentelemetry/semantic-conventions": "^1.29.0",
75
75
  "forwarded-parse": "2.1.2"
76
76
  },
77
77
  "homepage": "https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation-http",
78
78
  "sideEffects": false,
79
- "gitHead": "76fa6b509e2b48d9cbee31cb37a2efc61dc4d384"
79
+ "gitHead": "0b72a81636fa476e8f1f1afd2ae0c90a1362194c"
80
80
  }