dd-trace 5.136.0 → 5.138.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.
Files changed (190) hide show
  1. package/README.md +3 -0
  2. package/ci/cypress/support.js +2 -1
  3. package/ci/vitest-no-worker-init-node-setup.mjs +2 -1
  4. package/ci/vitest-no-worker-init-runner-setup.mjs +2 -1
  5. package/ci/vitest-no-worker-init-setup.mjs +729 -724
  6. package/ci/vitest-no-worker-init-v5-setup.mjs +2 -1
  7. package/index.d.ts +56 -0
  8. package/initialize.mjs +5 -3
  9. package/package.json +36 -32
  10. package/packages/datadog-esbuild/index.js +8 -15
  11. package/packages/datadog-esbuild/src/log.js +2 -29
  12. package/packages/datadog-instrumentations/src/ai.js +88 -122
  13. package/packages/datadog-instrumentations/src/aws-lambda.js +9 -0
  14. package/packages/datadog-instrumentations/src/cypress-config.js +20 -9
  15. package/packages/datadog-instrumentations/src/helpers/bundler-esm-exports.js +23 -1
  16. package/packages/datadog-instrumentations/src/helpers/bundler-log.js +38 -0
  17. package/packages/datadog-instrumentations/src/helpers/bundler-transform.js +9 -6
  18. package/packages/datadog-instrumentations/src/helpers/fetch.js +51 -6
  19. package/packages/datadog-instrumentations/src/helpers/hooks.js +0 -1
  20. package/packages/datadog-instrumentations/src/helpers/instrument.js +1 -3
  21. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +6 -0
  22. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +12 -1
  23. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/ai.js +2 -0
  24. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql-jit.js +5 -3
  25. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-client.js +30 -0
  26. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/modelcontextprotocol-server.js +23 -0
  27. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/next.js +21 -0
  28. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/postgres.js +33 -4
  29. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +30 -0
  30. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +6 -0
  31. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms/postgres.js +122 -0
  32. package/packages/datadog-instrumentations/src/microgateway-core.js +1 -2
  33. package/packages/datadog-instrumentations/src/modelcontextprotocol-client.js +21 -0
  34. package/packages/datadog-instrumentations/src/modelcontextprotocol-sdk.js +32 -2
  35. package/packages/datadog-instrumentations/src/modelcontextprotocol-server.js +43 -0
  36. package/packages/datadog-instrumentations/src/next.js +184 -20
  37. package/packages/datadog-instrumentations/src/path-to-regexp.js +11 -11
  38. package/packages/datadog-instrumentations/src/router.js +52 -13
  39. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +1 -1
  40. package/packages/datadog-instrumentations/src/vitest-main.js +10 -2
  41. package/packages/datadog-plugin-aws-lambda/src/arn.js +41 -0
  42. package/packages/datadog-plugin-aws-lambda/src/context/events.js +167 -0
  43. package/packages/datadog-plugin-aws-lambda/src/context/extractor.js +153 -0
  44. package/packages/datadog-plugin-aws-lambda/src/context/http.js +50 -0
  45. package/packages/datadog-plugin-aws-lambda/src/context/span-context.js +26 -0
  46. package/packages/datadog-plugin-aws-lambda/src/context/step-functions.js +142 -0
  47. package/packages/datadog-plugin-aws-lambda/src/context/types.d.ts +17 -0
  48. package/packages/datadog-plugin-aws-lambda/src/context/xray.js +67 -0
  49. package/packages/datadog-plugin-aws-lambda/src/event-type-guards.js +170 -0
  50. package/packages/datadog-plugin-aws-lambda/src/index.js +52 -4
  51. package/packages/datadog-plugin-aws-lambda/src/trigger.js +339 -0
  52. package/packages/datadog-plugin-aws-sdk/src/services/dynamodb.js +7 -0
  53. package/packages/datadog-plugin-aws-sdk/src/services/kinesis.js +32 -10
  54. package/packages/datadog-plugin-aws-sdk/src/services/lambda.js +10 -1
  55. package/packages/datadog-plugin-aws-sdk/src/services/sqs.js +4 -0
  56. package/packages/datadog-plugin-aws-sdk/src/services/stepfunctions.js +3 -0
  57. package/packages/datadog-plugin-azure-functions/src/index.js +68 -12
  58. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +30 -4
  59. package/packages/datadog-plugin-cypress/src/support.mjs +1353 -0
  60. package/packages/datadog-plugin-express/src/code_origin.js +2 -2
  61. package/packages/datadog-plugin-fastify/src/code_origin.js +2 -2
  62. package/packages/datadog-plugin-fetch/src/index.js +7 -0
  63. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +10 -0
  64. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +2 -0
  65. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +7 -0
  66. package/packages/datadog-plugin-google-cloud-pubsub/src/resource-names.js +24 -0
  67. package/packages/datadog-plugin-graphql/src/tools/transforms.js +1 -0
  68. package/packages/datadog-plugin-http/src/client.js +14 -1
  69. package/packages/datadog-plugin-http/src/server.js +18 -4
  70. package/packages/datadog-plugin-http2/src/client.js +2 -1
  71. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/tracing.js +28 -2
  72. package/packages/datadog-plugin-modelcontextprotocol-sdk/src/utils.js +1 -0
  73. package/packages/datadog-plugin-mongodb-core/src/query.js +17 -1
  74. package/packages/datadog-plugin-postgres/src/index.js +118 -41
  75. package/packages/datadog-plugin-supabase/src/supabase-auth-js-gotrueclient-getuser.js +18 -8
  76. package/packages/datadog-plugin-supabase/src/supabase-functions-js-functionsclient-invoke.js +49 -13
  77. package/packages/datadog-plugin-supabase/src/supabase-storage-js-handle-request.js +34 -9
  78. package/packages/datadog-plugin-vitest/src/index.js +3 -2
  79. package/packages/datadog-plugin-ws/src/close.js +3 -5
  80. package/packages/datadog-plugin-ws/src/producer.js +1 -4
  81. package/packages/datadog-plugin-ws/src/receiver.js +3 -5
  82. package/packages/datadog-plugin-ws/src/server.js +44 -13
  83. package/packages/datadog-vite/index.js +537 -0
  84. package/packages/datadog-vite/src/log.js +5 -0
  85. package/packages/datadog-webpack/src/log.js +2 -29
  86. package/packages/dd-trace/src/aiguard/client.js +7 -9
  87. package/packages/dd-trace/src/aiguard/evaluation.js +7 -2
  88. package/packages/dd-trace/src/aiguard/index.js +1 -1
  89. package/packages/dd-trace/src/aiguard/integrations/index.js +6 -5
  90. package/packages/dd-trace/src/aiguard/messages/utils.js +2 -2
  91. package/packages/dd-trace/src/aiguard/sdk.js +7 -2
  92. package/packages/dd-trace/src/appsec/api_security/normalized-route.js +273 -167
  93. package/packages/dd-trace/src/appsec/blocking/index.js +17 -1
  94. package/packages/dd-trace/src/appsec/channels.js +8 -0
  95. package/packages/dd-trace/src/appsec/downstream_requests.js +105 -0
  96. package/packages/dd-trace/src/appsec/graphql.js +10 -13
  97. package/packages/dd-trace/src/appsec/handlers/auth.js +1 -3
  98. package/packages/dd-trace/src/appsec/handlers/http-request.js +60 -65
  99. package/packages/dd-trace/src/appsec/handlers/http-response.js +61 -7
  100. package/packages/dd-trace/src/appsec/handlers/payments.js +23 -27
  101. package/packages/dd-trace/src/appsec/iast/taint-tracking/plugin.js +21 -14
  102. package/packages/dd-trace/src/appsec/index.js +9 -0
  103. package/packages/dd-trace/src/appsec/lambda.js +17 -17
  104. package/packages/dd-trace/src/appsec/rasp/command_injection.js +4 -4
  105. package/packages/dd-trace/src/appsec/rasp/index.js +64 -3
  106. package/packages/dd-trace/src/appsec/rasp/lfi.js +2 -2
  107. package/packages/dd-trace/src/appsec/rasp/sql_injection.js +7 -17
  108. package/packages/dd-trace/src/appsec/rasp/ssrf.js +80 -16
  109. package/packages/dd-trace/src/appsec/rasp/utils.js +47 -3
  110. package/packages/dd-trace/src/appsec/recommended.json +70 -3
  111. package/packages/dd-trace/src/appsec/reporter.js +9 -0
  112. package/packages/dd-trace/src/appsec/sdk/set_user.js +3 -3
  113. package/packages/dd-trace/src/appsec/sdk/track_event.js +4 -4
  114. package/packages/dd-trace/src/appsec/sdk/user_blocking.js +1 -1
  115. package/packages/dd-trace/src/appsec/user_tracking.js +6 -8
  116. package/packages/dd-trace/src/appsec/waf/index.js +65 -6
  117. package/packages/dd-trace/src/appsec/waf/waf_context_wrapper.js +33 -38
  118. package/packages/dd-trace/src/appsec/waf/waf_manager.js +18 -2
  119. package/packages/dd-trace/src/carrier.js +7 -1
  120. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/index.js +4 -2
  121. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/worker/index.js +31 -19
  122. package/packages/dd-trace/src/config/generated-config-types.d.ts +14 -5
  123. package/packages/dd-trace/src/config/index.js +73 -27
  124. package/packages/dd-trace/src/config/parsers.js +60 -0
  125. package/packages/dd-trace/src/config/remote-config-layers.js +38 -0
  126. package/packages/dd-trace/src/config/remote_config.js +2 -1
  127. package/packages/dd-trace/src/config/supported-configurations.json +41 -13
  128. package/packages/dd-trace/src/datastreams/fnv.js +27 -0
  129. package/packages/dd-trace/src/datastreams/http.js +57 -0
  130. package/packages/dd-trace/src/datastreams/index.js +24 -0
  131. package/packages/dd-trace/src/datastreams/pathway.js +142 -28
  132. package/packages/dd-trace/src/datastreams/processor.js +27 -7
  133. package/packages/dd-trace/src/debugger/config.js +1 -1
  134. package/packages/dd-trace/src/debugger/devtools_client/request-options.js +7 -9
  135. package/packages/dd-trace/src/debugger/devtools_client/send.js +1 -1
  136. package/packages/dd-trace/src/debugger/devtools_client/state.js +3 -1
  137. package/packages/dd-trace/src/debugger/devtools_client/tags.js +1 -1
  138. package/packages/dd-trace/src/debugger/index.js +2 -2
  139. package/packages/dd-trace/src/debugger/inspect-segment.js +3 -2
  140. package/packages/dd-trace/src/debugger/pause-duration-histogram.js +4 -1
  141. package/packages/dd-trace/src/debugger/probe_sampler.js +39 -17
  142. package/packages/dd-trace/src/debugger/unsupported-runtime.js +2 -0
  143. package/packages/dd-trace/src/git_metadata.js +2 -1
  144. package/packages/dd-trace/src/index.js +6 -3
  145. package/packages/dd-trace/src/lambda/facade.js +6 -5
  146. package/packages/dd-trace/src/lambda/handler-paths.js +1 -1
  147. package/packages/dd-trace/src/llmobs/constants/tags.js +1 -0
  148. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/index.js +86 -3
  149. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/utils.js +182 -1
  150. package/packages/dd-trace/src/llmobs/span_processor.js +3 -0
  151. package/packages/dd-trace/src/llmobs/tagger.js +9 -0
  152. package/packages/dd-trace/src/noop/span.js +0 -4
  153. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +3 -0
  154. package/packages/dd-trace/src/openfeature/configuration_source.js +20 -0
  155. package/packages/dd-trace/src/openfeature/flagging_provider.js +17 -0
  156. package/packages/dd-trace/src/opentelemetry/logs/otlp_transformer.js +2 -1
  157. package/packages/dd-trace/src/opentelemetry/metrics/otlp_transformer.js +2 -1
  158. package/packages/dd-trace/src/opentelemetry/otlp/otlp_transformer_base.js +16 -1
  159. package/packages/dd-trace/src/opentelemetry/trace/index.js +5 -4
  160. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +10 -6
  161. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +42 -26
  162. package/packages/dd-trace/src/opentracing/propagation/text_map.js +4 -4
  163. package/packages/dd-trace/src/plugin_manager.js +2 -0
  164. package/packages/dd-trace/src/plugins/ci_plugin.js +104 -9
  165. package/packages/dd-trace/src/plugins/index.js +2 -0
  166. package/packages/dd-trace/src/plugins/util/ci.js +34 -0
  167. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +9 -14
  168. package/packages/dd-trace/src/plugins/util/inferred_proxy.js +3 -5
  169. package/packages/dd-trace/src/plugins/util/test.js +28 -1
  170. package/packages/dd-trace/src/plugins/util/url.js +9 -6
  171. package/packages/dd-trace/src/plugins/util/user-provided-git.js +4 -4
  172. package/packages/dd-trace/src/process-tags/index.js +1 -1
  173. package/packages/dd-trace/src/profiler.js +74 -12
  174. package/packages/dd-trace/src/profiling/profiler.js +30 -2
  175. package/packages/dd-trace/src/profiling/profilers/space.js +3 -1
  176. package/packages/dd-trace/src/profiling/profilers/wall.js +4 -4
  177. package/packages/dd-trace/src/profiling/remote-config.js +354 -0
  178. package/packages/dd-trace/src/profiling/runtime-capabilities.js +11 -0
  179. package/packages/dd-trace/src/propagation-hash/index.js +7 -0
  180. package/packages/dd-trace/src/proxy.js +13 -1
  181. package/packages/dd-trace/src/register-loader.js +43 -0
  182. package/register.js +10 -44
  183. package/register.mjs +27 -0
  184. package/vendor/dist/@opentelemetry/core/LICENSE +11 -0
  185. package/vendor/dist/@opentelemetry/core/index.js +1 -1
  186. package/vite.d.ts +7 -0
  187. package/vite.js +3 -0
  188. package/lambda.d.ts +0 -39
  189. package/lambda.js +0 -3
  190. package/packages/datadog-plugin-cypress/src/support.js +0 -1348
