dd-trace 6.25.0 → 6.27.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 +58 -1
  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
@@ -139,12 +139,12 @@ class TaintTrackingPlugin extends SourceIastPlugin {
139
139
  addDatabaseSubscriptions () {
140
140
  this.addSub(
141
141
  { channelName: 'datadog:sequelize:query:finish', tag: SQL_ROW_VALUE },
142
- ({ result }) => this._taintDatabaseResult(result, 'sequelize', getIastContext(storage('legacy').getStore()))
142
+ ({ result }) => this.#taintDatabaseResult(result, 'sequelize', getIastContext(storage('legacy').getStore()))
143
143
  )
144
144
 
145
145
  this.addSub(
146
146
  { channelName: 'apm:pg:query:finish', tag: SQL_ROW_VALUE },
147
- ({ result, currentStore }) => this._taintDatabaseResult(result, 'pg', getIastContext(currentStore))
147
+ ({ result, currentStore }) => this.#taintDatabaseResult(result, 'pg', getIastContext(currentStore))
148
148
  )
149
149
  }
150
150
 
@@ -263,25 +263,32 @@ class TaintTrackingPlugin extends SourceIastPlugin {
263
263
  this.taintUrl(req, iastContext)
264
264
  }
265
265
 
266
- _taintDatabaseResult (result, dbOrigin, iastContext, name) {
266
+ #taintDatabaseResult (result, dbOrigin, iastContext, name, visited) {
267
267
  if (!iastContext || this._rowsToTaint === 0) return result
268
268
 
269
+ if (typeof result === 'string') {
270
+ return newTaintedString(iastContext, result, name, SQL_ROW_VALUE)
271
+ }
272
+
273
+ // Binary views, such as pg bytea columns, only hold numbers.
274
+ if (result === null || typeof result !== 'object' || ArrayBuffer.isView(result)) return result
275
+
276
+ visited ??= new WeakSet()
277
+ if (visited.has(result)) return result
278
+ visited.add(result)
279
+
269
280
  if (Array.isArray(result)) {
270
281
  for (let i = 0; i < result.length && i < this._rowsToTaint; i++) {
271
282
  const nextName = name ? `${name}.${i}` : String(i)
272
- result[i] = this._taintDatabaseResult(result[i], dbOrigin, iastContext, nextName)
283
+ result[i] = this.#taintDatabaseResult(result[i], dbOrigin, iastContext, nextName, visited)
273
284
  }
274
- } else if (result && typeof result === 'object') {
275
- if (dbOrigin === 'sequelize' && result.dataValues) {
276
- result.dataValues = this._taintDatabaseResult(result.dataValues, dbOrigin, iastContext, name)
277
- } else {
278
- for (const key in result) {
279
- const nextName = name ? `${name}.${key}` : key
280
- result[key] = this._taintDatabaseResult(result[key], dbOrigin, iastContext, nextName)
281
- }
285
+ } else if (dbOrigin === 'sequelize' && result.dataValues) {
286
+ result.dataValues = this.#taintDatabaseResult(result.dataValues, dbOrigin, iastContext, name, visited)
287
+ } else {
288
+ for (const key of Object.keys(result)) {
289
+ const nextName = name ? `${name}.${key}` : key
290
+ result[key] = this.#taintDatabaseResult(result[key], dbOrigin, iastContext, nextName, visited)
282
291
  }
283
- } else if (typeof result === 'string') {
284
- result = newTaintedString(iastContext, result, name, SQL_ROW_VALUE)
285
292
  }
286
293
 
287
294
  return result
@@ -20,6 +20,9 @@ const {
20
20
  queryParser,
21
21
  nextBodyParsed,
22
22
  nextQueryParsed,
23
+ nextResponseBody,
24
+ nextJsonResponse,
25
+ nextAppRouteResponse,
23
26
  expressProcessParams,
24
27
  fastifyQueryParams,
25
28
  responseBody,
@@ -27,6 +30,7 @@ const {
27
30
  responseSetHeader,
28
31
  informationalResponse,
29
32
  routerParam,
33
+ routerRouteCreate,
30
34
  fastifyResponseChannel,
31
35
  fastifyPathParams,
32
36
  stripeCheckoutSessionCreate,
@@ -41,6 +45,7 @@ const UserTracking = require('./user_tracking')
41
45
  const graphql = require('./graphql')
42
46
  const lambda = require('./lambda')
43
47
  const rasp = require('./rasp')
48
+ const { onRouteCreate } = require('./api_security/normalized-route')
44
49
  const httpRequest = require('./handlers/http-request')
45
50
  const httpResponse = require('./handlers/http-response')
46
51
  const auth = require('./handlers/auth')
@@ -62,12 +67,16 @@ const channelHandlers = [
62
67
  [queryParser, httpRequest.onRequestQueryParsed],
63
68
  [nextBodyParsed, httpRequest.onRequestBodyParsed],
64
69
  [nextQueryParsed, httpRequest.onRequestQueryParsed],
70
+ [nextResponseBody, httpResponse.onNextResponseBody],
71
+ [nextJsonResponse, httpResponse.onNextJsonResponse],
72
+ [nextAppRouteResponse, httpResponse.onNextAppRouteResponse],
65
73
  [expressProcessParams, httpRequest.onRequestProcessParams],
66
74
  [fastifyBodyParser, httpRequest.onRequestBodyParsed],
67
75
  [fastifyQueryParams, httpRequest.onRequestQueryParsed],
68
76
  [fastifyCookieParser, httpRequest.onRequestCookieParser],
69
77
  [fastifyPathParams, httpRequest.onRequestProcessParams],
70
78
  [routerParam, httpRequest.onRequestProcessParams],
79
+ [routerRouteCreate, onRouteCreate],
71
80
  [responseBody, httpResponse.onResponseBody],
72
81
  [fastifyResponseChannel, httpResponse.onResponseBody],
73
82
  [responseWriteHead, httpResponse.onResponseWriteHead],
@@ -41,43 +41,43 @@ function onLambdaStartInvocation (data) {
41
41
  '_dd.runtime_family': 'nodejs',
42
42
  })
43
43
 
44
- const persistent = {}
44
+ const requestData = {}
45
45
 
46
46
  if (path) {
47
- persistent[addresses.HTTP_INCOMING_URL] = path
47
+ requestData[addresses.HTTP_INCOMING_URL] = path
48
48
  }
49
49
 
50
50
  if (method) {
51
- persistent[addresses.HTTP_INCOMING_METHOD] = method
51
+ requestData[addresses.HTTP_INCOMING_METHOD] = method
52
52
  }
53
53
 
54
54
  if (headers) {
55
55
  // Cookie header is already stripped by the Lambda layer's event-data-extractor
56
- persistent[addresses.HTTP_INCOMING_HEADERS] = headers
56
+ requestData[addresses.HTTP_INCOMING_HEADERS] = headers
57
57
  }
58
58
 
59
59
  if (clientIp) {
60
60
  span.setTag(HTTP_CLIENT_IP, clientIp)
61
- persistent[addresses.HTTP_CLIENT_IP] = clientIp
61
+ requestData[addresses.HTTP_CLIENT_IP] = clientIp
62
62
  }
63
63
 
64
64
  if (query) {
65
- persistent[addresses.HTTP_INCOMING_QUERY] = query
65
+ requestData[addresses.HTTP_INCOMING_QUERY] = query
66
66
  }
67
67
 
68
68
  if (body !== undefined && body !== null) {
69
- persistent[addresses.HTTP_INCOMING_BODY] = body
69
+ requestData[addresses.HTTP_INCOMING_BODY] = body
70
70
  }
71
71
 
72
72
  if (pathParams) {
73
- persistent[addresses.HTTP_INCOMING_PARAMS] = pathParams
73
+ requestData[addresses.HTTP_INCOMING_PARAMS] = pathParams
74
74
  }
75
75
 
76
76
  if (cookies) {
77
- persistent[addresses.HTTP_INCOMING_COOKIES] = cookies
77
+ requestData[addresses.HTTP_INCOMING_COOKIES] = cookies
78
78
  }
79
79
 
80
- waf.run({ persistent }, req, undefined, span)
80
+ waf.run(requestData, req, undefined, span)
81
81
  } catch (err) {
82
82
  log.error('[ASM] Error in Lambda start-invocation handler', err)
83
83
  }
@@ -108,16 +108,16 @@ function onLambdaEndInvocation (data) {
108
108
  activeInvocations.delete(span)
109
109
 
110
110
  try {
111
- const persistent = {}
111
+ const requestData = {}
112
112
 
113
113
  if (statusCode) {
114
- persistent[addresses.HTTP_INCOMING_RESPONSE_CODE] = String(statusCode)
114
+ requestData[addresses.HTTP_INCOMING_RESPONSE_CODE] = String(statusCode)
115
115
  }
116
116
 
117
117
  if (responseHeaders) {
118
118
  const filteredHeaders = { ...responseHeaders }
119
119
  delete filteredHeaders['set-cookie']
120
- persistent[addresses.HTTP_INCOMING_RESPONSE_HEADERS] = filteredHeaders
120
+ requestData[addresses.HTTP_INCOMING_RESPONSE_HEADERS] = filteredHeaders
121
121
  }
122
122
 
123
123
  const samplingDecision = apiSecurity.sampleRootSpanRequest(span, {
@@ -129,17 +129,17 @@ function onLambdaEndInvocation (data) {
129
129
  }, true)
130
130
 
131
131
  if (samplingDecision === apiSecurity.SamplingDecision.SAMPLE) {
132
- persistent[addresses.WAF_CONTEXT_PROCESSOR] = { 'extract-schema': true }
132
+ requestData[addresses.WAF_CONTEXT_PROCESSOR] = { 'extract-schema': true }
133
133
 
134
134
  const parsedBody = parseResponseBody(responseBody, responseHeaders, isBase64Encoded)
135
135
  if (parsedBody !== undefined) {
136
- persistent[addresses.HTTP_INCOMING_RESPONSE_BODY] = parsedBody
136
+ requestData[addresses.HTTP_INCOMING_RESPONSE_BODY] = parsedBody
137
137
  }
138
138
  }
139
139
 
140
140
  let wafResult
141
- if (!isEmpty(persistent)) {
142
- wafResult = waf.run({ persistent }, req, undefined, span)
141
+ if (!isEmpty(requestData)) {
142
+ wafResult = waf.run(requestData, req, undefined, span)
143
143
  }
144
144
 
145
145
  apiSecurity.reportRootSpanRequest(span, samplingDecision, wafResult)
@@ -31,20 +31,20 @@ function analyzeCommandInjection ({ file, fileArgs, shell, abortController }) {
31
31
  const req = getActiveRequest()
32
32
  if (!req) return
33
33
 
34
- const ephemeral = {}
34
+ const subcontextData = {}
35
35
  const raspRule = { type: RULE_TYPES.COMMAND_INJECTION }
36
36
  const params = fileArgs ? [file, ...fileArgs] : file
37
37
 
38
38
  if (shell) {
39
- ephemeral[addresses.SHELL_COMMAND] = params
39
+ subcontextData[addresses.SHELL_COMMAND] = params
40
40
  raspRule.variant = 'shell'
41
41
  } else {
42
42
  const commandParams = Array.isArray(params) ? params : [params]
43
- ephemeral[addresses.EXEC_COMMAND] = commandParams
43
+ subcontextData[addresses.EXEC_COMMAND] = commandParams
44
44
  raspRule.variant = 'exec'
45
45
  }
46
46
 
47
- const result = waf.run({ ephemeral }, req, raspRule)
47
+ const result = waf.runSubContext(subcontextData, raspRule)
48
48
 
49
49
  handleResult(result, req, web.getContext(req)?.res, abortController, config, raspRule)
50
50
  }
@@ -1,11 +1,14 @@
1
1
  'use strict'
2
2
 
3
+ const { types } = require('node:util')
4
+
3
5
  const web = require('../../plugins/util/web')
4
6
  const {
5
7
  setUncaughtExceptionCaptureCallbackStart,
6
8
  expressMiddlewareError,
7
9
  fastifyMiddlewareError,
8
10
  routerMiddlewareError,
11
+ nextRequestStart,
9
12
  } = require('../channels')
10
13
  const { block, registerBlockDelegation, isBlocked } = require('../blocking')
11
14
  const { updateRaspRuleMatchMetricTags } = require('../telemetry')
@@ -14,7 +17,13 @@ const sqli = require('./sql_injection')
14
17
  const lfi = require('./lfi')
15
18
  const cmdi = require('./command_injection')
16
19
 
17
- const { DatadogRaspAbortError } = require('./utils')
20
+ const { DatadogRaspAbortError, hasBlockingAbort, markToBlockOnDetection } = require('./utils')
21
+
22
+ // Same bound as the `cause` chain; libraries keep the abort error one or two errors deep.
23
+ const MAX_WRAPPING_ERRORS = 10
24
+
25
+ // Error.isError is available from Node.js 24, and util.types.isNativeError is deprecated from 24.2.0 (DEP0197).
26
+ const isError = Error.isError ?? types.isNativeError
18
27
 
19
28
  function removeAllListeners (emitter, event) {
20
29
  const listeners = emitter.listeners(event)
@@ -43,6 +52,52 @@ function findDatadogRaspAbortError (err, deep = 10) {
43
52
  }
44
53
  }
45
54
 
55
+ /**
56
+ * Finds the abort error of the request in the errors held by the own data properties of an error, for libraries that
57
+ * throw their own error and keep the original one outside of `cause` (sequelize's `parent`, typeorm's `driverError`).
58
+ * Only native errors are walked, and getters are not called.
59
+ *
60
+ * @param {unknown} error
61
+ * @param {import('http').IncomingMessage} req
62
+ * @returns {DatadogRaspAbortError | undefined}
63
+ */
64
+ function findWrappedDatadogRaspAbortError (error, req) {
65
+ if (!isError(error)) return
66
+
67
+ const errors = [error]
68
+ for (let i = 0; i < errors.length; i++) {
69
+ for (const key of Reflect.ownKeys(errors[i])) {
70
+ // Before Node.js 22, reading the descriptor of `stack` formats the stack trace and calls Error.prepareStackTrace.
71
+ if (key === 'stack') continue
72
+
73
+ const value = Reflect.getOwnPropertyDescriptor(errors[i], key)?.value
74
+ if (!isError(value)) continue
75
+
76
+ if (value instanceof DatadogRaspAbortError) {
77
+ if (value.req === req) return value
78
+ } else if (errors.length < MAX_WRAPPING_ERRORS) {
79
+ errors.push(value)
80
+ }
81
+ }
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Finds the abort error of the request in the error of a failed operation
87
+ *
88
+ * @param {unknown} error
89
+ * @param {import('http').IncomingMessage} [failedRequest]
90
+ * @returns {DatadogRaspAbortError | undefined}
91
+ */
92
+ function resolveAbortError (error, failedRequest) {
93
+ const directError = findDatadogRaspAbortError(error)
94
+ if (directError) return directError
95
+
96
+ if (!hasBlockingAbort(failedRequest)) return
97
+
98
+ return findWrappedDatadogRaspAbortError(error, failedRequest)
99
+ }
100
+
46
101
  function handleUncaughtExceptionMonitor (error) {
47
102
  if (!blockOnDatadogRaspAbortError({ error, isTopLevel: true })) return
48
103
 
@@ -84,8 +139,8 @@ function handleUncaughtExceptionMonitor (error) {
84
139
  }
85
140
  }
86
141
 
87
- function blockOnDatadogRaspAbortError ({ error, isTopLevel }) {
88
- const abortError = findDatadogRaspAbortError(error)
142
+ function blockOnDatadogRaspAbortError ({ error, req: failedRequest, isTopLevel }) {
143
+ const abortError = resolveAbortError(error, failedRequest)
89
144
  if (!abortError) return false
90
145
 
91
146
  const { req, res, blockingAction, raspRule, ruleTriggered } = abortError
@@ -106,6 +161,10 @@ function blockOnDatadogRaspAbortError ({ error, isTopLevel }) {
106
161
  return true
107
162
  }
108
163
 
164
+ function onNextRequestStart ({ req, ignoreError }) {
165
+ markToBlockOnDetection(req, ignoreError)
166
+ }
167
+
109
168
  function enable (config) {
110
169
  ssrf.enable(config)
111
170
  sqli.enable(config)
@@ -117,6 +176,7 @@ function enable (config) {
117
176
  expressMiddlewareError.subscribe(blockOnDatadogRaspAbortError)
118
177
  fastifyMiddlewareError.subscribe(blockOnDatadogRaspAbortError)
119
178
  routerMiddlewareError.subscribe(blockOnDatadogRaspAbortError)
179
+ nextRequestStart.subscribe(onNextRequestStart)
120
180
  }
121
181
 
122
182
  function disable () {
@@ -130,6 +190,7 @@ function disable () {
130
190
  expressMiddlewareError.unsubscribe(blockOnDatadogRaspAbortError)
131
191
  fastifyMiddlewareError.unsubscribe(blockOnDatadogRaspAbortError)
132
192
  routerMiddlewareError.unsubscribe(blockOnDatadogRaspAbortError)
193
+ nextRequestStart.unsubscribe(onNextRequestStart)
133
194
  }
134
195
 
135
196
  module.exports = {
@@ -77,13 +77,13 @@ function analyzeLfi (ctx) {
77
77
  }
78
78
 
79
79
  function analyzeLfiPath (path, req, res, abortController) {
80
- const ephemeral = {
80
+ const subcontextData = {
81
81
  [FS_OPERATION_PATH]: path,
82
82
  }
83
83
 
84
84
  const raspRule = { type: RULE_TYPES.LFI }
85
85
 
86
- const result = waf.run({ ephemeral }, req, raspRule)
86
+ const result = waf.runSubContext(subcontextData, raspRule, undefined, req)
87
87
  handleResult(result, req, res, abortController, config, raspRule)
88
88
  }
89
89
 
@@ -65,37 +65,27 @@ function analyzeSqlInjection (query, dbSystem, abortController) {
65
65
  }
66
66
  executedQueries.add(query)
67
67
 
68
- const ephemeral = {
68
+ const subcontextData = {
69
69
  [addresses.DB_STATEMENT]: query,
70
70
  [addresses.DB_SYSTEM]: dbSystem,
71
71
  }
72
72
 
73
73
  const raspRule = { type: RULE_TYPES.SQL_INJECTION }
74
74
 
75
- const result = waf.run({ ephemeral }, req, raspRule)
75
+ const result = waf.runSubContext(subcontextData, raspRule)
76
76
 
77
77
  handleResult(result, req, web.getContext(req)?.res, abortController, config, raspRule)
78
78
  }
79
79
 
80
- function hasInputAddress (payload) {
81
- return hasAddressesObjectInputAddress(payload.ephemeral) || hasAddressesObjectInputAddress(payload.persistent)
82
- }
83
-
84
- function hasAddressesObjectInputAddress (addressesObject) {
85
- return addressesObject && Object.keys(addressesObject)
86
- .some(address => address.startsWith('server.request') || address.startsWith('graphql.server'))
87
- }
88
-
89
- function clearQuerySet ({ payload }) {
90
- if (!payload) return
91
-
92
- const req = getActiveRequest()
93
- if (!req) return
80
+ function clearQuerySet ({ req, payload }) {
81
+ if (!req || !payload) return
94
82
 
95
83
  const executedQueries = reqQueryMap.get(req)
96
84
  if (!executedQueries) return
97
85
 
98
- if (hasInputAddress(payload)) {
86
+ const hasInput = Object.keys(payload)
87
+ .some(address => address.startsWith('server.request') || address.startsWith('graphql.server'))
88
+ if (hasInput) {
99
89
  executedQueries.clear()
100
90
  }
101
91
  }
@@ -2,7 +2,10 @@
2
2
 
3
3
  const { format } = require('url')
4
4
  const {
5
+ fetchRequestStart,
5
6
  httpClientRequestStart,
7
+ httpClientRequestError,
8
+ httpClientRequestFinish,
6
9
  httpClientResponseStart,
7
10
  httpClientResponseFinish,
8
11
  } = require('../channels')
@@ -21,17 +24,23 @@ function enable (_config) {
21
24
  config = _config
22
25
  downstream.enable(_config)
23
26
 
27
+ httpClientRequestFinish.subscribe(handleRequestFinish)
28
+ httpClientRequestError.subscribe(handleRequestError)
24
29
  httpClientRequestStart.subscribe(analyzeSsrf)
25
30
  httpClientResponseStart.subscribe(planResponseBodyCollection)
26
31
  httpClientResponseFinish.subscribe(handleResponseFinish)
32
+ fetchRequestStart.subscribe(analyzeFetchSsrf)
27
33
  }
28
34
 
29
35
  function disable () {
30
36
  downstream.disable()
31
37
 
38
+ httpClientRequestFinish.unsubscribe(handleRequestFinish)
39
+ httpClientRequestError.unsubscribe(handleRequestError)
32
40
  if (httpClientRequestStart.hasSubscribers) httpClientRequestStart.unsubscribe(analyzeSsrf)
33
41
  if (httpClientResponseStart.hasSubscribers) httpClientResponseStart.unsubscribe(planResponseBodyCollection)
34
42
  if (httpClientResponseFinish.hasSubscribers) httpClientResponseFinish.unsubscribe(handleResponseFinish)
43
+ if (fetchRequestStart.hasSubscribers) fetchRequestStart.unsubscribe(analyzeFetchSsrf)
35
44
  }
36
45
 
37
46
  function analyzeSsrf (ctx) {
@@ -40,33 +49,85 @@ function analyzeSsrf (ctx) {
40
49
 
41
50
  if (!req || !outgoingUrl) return
42
51
 
43
- const requestAddresses = downstream.extractRequestData(ctx)
52
+ // The subcontext stays on ctx for the response evaluation of the same outgoing request.
53
+ runRequestEvaluation(req, outgoingUrl, downstream.extractRequestData(ctx), ctx.abortController, ctx)
54
+ }
55
+
56
+ /**
57
+ * Evaluates an outgoing request of the global fetch before it is sent.
58
+ * @param {{ req: Request, init?: import('undici-types').RequestInit, abortController: AbortController }} ctx fetch
59
+ * instrumentation context, where `init` holds the options that fetch applies over `req`.
60
+ */
61
+ function analyzeFetchSsrf ({ req: request, init, abortController }) {
62
+ const req = getActiveRequest()
63
+ if (!req) return
44
64
 
45
- const ephemeral = {
65
+ // Fetch responses are not evaluated, so the request runs in a subcontext released right away.
66
+ runRequestEvaluation(req, request.url, downstream.extractFetchRequestData(request, init), abortController)
67
+ }
68
+
69
+ /**
70
+ * Runs the request variant of SSRF RASP and aborts the outgoing request when a rule blocks it.
71
+ * @param {import('http').IncomingMessage} req originating request.
72
+ * @param {string} outgoingUrl URL of the outgoing request.
73
+ * @param {object} requestAddresses method and headers of the outgoing request.
74
+ * @param {AbortController} abortController aborts the outgoing request.
75
+ * @param {import('../waf').SubcontextState} [subcontextState] keeps the WAF subcontext for later evaluations.
76
+ */
77
+ function runRequestEvaluation (req, outgoingUrl, requestAddresses, abortController, subcontextState) {
78
+ const subcontextData = {
46
79
  [addresses.HTTP_OUTGOING_URL]: outgoingUrl,
47
80
  ...requestAddresses,
48
81
  }
49
82
 
50
83
  const raspRule = { type: RULE_TYPES.SSRF, variant: 'request' }
51
84
 
52
- const result = waf.run({ ephemeral }, req, raspRule)
85
+ const result = waf.runSubContext(subcontextData, raspRule, subcontextState)
53
86
 
54
- handleResult(result, req, web.getContext(req)?.res, ctx.abortController, config, raspRule)
87
+ handleResult(result, req, web.getContext(req)?.res, abortController, config, raspRule)
55
88
 
56
89
  downstream.incrementDownstreamAnalysisCount(req)
57
90
  }
58
91
 
59
92
  /**
60
- * Channel handler: plans downstream response body capture once response headers are available.
93
+ * Evaluates redirects before the next hop, or plans response body capture.
61
94
  * @param {{ ctx: object, res: import('http').IncomingMessage }} payload channel payload.
62
95
  */
63
96
  function planResponseBodyCollection ({ ctx, res }) {
64
- const originatingRequest = getActiveRequest()
97
+ const originatingRequest = waf.getRequest(ctx)
65
98
  if (!originatingRequest || !res) return
66
99
 
100
+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
101
+ // Record the redirect before application code can start the next hop.
102
+ ctx.ssrfResponseEvaluated = true
103
+ runResponseEvaluation(res, originatingRequest, null, ctx)
104
+ return
105
+ }
106
+
67
107
  downstream.planResponseBodyCollection(originatingRequest, res, ctx)
68
108
  }
69
109
 
110
+ /** @param {{ error?: Error, wafSubcontext?: import('../waf/waf_context_wrapper') }} ctx HTTP request context. */
111
+ function handleRequestError (ctx) {
112
+ // The error channel also publishes timeouts without an error; those can still receive a response.
113
+ if (ctx.error) waf.disposeSubContext(ctx)
114
+ }
115
+
116
+ /**
117
+ * @param {import('../waf').SubcontextState & { req?: import('http').ClientRequest,
118
+ * res?: import('http').IncomingMessage }} ctx HTTP request context.
119
+ */
120
+ function handleRequestFinish (ctx) {
121
+ // Ordinary responses still need their response-finish evaluation, including truncated bodies.
122
+ if (!waf.getRequest(ctx) || (ctx.res && !ctx.res.upgrade)) return
123
+ // Request finish is emitted only once and can precede a response after a timeout.
124
+ if (!ctx.res && ctx.req && !ctx.req.destroyed) {
125
+ ctx.req.once('close', () => handleRequestFinish(ctx))
126
+ return
127
+ }
128
+ waf.disposeSubContext(ctx)
129
+ }
130
+
70
131
  /**
71
132
  * Finalizes body collection for the response and triggers RASP analysis.
72
133
  * @param {object} params event payload from the channel.
@@ -75,14 +136,16 @@ function planResponseBodyCollection ({ ctx, res }) {
75
136
  * @param {string|Buffer|null} params.body collected body.
76
137
  */
77
138
  function handleResponseFinish ({ ctx, res, body }) {
78
- // downstream response object
79
- if (!res) return
80
-
81
- const originatingRequest = getActiveRequest()
82
- if (!originatingRequest) return
83
-
84
- const responseBody = ctx.shouldCollectBody ? body : null
85
- runResponseEvaluation(res, originatingRequest, responseBody)
139
+ const req = waf.getRequest(ctx)
140
+ if (!req) return
141
+
142
+ try {
143
+ if (!res || ctx.ssrfResponseEvaluated) return
144
+ const responseBody = ctx.shouldCollectBody ? body : null
145
+ runResponseEvaluation(res, req, responseBody, ctx)
146
+ } finally {
147
+ waf.disposeSubContext(ctx)
148
+ }
86
149
  }
87
150
 
88
151
  /**
@@ -90,14 +153,15 @@ function handleResponseFinish ({ ctx, res, body }) {
90
153
  * @param {import('http').IncomingMessage} res incoming response from downstream service.
91
154
  * @param {import('http').IncomingMessage} req originating request.
92
155
  * @param {string|Buffer|null} responseBody collected downstream response body.
156
+ * @param {object} ctx - Outgoing HTTP instrumentation context.
93
157
  */
94
- function runResponseEvaluation (res, req, responseBody) {
158
+ function runResponseEvaluation (res, req, responseBody, ctx) {
95
159
  const responseAddresses = downstream.extractResponseData(res, responseBody)
96
160
 
97
161
  if (isEmpty(responseAddresses)) return
98
162
 
99
163
  const raspRule = { type: RULE_TYPES.SSRF, variant: 'response' }
100
- const result = waf.run({ ephemeral: responseAddresses }, req, raspRule)
164
+ const result = waf.runSubContext(responseAddresses, raspRule, ctx)
101
165
 
102
166
  // TODO: this should be done in the waf functions directly instead of calling it everywhere
103
167
  const ruleTriggered = !!result?.events?.length
@@ -2,7 +2,7 @@
2
2
 
3
3
  const web = require('../../plugins/util/web')
4
4
  const { getCallsiteFrames, reportStackTrace, canReportStackTrace } = require('../stack_trace')
5
- const { getBlockingAction } = require('../blocking')
5
+ const { block, getBlockingAction, isBlocked } = require('../blocking')
6
6
  const log = require('../../log')
7
7
  const { updateRaspRuleMatchMetricTags } = require('../telemetry')
8
8
 
@@ -24,6 +24,30 @@ const ALLOWED_ROOTSPAN_NAMES = new Set([
24
24
  'fastify.request',
25
25
  ])
26
26
 
27
+ /** @type {WeakMap<import('http').IncomingMessage, ((error: Error) => void) | undefined>} */
28
+ const requestsToBlockOnDetection = new WeakMap()
29
+
30
+ /** @type {WeakSet<import('http').IncomingMessage>} */
31
+ const requestsWithBlockingAbort = new WeakSet()
32
+
33
+ /**
34
+ * Tells whether RASP aborted an operation of the request to block it.
35
+ *
36
+ * @param {import('http').IncomingMessage} req
37
+ */
38
+ function hasBlockingAbort (req) {
39
+ return requestsWithBlockingAbort.has(req)
40
+ }
41
+
42
+ /**
43
+ * @param {import('http').IncomingMessage} req
44
+ * @param {(error: Error) => void} [ignoreError] Keeps the abort error of a blocked request out of the framework's
45
+ * request errors.
46
+ */
47
+ function markToBlockOnDetection (req, ignoreError) {
48
+ requestsToBlockOnDetection.set(req, ignoreError)
49
+ }
50
+
27
51
  class DatadogRaspAbortError extends Error {
28
52
  constructor (req, res, blockingAction, raspRule, ruleTriggered) {
29
53
  super('DatadogRaspAbortError')
@@ -67,10 +91,28 @@ function handleResult (result, req, res, abortController, config, raspRule) {
67
91
 
68
92
  if (abortController && !abortOnUncaughtException) {
69
93
  const blockingAction = getBlockingAction(result?.actions)
70
- const rootSpanName = rootSpan?.context?.()?._name
94
+ const shouldBlockOnDetection = requestsToBlockOnDetection.has(req)
71
95
 
72
- if (blockingAction && ALLOWED_ROOTSPAN_NAMES.has(rootSpanName)) {
96
+ if (blockingAction && (shouldBlockOnDetection || ALLOWED_ROOTSPAN_NAMES.has(rootSpan?.context?.()?._name))) {
73
97
  const abortError = new DatadogRaspAbortError(req, res, blockingAction, raspRule, ruleTriggered)
98
+
99
+ if (shouldBlockOnDetection) {
100
+ // The blocking response is sent before the abort: once the operation fails, the framework can destroy the
101
+ // response before writing anything, as Next.js does when a stream fails before its first chunk.
102
+ let blocked = false
103
+ if (res) {
104
+ blocked = isBlocked(res) || block(req, res, rootSpan, null, blockingAction)
105
+ }
106
+ if (blocked) {
107
+ const ignoreError = requestsToBlockOnDetection.get(req)
108
+ ignoreError?.(abortError)
109
+ }
110
+ if (ruleTriggered) {
111
+ updateRaspRuleMatchMetricTags(req, raspRule, true, blocked)
112
+ }
113
+ }
114
+
115
+ requestsWithBlockingAbort.add(req)
74
116
  abortController.abort(abortError)
75
117
 
76
118
  return
@@ -84,6 +126,8 @@ function handleResult (result, req, res, abortController, config, raspRule) {
84
126
 
85
127
  module.exports = {
86
128
  handleResult,
129
+ hasBlockingAbort,
130
+ markToBlockOnDetection,
87
131
  RULE_TYPES,
88
132
  DatadogRaspAbortError,
89
133
  }