dd-trace 6.26.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 (69) hide show
  1. package/index.d.ts +58 -1
  2. package/initialize.mjs +5 -3
  3. package/package.json +9 -8
  4. package/packages/datadog-instrumentations/src/ai.js +88 -127
  5. package/packages/datadog-instrumentations/src/aws-lambda.js +9 -0
  6. package/packages/datadog-instrumentations/src/helpers/hooks.js +0 -1
  7. package/packages/datadog-instrumentations/src/helpers/instrument.js +1 -3
  8. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +4 -1
  9. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/ai.js +2 -0
  10. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql-jit.js +5 -3
  11. package/packages/datadog-instrumentations/src/modelcontextprotocol-sdk.js +26 -2
  12. package/packages/datadog-instrumentations/src/modelcontextprotocol-server.js +3 -1
  13. package/packages/datadog-instrumentations/src/path-to-regexp.js +11 -11
  14. package/packages/datadog-instrumentations/src/router.js +17 -1
  15. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +1 -1
  16. package/packages/datadog-plugin-aws-lambda/src/context/events.js +167 -0
  17. package/packages/datadog-plugin-aws-lambda/src/context/extractor.js +153 -0
  18. package/packages/datadog-plugin-aws-lambda/src/context/http.js +50 -0
  19. package/packages/datadog-plugin-aws-lambda/src/context/span-context.js +26 -0
  20. package/packages/datadog-plugin-aws-lambda/src/context/step-functions.js +142 -0
  21. package/packages/datadog-plugin-aws-lambda/src/context/types.d.ts +17 -0
  22. package/packages/datadog-plugin-aws-lambda/src/context/xray.js +67 -0
  23. package/packages/datadog-plugin-aws-lambda/src/index.js +52 -4
  24. package/packages/datadog-plugin-azure-functions/src/index.js +68 -12
  25. package/packages/datadog-plugin-fetch/src/index.js +7 -0
  26. package/packages/datadog-plugin-http/src/client.js +12 -0
  27. package/packages/datadog-plugin-http/src/server.js +18 -4
  28. package/packages/dd-trace/src/aiguard/client.js +7 -9
  29. package/packages/dd-trace/src/aiguard/evaluation.js +7 -2
  30. package/packages/dd-trace/src/aiguard/messages/utils.js +2 -2
  31. package/packages/dd-trace/src/aiguard/sdk.js +7 -2
  32. package/packages/dd-trace/src/appsec/api_security/normalized-route.js +273 -167
  33. package/packages/dd-trace/src/appsec/channels.js +1 -0
  34. package/packages/dd-trace/src/appsec/iast/taint-tracking/plugin.js +21 -14
  35. package/packages/dd-trace/src/appsec/index.js +3 -0
  36. package/packages/dd-trace/src/appsec/rasp/index.js +57 -3
  37. package/packages/dd-trace/src/appsec/rasp/utils.js +14 -0
  38. package/packages/dd-trace/src/carrier.js +7 -1
  39. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/index.js +4 -2
  40. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/worker/index.js +31 -19
  41. package/packages/dd-trace/src/config/generated-config-types.d.ts +10 -3
  42. package/packages/dd-trace/src/config/index.js +28 -2
  43. package/packages/dd-trace/src/config/parsers.js +25 -0
  44. package/packages/dd-trace/src/config/supported-configurations.json +27 -7
  45. package/packages/dd-trace/src/datastreams/http.js +57 -0
  46. package/packages/dd-trace/src/datastreams/index.js +24 -0
  47. package/packages/dd-trace/src/datastreams/pathway.js +33 -4
  48. package/packages/dd-trace/src/datastreams/processor.js +22 -3
  49. package/packages/dd-trace/src/lambda/handler-paths.js +1 -1
  50. package/packages/dd-trace/src/llmobs/constants/tags.js +1 -0
  51. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/index.js +33 -1
  52. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/utils.js +102 -1
  53. package/packages/dd-trace/src/llmobs/span_processor.js +3 -0
  54. package/packages/dd-trace/src/llmobs/tagger.js +9 -0
  55. package/packages/dd-trace/src/noop/span.js +0 -4
  56. package/packages/dd-trace/src/openfeature/flagging_provider.js +17 -0
  57. package/packages/dd-trace/src/opentelemetry/logs/otlp_transformer.js +2 -1
  58. package/packages/dd-trace/src/opentelemetry/metrics/otlp_transformer.js +2 -1
  59. package/packages/dd-trace/src/opentelemetry/otlp/otlp_transformer_base.js +16 -1
  60. package/packages/dd-trace/src/opentelemetry/trace/index.js +5 -4
  61. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +10 -6
  62. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +42 -26
  63. package/packages/dd-trace/src/opentracing/propagation/text_map.js +4 -4
  64. package/packages/dd-trace/src/plugin_manager.js +2 -0
  65. package/packages/dd-trace/src/plugins/util/inferred_proxy.js +3 -5
  66. package/packages/dd-trace/src/plugins/util/url.js +1 -1
  67. package/packages/dd-trace/src/register-loader.js +43 -0
  68. package/register.js +10 -44
  69. package/register.mjs +27 -0