@@ -40,6 +40,14 @@ const responseBlockedSet = new WeakSet()
40
40
 
41
41
  const blockDelegations = new WeakMap()
42
42
 
43
+ // Abort reason for instrumentations that must reject an operation the application awaits.
44
+ class BlockedRequestError extends Error {
45
+ constructor () {
46
+ super('Request blocked by Datadog App and API Protection')
47
+ this.name = 'BlockedRequestError'
48
+ }
49
+ }
50
+
43
51
  const specificBlockingTypes = {
44
52
  GRAPHQL: 'graphqlJson',
45
53
  }
@@ -128,6 +136,14 @@ function block (req, res, rootSpan, abortController, actionParameters = defaultB
128
136
  throw new Error('Headers have already been sent')
129
137
  }
130
138
 
139
+ // A destroyed response accepts the writes without sending anything to the client.
140
+ if (res.destroyed) {
141
+ log.warn('[ASM] Cannot send blocking response when the response has been destroyed')
142
+ abortController?.abort(new BlockedRequestError())
143
+
144
+ throw new Error('Response has been destroyed')
145
+ }
146
+
131
147
  const { body, headers, statusCode } = getBlockingData(req, null, actionParameters)
132
148
 
133
149
  for (const headerName of res.getHeaderNames()) {
@@ -146,7 +162,7 @@ function block (req, res, rootSpan, abortController, actionParameters = defaultB
146
162
  // The blocking response is final, but frameworks may keep running and rewrite the status (Next.js restores it).
147
163
  Object.defineProperty(res, 'statusCode', { configurable: true, enumerable: true, get: () => statusCode, set () {} })
148
164
 
149
- abortController?.abort()
165
+ abortController?.abort(new BlockedRequestError())
150
166
 
151
167
  return true
152
168
  } catch (err) {
@@ -20,8 +20,11 @@ module.exports = {
20
20
  fastifyPathParams: dc.channel('datadog:fastify:path-params:finish'),
21
21
  fastifyQueryParams: dc.channel('datadog:fastify:query-params:finish'),
22
22
  fastifyResponseChannel: dc.channel('datadog:fastify:response:finish'),
23
+ fetchRequestStart: dc.channel('tracing:apm:fetch:request:start'),
23
24
  fsOperationStart: dc.channel('apm:fs:operation:start'),
24
25
  graphqlMiddlewareChannel: dc.tracingChannel('datadog:apollo:middleware'),
26
+ httpClientRequestFinish: dc.channel('apm:http:client:request:finish'),
27
+ httpClientRequestError: dc.channel('apm:http:client:request:error'),
25
28
  httpClientRequestStart: dc.channel('apm:http:client:request:start'),
26
29
  httpClientResponseStart: dc.channel('apm:http:client:response:start'),
27
30
  httpClientResponseFinish: dc.channel('apm:http:client:response:finish'),
@@ -34,6 +37,10 @@ module.exports = {
34
37
  mysql2OuterQueryStart: dc.channel('datadog:mysql2:outerquery:start'),
35
38
  nextBodyParsed: dc.channel('apm:next:body-parsed'),
36
39
  nextQueryParsed: dc.channel('apm:next:query-parsed'),
40
+ nextRequestStart: dc.channel('apm:next:request:start'),
41
+ nextResponseBody: dc.channel('tracing:orchestrion:next:responseBody:start'),
42
+ nextJsonResponse: dc.channel('apm:next:response:json'),
43
+ nextAppRouteResponse: dc.channel('tracing:orchestrion:next:appRouteResponse:asyncEnd'),
37
44
  passportUser: dc.channel('datadog:passport:deserializeUser:finish'),
38
45
  passportVerify: dc.channel('datadog:passport:verify:finish'),
39
46
  pgPoolQueryStart: dc.channel('datadog:pg:pool:query:start'),
@@ -44,6 +51,7 @@ module.exports = {
44
51
  responseWriteHead: dc.channel('apm:http:server:response:writeHead:start'),
45
52
  routerMiddlewareError: dc.channel('apm:router:middleware:error'),
46
53
  routerParam: dc.channel('datadog:router:param:start'),
54
+ routerRouteCreate: dc.channel('datadog:router:route:create'),
47
55
  setCookieChannel: dc.channel('datadog:iast:set-cookie'),
48
56
  setUncaughtExceptionCaptureCallbackStart: dc.channel('datadog:process:setUncaughtExceptionCaptureCallback:start'),
49
57
  startGraphqlResolver: dc.channel('datadog:graphql:resolver:start'),
@@ -1,5 +1,8 @@
1
1
  'use strict'
2
2
 
3
+ // Headers is only used for requests of the global fetch, which comes with it.
4
+ /* eslint n/no-unsupported-features/node-builtins: ['error', { ignores: ['Headers'] }] */
5
+
3
6
  const web = require('../plugins/util/web')
4
7
  const log = require('../log')
5
8
  const { isEmpty } = require('../util')
@@ -27,6 +30,19 @@ const RESPONSE_BODY_IGNORED_TAG_CONTENT_LENGTH_MISSING =
27
30
  const RESPONSE_BODY_IGNORED_TAG_CONTENT_LENGTH_TOO_BIG =
28
31
  '_dd.appsec.downstream_request.response_body_ignored.content_length_too_big'
29
32
 
33
+ const HTTP_TOKEN_PATTERN = /^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/
34
+ const FORBIDDEN_FETCH_METHODS = new Set(['connect', 'trace', 'track'])
35
+ const ARRAY_ITERATOR = Array.prototype[Symbol.iterator]
36
+ const NORMALIZED_FETCH_METHODS = new Map([
37
+ ['delete', 'DELETE'],
38
+ ['get', 'GET'],
39
+ ['head', 'HEAD'],
40
+ ['options', 'OPTIONS'],
41
+ ['post', 'POST'],
42
+ ['put', 'PUT'],
43
+ ['query', 'QUERY'],
44
+ ])
45
+
30
46
  let config
31
47
  let samplingRate
32
48
  let globalRequestCounter
@@ -211,6 +227,94 @@ function extractRequestData (ctx) {
211
227
  return addresses
212
228
  }
213
229
 
230
+ /**
231
+ * Extracts request data from an outgoing fetch request for WAF analysis.
232
+ * @param {Request} request outgoing fetch request.
233
+ * @param {import('undici-types').RequestInit} [init] options that fetch applies over `request`.
234
+ * @returns {object} a map of addresses and request data.
235
+ */
236
+ function extractFetchRequestData (request, init) {
237
+ /** @type {Record<string, unknown>} */
238
+ const addresses = {}
239
+
240
+ // An override that can't be read as plain data is left out rather than reported with the value it replaces.
241
+ const method = init?.method === undefined ? request.method : getFetchMethod(init.method)
242
+ if (method !== undefined) {
243
+ addresses[HTTP_OUTGOING_METHOD] = method
244
+ }
245
+
246
+ // Header names of a fetch request are already lowercase.
247
+ const headers = init?.headers === undefined ? Object.fromEntries(request.headers) : getFetchHeaders(init.headers)
248
+ if (headers !== undefined && !isEmpty(headers)) {
249
+ addresses[HTTP_OUTGOING_HEADERS] = headers
250
+ }
251
+
252
+ return addresses
253
+ }
254
+
255
+ /**
256
+ * Returns the method that fetch sends for a method option, or undefined when fetch would reject it or would have to
257
+ * convert it to a string.
258
+ * @param {unknown} method method option of a fetch call.
259
+ * @returns {string | undefined}
260
+ */
261
+ function getFetchMethod (method) {
262
+ if (typeof method !== 'string' || !HTTP_TOKEN_PATTERN.test(method)) return
263
+
264
+ const lowercaseMethod = method.toLowerCase()
265
+ if (FORBIDDEN_FETCH_METHODS.has(lowercaseMethod)) return
266
+
267
+ return NORMALIZED_FETCH_METHODS.get(lowercaseMethod) ?? method
268
+ }
269
+
270
+ /**
271
+ * Returns the headers that fetch sends for a headers option, or undefined when the option is not plain data. Iterables
272
+ * other than plain arrays and Headers objects are left out: reading them could consume the values that fetch sends.
273
+ * @param {unknown} headers headers option of a fetch call.
274
+ * @returns {Record<string, string> | undefined}
275
+ */
276
+ function getFetchHeaders (headers) {
277
+ if (typeof headers !== 'object' || headers === null) return
278
+
279
+ try {
280
+ const iterator = headers[Symbol.iterator]
281
+ let entries
282
+ if (iterator == null) {
283
+ entries = Object.entries(headers)
284
+ if (!entries.every(([, value]) => isFetchHeaderPrimitive(value))) return
285
+ } else if (iterator === ARRAY_ITERATOR && Array.isArray(headers)) {
286
+ if (!headers.every(isFetchHeaderEntry)) return
287
+ entries = headers
288
+ } else if (headers instanceof Headers && iterator === Headers.prototype[Symbol.iterator]) {
289
+ return Object.fromEntries(headers)
290
+ } else {
291
+ return
292
+ }
293
+
294
+ // Headers applies the normalization of fetch, and rejects the names and values that fetch rejects.
295
+ return Object.fromEntries(new Headers(entries))
296
+ } catch {}
297
+ }
298
+
299
+ /**
300
+ * @param {unknown} entry entry of a headers option given as an array.
301
+ */
302
+ function isFetchHeaderEntry (entry) {
303
+ return Array.isArray(entry) &&
304
+ entry[Symbol.iterator] === ARRAY_ITERATOR &&
305
+ entry.length === 2 &&
306
+ isFetchHeaderPrimitive(entry[0]) &&
307
+ isFetchHeaderPrimitive(entry[1])
308
+ }
309
+
310
+ /**
311
+ * Tells whether fetch converts a header name or value to a string without calling code of the application.
312
+ * @param {unknown} value header name or value of a headers option.
313
+ */
314
+ function isFetchHeaderPrimitive (value) {
315
+ return value === null || (typeof value !== 'object' && typeof value !== 'function' && typeof value !== 'symbol')
316
+ }
317
+
214
318
  /**
215
319
  * Extracts response data for WAF analysis.
216
320
  * @param {import('http').IncomingMessage} res downstream response object.
@@ -341,5 +445,6 @@ module.exports = {
341
445
  incrementDownstreamAnalysisCount,
342
446
  extractMimeType,
343
447
  extractRequestData,
448
+ extractFetchRequestData,
344
449
  extractResponseData,
345
450
  }
@@ -52,7 +52,7 @@ function onGraphqlStartResolver (data) {
52
52
 
53
53
  const knownActions = fieldsWithoutArgumentsActions.get(req)
54
54
  if (knownActions === undefined &&
55
- !waf.wafManager.getWAFContext(req).knownAddresses.has(addresses.HTTP_INCOMING_GRAPHQL_RESOLVER)) return
55
+ !waf.wafManager.getWAFContext(req)?.knownAddresses.has(addresses.HTTP_INCOMING_GRAPHQL_RESOLVER)) return
56
56
 
57
57
  const resolverInfo = data.createResolverInfo?.(data)
58
58
  if (!resolverInfo || typeof resolverInfo !== 'object') return
@@ -63,12 +63,12 @@ function onGraphqlStartResolver (data) {
63
63
  return
64
64
  }
65
65
 
66
- const result = waf.run({ ephemeral: { [addresses.HTTP_INCOMING_GRAPHQL_RESOLVER]: resolverInfo } }, req)
66
+ const result = waf.runSubContext({ [addresses.HTTP_INCOMING_GRAPHQL_RESOLVER]: resolverInfo })
67
67
  const blockingAction = getBlockingAction(result?.actions)
68
68
 
69
69
  // A run that timed out, failed, or found no rule to evaluate is not an answer about the field, so let the next
70
70
  // occurrence run again instead of reading it back as "allowed".
71
- if (cacheKey !== undefined && result !== undefined && !result.timeout) {
71
+ if (cacheKey !== undefined && result !== undefined && !result.timeout && !(result.errorCode < 0)) {
72
72
  if (knownActions === undefined) {
73
73
  const blockingActions = new Map()
74
74
  blockingActions.set(cacheKey, blockingAction)
@@ -82,17 +82,14 @@ function onGraphqlStartResolver (data) {
82
82
  }
83
83
 
84
84
  /**
85
- * Persistent inputs stay in the request's WAF context, so they can change the action of a field checked before
86
- * they arrived. Forget what we know about the request when a run carries them. Resolver runs send ephemeral
87
- * inputs only, so they never invalidate their own answers.
85
+ * Inputs stay in the request's WAF context, so they can change the action of a field checked before
86
+ * they arrived. Invalidate cached answers after evaluations on the request context.
87
+ * Resolver evaluations use subcontexts, so they never invalidate their own answers.
88
88
  *
89
- * @param {{ payload?: { persistent?: object } }} data
89
+ * @param {{ req?: object, payload?: object, isSubcontext?: boolean }} data
90
90
  */
91
- function onWafRunFinished ({ payload }) {
92
- if (!payload?.persistent) return
93
-
94
- const req = getActiveRequest()
95
- if (!req) return
91
+ function onWafRunFinished ({ req, payload, isSubcontext }) {
92
+ if (!req || !payload || isSubcontext) return
96
93
 
97
94
  fieldsWithoutArgumentsActions.delete(req)
98
95
  }
@@ -112,7 +109,7 @@ function getFieldCacheKey (resolverInfo) {
112
109
  for (const name of names) {
113
110
  const directive = fieldArguments[name]
114
111
  if ((name !== 'include' && name !== 'skip') ||
115
- !directive || typeof directive !== 'object') return
112
+ !directive || typeof directive !== 'object') return
116
113
  const argumentNames = Object.keys(directive)
117
114
  if (argumentNames.length !== 1 || argumentNames[0] !== 'if') return
118
115
  const value = directive.if
@@ -47,9 +47,7 @@ function onExpressSession ({ req, res, sessionId, abortController }) {
47
47
  if (isSdkCalled) return
48
48
 
49
49
  const results = waf.run({
50
- persistent: {
51
- [addresses.USER_SESSION_ID]: sessionId,
52
- },
50
+ [addresses.USER_SESSION_ID]: sessionId,
53
51
  }, req)
54
52
 
55
53
  handleResults(results?.actions, req, res, rootSpan, abortController)
@@ -32,6 +32,7 @@ function onRequestBodyParsed ({ req, res, body, abortController }) {
32
32
 
33
33
  if (!req) {
34
34
  req = getActiveRequest()
35
+ res ??= web.getContext(req)?.res
35
36
  }
36
37
 
37
38
  const rootSpan = web.root(req)
@@ -48,9 +49,7 @@ function onRequestBodyParsed ({ req, res, body, abortController }) {
48
49
  }
49
50
 
50
51
  const results = waf.run({
51
- persistent: {
52
- [addresses.HTTP_INCOMING_BODY]: body,
53
- },
52
+ [addresses.HTTP_INCOMING_BODY]: body,
54
53
  }, req)
55
54
 
56
55
  handleResults(results?.actions, req, res, rootSpan, abortController)
@@ -64,9 +63,7 @@ function onRequestCookieParser ({ req, res, abortController, cookies }) {
64
63
  analyzedCookies.add(cookies)
65
64
 
66
65
  const results = waf.run({
67
- persistent: {
68
- [addresses.HTTP_INCOMING_COOKIES]: cookies,
69
- },
66
+ [addresses.HTTP_INCOMING_COOKIES]: cookies,
70
67
  }, req)
71
68
 
72
69
  handleResults(results?.actions, req, res, rootSpan, abortController)
@@ -91,82 +88,84 @@ function incomingHttpStartTranslator ({ req, res, abortController }) {
91
88
  }
92
89
  }
93
90
 
94
- const persistent = {
91
+ const requestData = {
95
92
  [addresses.HTTP_INCOMING_URL]: req.url,
96
93
  [addresses.HTTP_INCOMING_HEADERS]: copyHeadersOmitting(req.headers, 'cookie'),
97
94
  [addresses.HTTP_INCOMING_METHOD]: req.method,
98
95
  }
99
96
 
100
97
  if (clientIp) {
101
- persistent[addresses.HTTP_CLIENT_IP] = clientIp
98
+ requestData[addresses.HTTP_CLIENT_IP] = clientIp
102
99
  }
103
100
 
104
- const results = waf.run({ persistent }, req)
101
+ const results = waf.run(requestData, req)
105
102
 
106
103
  handleResults(results?.actions, req, res, rootSpan, abortController)
107
104
  }
108
105
 
109
106
  function incomingHttpEndTranslator ({ req, res }) {
110
- const persistent = {}
111
-
112
- // we need to keep this to support other body parsers
113
- if (req.body !== undefined && req.body !== null) {
114
- if (typeof req.body === 'object') {
115
- if (!isEmpty(req.body) && !analyzedBodies.has(req.body)) {
116
- persistent[addresses.HTTP_INCOMING_BODY] = req.body
107
+ try {
108
+ const requestData = {}
109
+
110
+ // we need to keep this to support other body parsers
111
+ if (req.body !== undefined && req.body !== null) {
112
+ if (typeof req.body === 'object') {
113
+ if (!isEmpty(req.body) && !analyzedBodies.has(req.body)) {
114
+ requestData[addresses.HTTP_INCOMING_BODY] = req.body
115
+ }
116
+ } else {
117
+ requestData[addresses.HTTP_INCOMING_BODY] = req.body
117
118
  }
118
- } else {
119
- persistent[addresses.HTTP_INCOMING_BODY] = req.body
120
119
  }
121
- }
122
-
123
- // we need to keep this to support other cookie parsers
124
- if (
125
- req.cookies !== null &&
126
- typeof req.cookies === 'object' &&
127
- !isEmpty(req.cookies) &&
128
- !analyzedCookies.has(req.cookies)
129
- ) {
130
- persistent[addresses.HTTP_INCOMING_COOKIES] = req.cookies
131
- }
132
120
 
133
- // we need to keep this to support nextjs
134
- const query = req.query
135
- if (
136
- query !== null &&
137
- typeof query === 'object' &&
138
- !isEmpty(query)
139
- ) {
140
- persistent[addresses.HTTP_INCOMING_QUERY] = query
141
- }
121
+ // we need to keep this to support other cookie parsers
122
+ if (
123
+ req.cookies !== null &&
124
+ typeof req.cookies === 'object' &&
125
+ !isEmpty(req.cookies) &&
126
+ !analyzedCookies.has(req.cookies)
127
+ ) {
128
+ requestData[addresses.HTTP_INCOMING_COOKIES] = req.cookies
129
+ }
142
130
 
143
- // This hook runs before span finish, so ensure route/endpoint tags are available before API Security sampling runs.
144
- web.setRouteOrEndpointTag(req)
131
+ // we need to keep this to support nextjs
132
+ const query = req.query
133
+ if (
134
+ query !== null &&
135
+ typeof query === 'object' &&
136
+ !isEmpty(query)
137
+ ) {
138
+ requestData[addresses.HTTP_INCOMING_QUERY] = query
139
+ }
145
140
 
146
- if (config.appsec.DD_API_SECURITY_ENABLED) {
147
- try {
148
- const normalized = normalizeRoute(req)
149
- if (normalized !== null) {
150
- web.root(req)?.setTag('_dd.appsec.normalized_route', normalized)
141
+ // This hook runs before span finish, so ensure route/endpoint tags are available before API Security sampling runs.
142
+ web.setRouteOrEndpointTag(req)
143
+
144
+ if (config.appsec.DD_API_SECURITY_ENABLED) {
145
+ try {
146
+ const normalized = normalizeRoute(req)
147
+ if (normalized !== null) {
148
+ web.root(req)?.setTag('_dd.appsec.normalized_route', normalized)
149
+ }
150
+ } catch (e) {
151
+ log.debug('[ASM] Unable to compute normalized route: %s', e.message)
151
152
  }
152
- } catch (e) {
153
- log.debug('[ASM] Unable to compute normalized route: %s', e.message)
154
153
  }
155
- }
156
-
157
- const apiSecSamplingDecision = apiSecurity.sampleRequest(req, res, true)
158
- if (apiSecSamplingDecision === apiSecurity.SamplingDecision.SAMPLE) {
159
- persistent[addresses.WAF_CONTEXT_PROCESSOR] = { 'extract-schema': true }
160
- }
161
154
 
162
- let wafResult
163
- if (!isEmpty(persistent)) {
164
- wafResult = waf.run({ persistent }, req)
165
- }
155
+ const apiSecSamplingDecision = apiSecurity.sampleRequest(req, res, true)
156
+ if (apiSecSamplingDecision === apiSecurity.SamplingDecision.SAMPLE) {
157
+ requestData[addresses.WAF_CONTEXT_PROCESSOR] = { 'extract-schema': true }
158
+ }
166
159
 
167
- apiSecurity.reportRequest(req, apiSecSamplingDecision, wafResult)
160
+ let wafResult
161
+ if (!isEmpty(requestData)) {
162
+ wafResult = waf.run(requestData, req)
163
+ }
168
164
 
169
- waf.disposeContext(req)
165
+ apiSecurity.reportRequest(req, apiSecSamplingDecision, wafResult)
166
+ } finally {
167
+ waf.disposeContext(req)
168
+ }
170
169
 
171
170
  const storedHeaders = storedResponseHeaders.get(req) || {}
172
171
 
@@ -190,9 +189,7 @@ function onRequestQueryParsed ({ req, res, query, abortController }) {
190
189
  if (!rootSpan || isEmpty(query)) return
191
190
 
192
191
  const results = waf.run({
193
- persistent: {
194
- [addresses.HTTP_INCOMING_QUERY]: query,
195
- },
192
+ [addresses.HTTP_INCOMING_QUERY]: query,
196
193
  }, req)
197
194
 
198
195
  handleResults(results?.actions, req, res, rootSpan, abortController)
@@ -203,9 +200,7 @@ function onRequestProcessParams ({ req, res, abortController, params }) {
203
200
  if (!rootSpan || !params || typeof params !== 'object' || isEmpty(params)) return
204
201
 
205
202
  const results = waf.run({
206
- persistent: {
207
- [addresses.HTTP_INCOMING_PARAMS]: params,
208
- },
203
+ [addresses.HTTP_INCOMING_PARAMS]: params,
209
204
  }, req)
210
205
 
211
206
  handleResults(results?.actions, req, res, rootSpan, abortController)
@@ -1,14 +1,69 @@
1
1
  'use strict'
2
2
 
3
+ const { Stream } = require('node:stream')
4
+
3
5
  const web = require('../../plugins/util/web')
4
6
  const { isEmpty } = require('../../util')
5
7
  const addresses = require('../addresses')
6
8
  const apiSecurity = require('../api_security')
7
9
  const { isBlocked, callBlockDelegation, handleResults } = require('../blocking')
10
+ const { getActiveRequest } = require('../store')
8
11
  const waf = require('../waf')
9
12
  const { storedResponseHeaders, copyHeadersOmitting } = require('./http-shared')
10
13
 
11
14
  const responseAnalyzedSet = new WeakSet()
15
+ const nextResponseBodies = new WeakMap()
16
+
17
+ /**
18
+ * @param {unknown} body
19
+ * @returns {body is object}
20
+ */
21
+ function isJsonBody (body) {
22
+ return body !== null && typeof body === 'object' && !Buffer.isBuffer(body) && !(body instanceof Stream)
23
+ }
24
+
25
+ /**
26
+ * @param {{ stream: ReadableStream | null, body: unknown }} ctx
27
+ */
28
+ function onNextJsonResponse ({ stream, body }) {
29
+ // NextResponse wraps the native Response but retains its body stream.
30
+ if (stream && isJsonBody(body)) nextResponseBodies.set(stream, body)
31
+ }
32
+
33
+ /**
34
+ * Pages Router `res.json()` and `res.send()`.
35
+ *
36
+ * @param {{ arguments: unknown[] }} ctx
37
+ */
38
+ function onNextResponseBody (ctx) {
39
+ const body = ctx.arguments[0]
40
+ if (!isJsonBody(body)) return
41
+
42
+ const req = /** @type {import('node:http').IncomingMessage | undefined} */ (getActiveRequest())
43
+ if (!req || req.method === 'HEAD') return
44
+
45
+ const res = web.getContext(req)?.res
46
+ if (res) onResponseBody({ req, res, body })
47
+ }
48
+
49
+ /**
50
+ * App Router route handler result. Only the returned response is analyzed.
51
+ *
52
+ * @param {{ result?: Response, error?: unknown }} ctx
53
+ */
54
+ function onNextAppRouteResponse (ctx) {
55
+ // Async completion is also published for rejected route handlers, including rejection with undefined.
56
+ if ('error' in ctx) return
57
+
58
+ const response = ctx.result
59
+ const body = response?.body && nextResponseBodies.get(response.body)
60
+ if (!body) return
61
+
62
+ const req = /** @type {import('node:http').IncomingMessage | undefined} */ (getActiveRequest())
63
+ if (!req || req.method === 'HEAD') return
64
+
65
+ onResponseBody({ req, res: { statusCode: response.status }, body })
66
+ }
12
67
 
13
68
  function onResponseBody ({ req, res, body }) {
14
69
  if (
@@ -21,9 +76,7 @@ function onResponseBody ({ req, res, body }) {
21
76
 
22
77
  // we don't support blocking at this point, so no results needed
23
78
  waf.run({
24
- persistent: {
25
- [addresses.HTTP_INCOMING_RESPONSE_BODY]: body,
26
- },
79
+ [addresses.HTTP_INCOMING_RESPONSE_BODY]: body,
27
80
  }, req)
28
81
  }
29
82
 
@@ -59,10 +112,8 @@ function onResponseWriteHead ({ req, res, abortController, statusCode, responseH
59
112
  if (!rootSpan) return
60
113
 
61
114
  const results = waf.run({
62
- persistent: {
63
- [addresses.HTTP_INCOMING_RESPONSE_CODE]: String(statusCode),
64
- [addresses.HTTP_INCOMING_RESPONSE_HEADERS]: copyHeadersOmitting(normalizedResponseHeaders, 'set-cookie'),
65
- },
115
+ [addresses.HTTP_INCOMING_RESPONSE_CODE]: String(statusCode),
116
+ [addresses.HTTP_INCOMING_RESPONSE_HEADERS]: copyHeadersOmitting(normalizedResponseHeaders, 'set-cookie'),
66
117
  }, req)
67
118
 
68
119
  responseAnalyzedSet.add(res)
@@ -77,6 +128,9 @@ function onResponseOperation ({ res, abortController }) {
77
128
  }
78
129
 
79
130
  module.exports = {
131
+ onNextAppRouteResponse,
132
+ onNextResponseBody,
133
+ onNextJsonResponse,
80
134
  onResponseBody,
81
135
  onResponseWriteHead,
82
136
  onResponseOperation,
@@ -7,19 +7,17 @@ function onStripeCheckoutSessionCreate (payload) {
7
7
  if (payload?.mode !== 'payment') return
8
8
 
9
9
  waf.run({
10
- persistent: {
11
- [addresses.PAYMENT_CREATION]: {
12
- integration: 'stripe',
13
- id: payload.id,
14
- amount_total: payload.amount_total,
15
- client_reference_id: payload.client_reference_id,
16
- currency: payload.currency,
17
- 'discounts.coupon': payload.discounts?.[0]?.coupon,
18
- 'discounts.promotion_code': payload.discounts?.[0]?.promotion_code,
19
- livemode: payload.livemode,
20
- 'total_details.amount_discount': payload.total_details?.amount_discount,
21
- 'total_details.amount_shipping': payload.total_details?.amount_shipping,
22
- },
10
+ [addresses.PAYMENT_CREATION]: {
11
+ integration: 'stripe',
12
+ id: payload.id,
13
+ amount_total: payload.amount_total,
14
+ client_reference_id: payload.client_reference_id,
15
+ currency: payload.currency,
16
+ 'discounts.coupon': payload.discounts?.[0]?.coupon,
17
+ 'discounts.promotion_code': payload.discounts?.[0]?.promotion_code,
18
+ livemode: payload.livemode,
19
+ 'total_details.amount_discount': payload.total_details?.amount_discount,
20
+ 'total_details.amount_shipping': payload.total_details?.amount_shipping,
23
21
  },
24
22
  })
25
23
  }
@@ -28,15 +26,13 @@ function onStripePaymentIntentCreate (payload) {
28
26
  if (payload === null || typeof payload !== 'object') return
29
27
 
30
28
  waf.run({
31
- persistent: {
32
- [addresses.PAYMENT_CREATION]: {
33
- integration: 'stripe',
34
- id: payload.id,
35
- amount: payload.amount,
36
- currency: payload.currency,
37
- livemode: payload.livemode,
38
- payment_method: payload.payment_method,
39
- },
29
+ [addresses.PAYMENT_CREATION]: {
30
+ integration: 'stripe',
31
+ id: payload.id,
32
+ amount: payload.amount,
33
+ currency: payload.currency,
34
+ livemode: payload.livemode,
35
+ payment_method: payload.payment_method,
40
36
  },
41
37
  })
42
38
  }
@@ -45,11 +41,11 @@ function onStripeConstructEvent (payload) {
45
41
  const object = payload?.data?.object
46
42
  if (object === null || typeof object !== 'object') return
47
43
 
48
- let persistent
44
+ let requestData
49
45
 
50
46
  switch (payload.type) {
51
47
  case 'payment_intent.succeeded':
52
- persistent = {
48
+ requestData = {
53
49
  [addresses.PAYMENT_SUCCESS]: {
54
50
  integration: 'stripe',
55
51
  id: object.id,
@@ -62,7 +58,7 @@ function onStripeConstructEvent (payload) {
62
58
  break
63
59
 
64
60
  case 'payment_intent.payment_failed':
65
- persistent = {
61
+ requestData = {
66
62
  [addresses.PAYMENT_FAILURE]: {
67
63
  integration: 'stripe',
68
64
  id: object.id,
@@ -78,7 +74,7 @@ function onStripeConstructEvent (payload) {
78
74
  break
79
75
 
80
76
  case 'payment_intent.canceled':
81
- persistent = {
77
+ requestData = {
82
78
  [addresses.PAYMENT_CANCELLATION]: {
83
79
  integration: 'stripe',
84
80
  id: object.id,
@@ -94,7 +90,7 @@ function onStripeConstructEvent (payload) {
94
90
  return
95
91
  }
96
92
 
97
- waf.run({ persistent })
93
+ waf.run(requestData)
98
94
  }
99
95
 
100
96
  module.exports = {