@@ -5,31 +5,40 @@ const web = require('../../plugins/util/web')
5
5
  const { getParse, getMatch } = require('../../../../datadog-instrumentations/src/path-to-regexp')
6
6
 
7
7
  /**
8
- * Normalize an HTTP route to the RFC-1103 _dd.appsec.normalized_route format.
8
+ * Normalize an HTTP route to the _dd.appsec.normalized_route format.
9
9
  *
10
10
  * Rules: (1) starts with /, trailing slash only if declared; (2) no empty elements; (3) static
11
11
  * segments keep [A-Za-z0-9.-~_], other chars percent-encoded (UTF-8); (4) dynamic params render as
12
- * {name} (chars /?#+{} encoded, + reserved), shadowed duplicate names become paramN; (5) one URL
13
- * segment = one element, multiple params combine as {a+b}, a catch-all is a single terminal element;
14
- * (6) optional param elements are resolved per request against the matched URL.
12
+ * {name}, names limited to [A-Za-z0-9_] with an _N suffix on collision; (5) a segment keeps its static
13
+ * text and each param in place ('/photos/{id}.{format}'); (6) optional groups and catch-alls are
14
+ * resolved per request against the matched URL.
15
15
  *
16
16
  * Design: Express 5 / path-to-regexp 8 only. The route is parsed once by path-to-regexp's `parse()`
17
17
  * (token tree → segment templates, cached per route string). Per-request presence of optional
18
- * groups is resolved with path-to-regexp's own `match()` — we do not re-implement matching. Static-
19
- * only optional groups (no param to capture) are dropped (rendered absent). Express 4 ships
18
+ * groups is resolved with path-to-regexp's own `match()` — we do not re-implement matching. As in
19
+ * Express, the mount prefix matches the start of the URL, with the app Router's case sensitivity, and
20
+ * the served route the rest, with its own Router's options; each tries its alternatives in
21
+ * path-to-regexp's order (group included, then excluded), else req.params is used. Express 4 ships
20
22
  * path-to-regexp 0.x, which has no `parse()` → no tag.
21
23
  */
22
24
 
23
25
  // path-to-regexp's match() builds a regexp exponential in a route's optional-group count, so cap it;
24
- // routes with more optional groups are omitted.
26
+ // a part with more optional groups resolves presence from req.params, a route with more skips the
27
+ // render cache.
25
28
  const MAX_OPTIONAL_GROUPS = 8
26
29
 
30
+ // Rendered outputs cached per route; presence masks depend on the request, so bound them.
31
+ const MAX_CACHED_VARIANTS = 64
32
+
27
33
  // Keyed on the raw route string — bounded by declared routes (never attacker URLs), so it retains
28
34
  // for the process lifetime.
29
35
  const routeCache = new Map()
30
36
 
31
37
  const EMPTY_SET = new Set()
32
38
 
39
+ /** @type {WeakMap<object, RoutingOptions>} options of the Router that registered each Route */
40
+ const routeOptions = new WeakMap()
41
+
33
42
  /**
34
43
  * @typedef {{ type: 'slash', group: number }
35
44
  * | { type: 'static', text: string, group: number }
@@ -37,27 +46,41 @@ const EMPTY_SET = new Set()
37
46
  * | { type: 'wildcard', name: string, group: number }} RouteToken
38
47
  *
39
48
  * `group` is the id of the innermost enclosing optional `{...}` group (0 = top-level, always present).
49
+ * A wildcard gets its own group: a catch-all is always optional.
40
50
  *
41
51
  * @typedef {{ group: number, tokens: RouteToken[] }} RouteSegment
42
52
  *
43
53
  * @typedef {{ type: 'text', value: string } | { type: 'param', name: string }
44
54
  * | { type: 'wildcard', name: string } | { type: 'group', tokens: PathToRegexpToken[] }} PathToRegexpToken
45
55
  *
56
+ * @typedef {{ tokens: PathToRegexpToken[], groups: number[],
57
+ * matchers: Array<((url: string) => object | undefined) | undefined> }} RouteBranch
58
+ *
46
59
  * @typedef {{ segments: RouteSegment[], groupParent: Map<number, number>, optionalGroups: number[],
47
- * trailingSlash: boolean, precomputed: string | null,
48
- * matcher: ((url: string) => object | undefined) | null,
60
+ * tokens: PathToRegexpToken[], wildcards: RouteToken[], nameCount: Map<string, number>,
61
+ * precomputed: string | null, branches: RouteBranch[] | null,
49
62
  * variants?: Map<number, string> }} CompiledRoute
63
+ *
64
+ * @typedef {{ sensitive?: boolean, strict?: boolean, end?: boolean }} RoutingOptions - `end: false` for a mount
65
+ *
66
+ * @typedef {{ route: string, options: RoutingOptions }} MatchedPart
67
+ * A part of the route and the options of the Router layer that matched it.
68
+ *
69
+ * @typedef {(tokens: PathToRegexpToken[], options: { sensitive: boolean, trailing: boolean, end: boolean })
70
+ * => ((url: string) => { path: string, params: object } | undefined) | undefined} MatcherFactory
50
71
  */
51
72
 
52
73
  /**
53
74
  * Convert path-to-regexp's nested token tree into a flat segment model. Text tokens split on '/'
54
75
  * into slash + static tokens; each `{...}` group gets a fresh id (parent tracked in groupParent),
55
- * its inner tokens inherit it. A trailing empty top-level segment denotes a declared trailing slash.
76
+ * its inner tokens inherit it (groupIds maps each group token to its id).
56
77
  * @param {PathToRegexpToken[]} ptTokens
57
- * @returns {{ segments: RouteSegment[], groupParent: Map<number, number>, trailingSlash: boolean }}
78
+ * @returns {{ segments: RouteSegment[], groupParent: Map<number, number>,
79
+ * groupIds: Map<PathToRegexpToken, number> }}
58
80
  */
59
81
  function tokensToSegments (ptTokens) {
60
82
  const groupParent = new Map()
83
+ const groupIds = new Map()
61
84
  let nextGroupId = 0
62
85
  /** @type {RouteToken[]} */
63
86
  const flat = []
@@ -73,11 +96,14 @@ function tokensToSegments (ptTokens) {
73
96
  } else if (token.type === 'param') {
74
97
  flat.push({ type: 'param', name: token.name, group })
75
98
  } else if (token.type === 'wildcard') {
76
- flat.push({ type: 'wildcard', name: token.name, group })
99
+ nextGroupId++
100
+ groupParent.set(nextGroupId, group)
101
+ flat.push({ type: 'wildcard', name: token.name, group: nextGroupId })
77
102
  } else if (token.type === 'group') {
78
103
  nextGroupId++
79
104
  const groupId = nextGroupId
80
105
  groupParent.set(groupId, group)
106
+ groupIds.set(token, groupId)
81
107
  walk(token.tokens, groupId)
82
108
  }
83
109
  }
@@ -98,114 +124,80 @@ function tokensToSegments (ptTokens) {
98
124
  }
99
125
  if (cur) segments.push(cur)
100
126
 
101
- let trailingSlash = false
102
- const last = segments.at(-1)
103
- if (last && last.tokens.length === 0 && last.group === 0) {
104
- trailingSlash = true
105
- segments.pop()
106
- }
127
+ return { segments, groupParent, groupIds }
128
+ }
107
129
 
108
- return { segments, groupParent, trailingSlash }
130
+ /**
131
+ * List the route's alternatives in path-to-regexp's order (each group included, then excluded,
132
+ * earlier groups varying slowest), each with its flat tokens and the ids of its included groups.
133
+ * @param {PathToRegexpToken[]} tokens
134
+ * @param {Map<PathToRegexpToken, number>} groupIds
135
+ * @returns {Array<{ tokens: PathToRegexpToken[], groups: number[] }>}
136
+ */
137
+ function expandBranches (tokens, groupIds) {
138
+ let branches = [{ tokens: [], groups: [] }]
139
+ for (const token of tokens) {
140
+ const choices = token.type === 'group'
141
+ ? [...expandBranches(token.tokens, groupIds).map(inner => ({
142
+ tokens: inner.tokens,
143
+ groups: [groupIds.get(token), ...inner.groups],
144
+ })), { tokens: [], groups: [] }]
145
+ : [{ tokens: [token], groups: [] }]
146
+ branches = branches.flatMap(branch => choices.map(choice => ({
147
+ tokens: [...branch.tokens, ...choice.tokens],
148
+ groups: [...branch.groups, ...choice.groups],
149
+ })))
150
+ }
151
+ return branches
109
152
  }
110
153
 
111
154
  /**
112
155
  * Compile a raw route string into a CompiledRoute, or null when unsupported.
113
156
  * @param {string} route
114
157
  * @param {(pattern: string) => { tokens: PathToRegexpToken[] } | undefined} parse
115
- * @param {(route: string) => ((url: string) => object | undefined) | undefined} makeMatcher
116
158
  * @returns {CompiledRoute | null}
117
159
  */
118
- function compileRoute (route, parse, makeMatcher) {
160
+ function compileRoute (route, parse) {
119
161
  const parsed = parse(route)
120
162
  if (!Array.isArray(parsed?.tokens)) return null
121
163
 
122
- const { segments, groupParent, trailingSlash } = tokensToSegments(parsed.tokens)
123
-
124
- // Empty segments (a bare optional slash like '/users{/}', or '/a//b') carry no element; drop them.
125
- const cleaned = segments.filter(s => s.tokens.length > 0)
126
-
127
- if (cleaned.length === 0) {
128
- return {
129
- segments: [],
130
- groupParent: new Map(),
131
- optionalGroups: [],
132
- trailingSlash: false,
133
- precomputed: '/',
134
- matcher: null,
135
- }
136
- }
137
-
138
- // A catch-all must be the last token of the last segment (rule 5, terminal).
139
- for (let s = 0; s < cleaned.length; s++) {
140
- const toks = cleaned[s].tokens
141
- for (let k = 0; k < toks.length; k++) {
142
- if (toks[k].type === 'wildcard' && (s !== cleaned.length - 1 || k !== toks.length - 1)) return null
143
- }
144
- }
145
-
146
- // Collapse structural-only groups ('/a{{/b}}'): reparent each group to its nearest represented one.
147
- const represented = new Set()
148
- for (const seg of cleaned) {
149
- if (seg.group !== 0) represented.add(seg.group)
150
- for (const t of seg.tokens) if (t.group !== 0) represented.add(t.group)
151
- }
152
- const effectiveParent = new Map()
153
- for (const g of represented) {
154
- let p = groupParent.get(g)
155
- while (p !== 0 && p !== undefined && !represented.has(p)) p = groupParent.get(p)
156
- effectiveParent.set(g, p === undefined ? 0 : p)
157
- }
164
+ const { segments, groupParent, groupIds } = tokensToSegments(parsed.tokens)
158
165
 
159
- // Group presence is read from match()'s params, so a group is resolvable only via a uniquely named
160
- // param/wildcard (duplicate names collapse to one key). `paramGroups` = groups holding any param,
161
- // `detectable` = those we can resolve. Omit the route if a param group is unresolvable (would
162
- // mis-assign presence); a static-only group has no param, so it renders as absent (dropped).
163
166
  const nameCount = new Map()
164
- for (const seg of cleaned) {
165
- for (const t of seg.tokens) {
166
- if (t.type !== 'static') nameCount.set(t.name, (nameCount.get(t.name) ?? 0) + 1)
167
- }
168
- }
169
- const paramGroups = new Set()
170
- const detectable = new Set()
171
- for (const seg of cleaned) {
167
+ const wildcards = []
168
+ for (const seg of segments) {
172
169
  for (const t of seg.tokens) {
173
170
  if (t.type === 'static') continue
174
- // Resolvable only via a unique param the group holds DIRECTLY: a param in a nested optional
175
- // subgroup can be absent while this group is present, so it can't prove this group's presence.
176
- if (t.group !== 0 && nameCount.get(t.name) === 1) detectable.add(t.group)
177
- for (let g = t.group; g !== 0; g = groupParent.get(g)) paramGroups.add(g)
171
+ nameCount.set(t.name, (nameCount.get(t.name) ?? 0) + 1)
172
+ if (t.type === 'wildcard') wildcards.push(t)
178
173
  }
179
174
  }
180
- for (const g of represented) {
181
- if (paramGroups.has(g) && !detectable.has(g)) return null
182
- }
183
175
 
184
- // Only resolvable (param) groups become variants; static-only groups stay out and render absent.
185
- const optionalGroups = [...represented].filter(g => detectable.has(g)).sort((a, b) => a - b)
176
+ const optionalGroups = [...groupParent.keys()]
186
177
 
187
178
  const compiled = {
188
- segments: cleaned,
189
- groupParent: effectiveParent,
179
+ segments,
180
+ groupParent,
190
181
  optionalGroups,
191
- trailingSlash,
182
+ tokens: parsed.tokens,
183
+ wildcards,
184
+ nameCount,
192
185
  precomputed: null,
193
- matcher: null,
186
+ branches: null,
187
+ }
188
+
189
+ // match()'s regexp is exponential in the route's TOTAL optional-group count (static and structural
190
+ // groups included, not just the resolvable ones), so cap that before building the matcher. A route
191
+ // without groups still gets its single branch: as a mount, it must match to consume its part.
192
+ if (groupIds.size <= MAX_OPTIONAL_GROUPS) {
193
+ compiled.branches = expandBranches(parsed.tokens, groupIds).map(branch => ({ ...branch, matchers: [] }))
194
194
  }
195
195
 
196
- // No optional groups → fixed output, computed once (no matcher, so group count is irrelevant here).
196
+ // No optional groups → fixed output, computed once.
197
197
  if (optionalGroups.length === 0) {
198
198
  compiled.precomputed = renderRoute(compiled, EMPTY_SET)
199
199
  return compiled
200
200
  }
201
-
202
- // match()'s regexp is exponential in the route's TOTAL optional-group count (static and structural
203
- // groups included, not just the resolvable ones), so cap that before building the matcher.
204
- if (groupParent.size > MAX_OPTIONAL_GROUPS) return null
205
-
206
- const matcher = makeMatcher(route)
207
- if (matcher === undefined) return null
208
- compiled.matcher = matcher
209
201
  compiled.variants = new Map()
210
202
  return compiled
211
203
  }
@@ -225,12 +217,13 @@ function groupActive (g, groupParent, present) {
225
217
  }
226
218
 
227
219
  /**
228
- * URL-encode chars outside the RFC-1103 static alphabet [A-Za-z0-9.-~_]. The 'u' flag iterates whole
220
+ * URL-encode chars outside the static alphabet [A-Za-z0-9.-~_], keeping valid %XX escapes. The 'u' flag iterates whole
229
221
  * codepoints so surrogate pairs encode as correct multi-byte UTF-8.
230
222
  * @param {string} str
231
223
  */
232
224
  function encodeStaticSegment (str) {
233
- return str.replaceAll(/[^A-Za-z0-9.\-~_]/gu, c => {
225
+ return str.replaceAll(/%[0-9A-Fa-f]{2}|[^A-Za-z0-9.\-~_]/gu, c => {
226
+ if (c.length === 3) return c.toUpperCase()
234
227
  const code = c.charCodeAt(0)
235
228
  if (code < 0x80) return '%' + code.toString(16).toUpperCase().padStart(2, '0')
236
229
  try {
@@ -241,14 +234,6 @@ function encodeStaticSegment (str) {
241
234
  })
242
235
  }
243
236
 
244
- /**
245
- * URL-encode the 6 characters not allowed in a normalized param name (/?#+{}).
246
- * @param {string} name
247
- */
248
- function encodeParamName (name) {
249
- return name.replaceAll(/[/?#+{}]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0'))
250
- }
251
-
252
237
  /**
253
238
  * Render the normalized route for a given set of present optional groups.
254
239
  * @param {CompiledRoute} compiled
@@ -266,29 +251,23 @@ function renderRoute (compiled, present) {
266
251
  }
267
252
  }
268
253
 
269
- // Pass 2: a token keeps its (encoded) name iff it is the last present occurrence of that name;
270
- // earlier duplicates become paramN (skipping surviving names).
271
- const encodedNames = new Array(dyn.length)
254
+ // Pass 2: a valid name keeps itself at its last present occurrence (the value Express exposes);
255
+ // every other token takes its sanitized name if free, else the smallest free _N suffix.
256
+ const sanitized = dyn.map(t => t.name.replaceAll(/[^A-Za-z0-9_]/gu, '_'))
272
257
  const lastIndexByName = new Map()
273
258
  for (let idx = 0; idx < dyn.length; idx++) {
274
- encodedNames[idx] = encodeParamName(dyn[idx].name)
275
- lastIndexByName.set(encodedNames[idx], idx)
276
- }
277
- const used = new Set()
278
- for (let idx = 0; idx < dyn.length; idx++) {
279
- if (lastIndexByName.get(encodedNames[idx]) === idx) used.add(encodedNames[idx])
259
+ if (sanitized[idx] === dyn[idx].name) lastIndexByName.set(dyn[idx].name, idx)
280
260
  }
261
+ const used = new Set(lastIndexByName.keys())
281
262
  const resolvedNames = new Array(dyn.length)
282
- let counter = 1
283
263
  for (let idx = 0; idx < dyn.length; idx++) {
284
- if (lastIndexByName.get(encodedNames[idx]) === idx) {
285
- resolvedNames[idx] = encodedNames[idx]
286
- } else {
287
- while (used.has(`param${counter}`)) counter++
288
- resolvedNames[idx] = `param${counter}`
289
- used.add(`param${counter}`)
290
- counter++
264
+ let name = dyn[idx].name
265
+ if (lastIndexByName.get(name) !== idx) {
266
+ name = sanitized[idx]
267
+ for (let n = 2; used.has(name); n++) name = `${sanitized[idx]}_${n}`
268
+ used.add(name)
291
269
  }
270
+ resolvedNames[idx] = name
292
271
  }
293
272
 
294
273
  // Pass 3: build the output elements. Each present leading slash starts a new element; a segment
@@ -296,46 +275,41 @@ function renderRoute (compiled, present) {
296
275
  // '.json' in '/x{/:id}.json' survives when :id is absent) rather than being dropped with the slash.
297
276
  const out = []
298
277
  let dynPtr = 0
299
- let staticText = ''
300
- let paramNames = []
301
- let isCatchAll = false
302
-
303
- const flush = () => {
304
- if (isCatchAll) {
305
- out.push(`{${paramNames.join('+')}}`) // terminal catch-all; static prefix subsumed (rule 5)
306
- } else if (paramNames.length === 1) {
307
- out.push(`{${paramNames[0]}}`)
308
- } else if (paramNames.length > 1) {
309
- out.push(`{${paramNames.join('+')}}`)
310
- } else if (staticText !== '') {
311
- out.push(encodeStaticSegment(staticText))
312
- }
313
- staticText = ''
314
- paramNames = []
315
- isCatchAll = false
316
- }
278
+ let current = ''
279
+ let trailingSlash = false
317
280
 
318
281
  for (const seg of segments) {
319
- if (groupActive(seg.group, groupParent, present)) flush()
282
+ if (groupActive(seg.group, groupParent, present)) {
283
+ out.push(current)
284
+ current = ''
285
+ trailingSlash = true
286
+ }
320
287
  for (const t of seg.tokens) {
321
288
  if (!groupActive(t.group, groupParent, present)) continue
322
- if (t.type === 'static') {
323
- staticText += t.text
324
- } else {
325
- if (t.type === 'wildcard') isCatchAll = true
326
- paramNames.push(resolvedNames[dynPtr++])
327
- }
289
+ current += t.type === 'static' ? encodeStaticSegment(t.text) : `{${resolvedNames[dynPtr++]}}`
290
+ trailingSlash = false
328
291
  }
329
292
  }
330
- flush()
293
+ out.push(current)
294
+
295
+ const normalized = '/' + out.filter(Boolean).join('/')
296
+ return trailingSlash && normalized !== '/' ? normalized + '/' : normalized
297
+ }
331
298
 
332
- const normalized = '/' + out.join('/')
333
- return compiled.trailingSlash && normalized !== '/' ? normalized + '/' : normalized
299
+ /**
300
+ * True when a param value is missing or empty; a catch-all that captured only slashes is empty.
301
+ * @param {unknown} value - raw string (match) or decoded value (req.params)
302
+ * @param {boolean} wildcard
303
+ */
304
+ function isEmptyValue (value, wildcard) {
305
+ if (value === undefined || value === '') return true
306
+ if (!wildcard) return false
307
+ return Array.isArray(value) ? value.every(part => part === '') : /^\/*$/.test(String(value))
334
308
  }
335
309
 
336
310
  /**
337
311
  * Which optional groups are present, from a captured/params object: an optional group is present iff
338
- * one of its param tokens has a defined own-property value. Marks ancestor groups present too.
312
+ * one of its uniquely named param tokens has a non-empty own-property value. Marks ancestor groups present too.
339
313
  * @param {CompiledRoute} compiled
340
314
  * @param {object | null | undefined} params
341
315
  * @returns {Set<number>}
@@ -343,11 +317,11 @@ function renderRoute (compiled, present) {
343
317
  function resolvePresence (compiled, params) {
344
318
  const present = new Set()
345
319
  if (params == null) return present
346
- const { segments, groupParent } = compiled
320
+ const { segments, groupParent, nameCount } = compiled
347
321
  for (const seg of segments) {
348
322
  for (const t of seg.tokens) {
349
- if (t.group === 0 || t.type === 'static') continue
350
- if (Object.hasOwn(params, t.name) && params[t.name] !== undefined) {
323
+ if (t.group === 0 || t.type === 'static' || nameCount.get(t.name) > 1) continue
324
+ if (Object.hasOwn(params, t.name) && !isEmptyValue(params[t.name], t.type === 'wildcard')) {
351
325
  let g = t.group
352
326
  while (g !== 0 && !present.has(g)) {
353
327
  present.add(g)
@@ -359,6 +333,59 @@ function resolvePresence (compiled, params) {
359
333
  return present
360
334
  }
361
335
 
336
+ /**
337
+ * Which optional groups are present, from the first alternative matching the URL (the one Express
338
+ * served), with the matched path, or undefined when none can be matched. A catch-all is present
339
+ * unless it captured only slashes, or when another token of that alternative shares its name (its
340
+ * value can't be told apart).
341
+ * @param {CompiledRoute} compiled
342
+ * @param {string} path - request path, query stripped
343
+ * @param {MatcherFactory} makeMatcher
344
+ * @param {RoutingOptions} options
345
+ * @returns {{ present: Set<number>, path: string } | undefined}
346
+ */
347
+ function matchPresence (compiled, path, makeMatcher, options) {
348
+ const sensitive = options.sensitive === true
349
+ const strict = options.strict === true
350
+ const end = options.end !== false
351
+ const key = (sensitive ? 1 : 0) | (strict ? 2 : 0) | (end ? 0 : 4)
352
+ for (const branch of compiled.branches) {
353
+ let matcher = branch.matchers[key]
354
+ if (matcher === undefined) {
355
+ // Like Express's router, a non-strict route matches without its trailing slashes.
356
+ let { tokens } = branch
357
+ const last = compiled.tokens.at(-1)
358
+ if (!strict && last?.type === 'text' && last.value.endsWith('/')) {
359
+ let end = last.value.length
360
+ while (end > 0 && last.value[end - 1] === '/') end--
361
+ tokens = [...tokens.slice(0, -1), { type: 'text', value: last.value.slice(0, end) }]
362
+ }
363
+ matcher = makeMatcher(tokens, { sensitive, trailing: !strict, end })
364
+ if (matcher === undefined) return
365
+ branch.matchers[key] = matcher
366
+ }
367
+ const match = matcher(path)
368
+ if (match === undefined) continue
369
+
370
+ const { params } = match
371
+ const present = new Set(branch.groups)
372
+ for (const t of compiled.wildcards) {
373
+ let shared = false
374
+ if (compiled.nameCount.get(t.name) > 1) {
375
+ let count = 0
376
+ for (const other of branch.tokens) {
377
+ if (other.type !== 'text' && other.name === t.name && ++count === 2) {
378
+ shared = true
379
+ break
380
+ }
381
+ }
382
+ }
383
+ if (shared || !isEmptyValue(params[t.name], true)) present.add(t.group)
384
+ }
385
+ return { present, path: match.path }
386
+ }
387
+ }
388
+
362
389
  /**
363
390
  * Stable bitmask key for a present-group set (group ids are small, route-local).
364
391
  * @param {number[]} optionalGroups
@@ -372,6 +399,45 @@ function presenceBitmask (optionalGroups, present) {
372
399
  return mask
373
400
  }
374
401
 
402
+ /**
403
+ * @param {string} route
404
+ * @param {(pattern: string) => { tokens: PathToRegexpToken[] } | undefined} parse
405
+ */
406
+ function getCompiledRoute (route, parse) {
407
+ let entry = routeCache.get(route)
408
+ if (entry === undefined) {
409
+ entry = compileRoute(route, parse)
410
+ routeCache.set(route, entry)
411
+ }
412
+ return entry
413
+ }
414
+
415
+ /**
416
+ * Which optional groups of the joined route are present, from its parts matched in sequence against
417
+ * the path as Express routed it: a mount consumes the start, the next part matches the rest. Undefined
418
+ * when a part doesn't match. A part's group ids follow those of the parts before it.
419
+ * @param {MatchedPart[]} parts
420
+ * @param {string} path - request path, query stripped
421
+ * @param {(pattern: string) => { tokens: PathToRegexpToken[] } | undefined} parse
422
+ * @param {MatcherFactory} makeMatcher
423
+ * @returns {Set<number> | undefined}
424
+ */
425
+ function matchParts (parts, path, parse, makeMatcher) {
426
+ const present = new Set()
427
+ let offset = 0
428
+ for (const { route, options } of parts) {
429
+ const compiled = getCompiledRoute(route, parse)
430
+ if (compiled === null || compiled.branches === null) return
431
+
432
+ const matched = matchPresence(compiled, path, makeMatcher, options)
433
+ if (matched === undefined) return
434
+ for (const group of matched.present) present.add(group + offset)
435
+ offset += compiled.optionalGroups.length
436
+ path = path.slice(matched.path.length) || '/'
437
+ }
438
+ return present
439
+ }
440
+
375
441
  /**
376
442
  * Normalize an Express route string. Express 5 only: `parse`/`makeMatcher` are path-to-regexp 8's
377
443
  * `parse()` and a `match()` factory; returns null when either is unavailable (Express 4).
@@ -379,44 +445,74 @@ function presenceBitmask (optionalGroups, present) {
379
445
  * @param {object|null|undefined} params - req.params (fallback when the URL doesn't match)
380
446
  * @param {string|undefined} urlPath - request URL (query stripped here)
381
447
  * @param {(pattern: string) => { tokens: PathToRegexpToken[] } | undefined} parse
382
- * @param {(route: string) => ((url: string) => object | undefined) | undefined} makeMatcher
383
- * @returns {string|null}
448
+ * @param {MatcherFactory} makeMatcher
449
+ * @param {MatchedPart[]} [parts] - the route's parts, in order, as its Routers matched them
384
450
  */
385
- function normalizeRouteExpress (route, params, urlPath, parse, makeMatcher) {
451
+ function normalizeRouteExpress (route, params, urlPath, parse, makeMatcher, parts) {
386
452
  if (typeof route !== 'string' || !route || typeof parse !== 'function' || typeof makeMatcher !== 'function') {
387
453
  return null
388
454
  }
389
455
 
390
- let entry = routeCache.get(route)
391
- if (entry === undefined) {
392
- entry = compileRoute(route, parse, makeMatcher)
393
- routeCache.set(route, entry)
394
- }
456
+ const entry = getCompiledRoute(route, parse)
395
457
  if (entry === null) return null
396
458
  if (entry.precomputed !== null) return entry.precomputed
397
459
 
398
- // The matched URL is authoritative (handles mergeParams=false sub-routers); fall back to
399
- // req.params when there is no URL or it doesn't match.
400
- let matched
401
- if (urlPath) {
460
+ // The matched URL is authoritative (it keeps mount params that mergeParams=false drops); fall back
461
+ // to req.params when the route can't be split or the URL doesn't match.
462
+ let present
463
+ if (urlPath && parts !== undefined) {
402
464
  const qIdx = urlPath.indexOf('?')
403
- matched = entry.matcher(qIdx === -1 ? urlPath : urlPath.slice(0, qIdx))
465
+ present = matchParts(parts, qIdx === -1 ? urlPath : urlPath.slice(0, qIdx), parse, makeMatcher)
404
466
  }
405
- const present = resolvePresence(entry, matched ?? params)
467
+ present ??= resolvePresence(entry, params)
468
+
469
+ if (entry.optionalGroups.length > MAX_OPTIONAL_GROUPS) return renderRoute(entry, present)
406
470
 
407
471
  const mask = presenceBitmask(entry.optionalGroups, present)
408
472
  const cached = entry.variants.get(mask)
409
473
  if (cached !== undefined) return cached
410
474
 
411
475
  const result = renderRoute(entry, present)
412
- entry.variants.set(mask, result)
476
+ if (entry.variants.size < MAX_CACHED_VARIANTS) entry.variants.set(mask, result)
413
477
  return result
414
478
  }
415
479
 
480
+ /**
481
+ * Split the route where Express matched it: the mount prefix, with the app Router's case
482
+ * sensitivity, then the served route, with its own Router's options. Only route patterns and options
483
+ * are read: Express restores `req.url`/`req.baseUrl` once a request leaves a Router (e.g. to an app
484
+ * error handler). Undefined when the served Router's options are unknown (route registered while
485
+ * AppSec was off) or the route can't be split (a route array). A nested Router's own case
486
+ * sensitivity is not tracked per mount, so its mount matches with the app's: only alternatives
487
+ * differing by letter case can then resolve differently.
488
+ * @param {object} req
489
+ * @param {unknown} route - joined route (http.route)
490
+ * @returns {MatchedPart[] | undefined}
491
+ */
492
+ function splitRoute (req, route) {
493
+ const options = routeOptions.get(req.route)
494
+ const leaf = req.route?.path
495
+ if (options === undefined || typeof route !== 'string' || typeof leaf !== 'string') return
496
+
497
+ let prefix
498
+ if (route.endsWith(leaf)) {
499
+ prefix = route.slice(0, route.length - leaf.length)
500
+ } else if (leaf === '/') {
501
+ prefix = route // the router plugin leaves a mounted '/' out of http.route
502
+ } else {
503
+ return
504
+ }
505
+
506
+ const served = { route: leaf, options }
507
+ if (prefix === '') return [served]
508
+ // Mounts are never strict and match the start of the path.
509
+ const mount = { sensitive: req.app?.router?.caseSensitive === true, end: false }
510
+ return [{ route: prefix, options: mount }, served]
511
+ }
512
+
416
513
  /**
417
514
  * Normalize an HTTP route from a request. Reads the framework from the span component tag.
418
515
  * @param {object} req
419
- * @returns {string|null}
420
516
  */
421
517
  function normalizeRoute (req) {
422
518
  const spanContext = web.root(req)?.context()
@@ -435,15 +531,25 @@ function normalizeRoute (req) {
435
531
  if (parse === undefined || makeMatcher === undefined) return null
436
532
  // Reuse the http.route tag set by web.setRouteOrEndpointTag just before this hook.
437
533
  const route = spanContext.getTag(HTTP_ROUTE)
438
- return normalizeRouteExpress(route, req.params, req.originalUrl || req.url, parse, makeMatcher)
534
+ return normalizeRouteExpress(route, req.params, req.originalUrl || req.url, parse, makeMatcher,
535
+ splitRoute(req, route))
439
536
  }
440
537
  default:
441
538
  return null
442
539
  }
443
540
  }
444
541
 
542
+ /**
543
+ * Record the options of the Router that registered a Route (published by the router instrumentation).
544
+ * @param {{ route: object, sensitive: boolean, strict: boolean }} message
545
+ */
546
+ function onRouteCreate ({ route, sensitive, strict }) {
547
+ routeOptions.set(route, { sensitive, strict })
548
+ }
549
+
445
550
  module.exports = {
446
551
  normalizeRoute,
552
+ onRouteCreate,
447
553
  // exported for unit testing (framework-agnostic core)
448
554
  normalizeRouteExpress,
449
555
  }
@@ -51,6 +51,7 @@ module.exports = {
51
51
  responseWriteHead: dc.channel('apm:http:server:response:writeHead:start'),
52
52
  routerMiddlewareError: dc.channel('apm:router:middleware:error'),
53
53
  routerParam: dc.channel('datadog:router:param:start'),
54
+ routerRouteCreate: dc.channel('datadog:router:route:create'),
54
55
  setCookieChannel: dc.channel('datadog:iast:set-cookie'),
55
56
  setUncaughtExceptionCaptureCallbackStart: dc.channel('datadog:process:setUncaughtExceptionCaptureCallback:start'),
56
57
  startGraphqlResolver: dc.channel('datadog:graphql:resolver:start'),