Repository navigation
Implement normalised http routes - #4101
estringana wants to merge 22 commits into
Conversation
Snapshots difference summaryThe following differences have been observed in committed snapshots. It is meant to help the reviewer. If you need to update snapshots, please refer to CONTRIBUTING.md 4 occurrences of : - "resource": "Laminas\\Router\\Http\\TreeRouteStack@match"
+ "resource": "Laminas\\Router\\Http\\TranslatorAwareTreeRouteStack@match"
|
❌ ErrorsYour PR has failed checks. Please review the issues below and take necessary action before merging. 🚦 24 Pipeline jobs failed
ℹ️ InfoNo other issues found (see more)❄️ No new flaky tests detected 🎯 Code Coverage (details) Useful? React with 👍 / 👎 This comment will be updated automatically if new data arrives.🔗 Commit SHA: 8e9a3f1 | Docs | View more details | Give us feedback! |
0cc69dd to
1fa5485
Compare
Benchmarks [ tracer ]Benchmark execution time: 2026-11-24 17:21:37 Comparing candidate commit 35431b4 in PR branch Found 1 performance improvements and 1 performance regressions! Performance is the same for 215 metrics, 1 unstable metrics.
|
a2be41b to
7b7f971
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7b7f9710a5
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
Do you have a rough estimate on the overhead of the route normalization? It seems expensive. Laminas is obviously just slow because it does runtime route matching, but other stacks like Slim or Symfony rely on precompiled routes. |
ff7f8fe to
8632abe
Compare
|
Approving from the stance of IDM, due to the new field being introduced |
b57a9e9 to
2ab71bd
Compare
34e4e8b to
f42c408
Compare
cataphract
left a comment
There was a problem hiding this comment.
It seems there are many gaps in framework support. I asked AI for failing counterexamples against the spec and got many:
I already removed a few that were obviously invalid (like, changing the routing type at runtime and complained about cache staleness), but the rest seem mostly valid
5d1199f to
d5e909b
Compare
|
@cataphract pr is ready back to you with all your comments addressed |
4cbeed5 to
82db9a3
Compare
cataphract
left a comment
There was a problem hiding this comment.
The mostly unreviewed implementation of the suggestions is at 82db9a3...glopes/normalise-http-route
396d141 to
6e42a3f
Compare
fb49f63 to
53105f7
Compare
There was a problem hiding this comment.
Valid branch-reset regex routes can copy captured request values into normalized route tags, exposing concrete parameters and creating unbounded route cardinality. A focused PHP reproduction confirms the failure.
🤖 Bits Code Review · Commit 53105f7
There was a problem hiding this comment.
More details
The PR adds normalized AppSec routes for Laravel, Symfony, Laminas, and WordPress, with other named frameworks explicitly excluded. The new guard fixes the previously reported branch-reset capture-numbering leak; the incremental review found no new issues, and no findings remain open.
🤖 Bits Code Review · Commit 2382960
There was a problem hiding this comment.
The PR adds normalized AppSec routes for Laravel, Symfony, Laminas, and WordPress; the earlier branch-reset leak is fixed. The latest Symfony optimization introduces two open regressions: stale route tags after external generator replacement in long-running workers, and lost route tagging when filter_var is unavailable.
🤖 Bits Code Review · Commit c8de8d8
Optionality was decided by walking the generator tokens, and nothing asserted that the walk is the one RouteCompiler::compilePattern() makes. The same went for participation: the replay was covered by cases whose answers we wrote down ourselves, so a wrong decision and a wrong expectation would have agreed. Drive thirteen route shapes through Symfony instead. Each case compiles a real Route, hands the catalog the data CompiledUrlGeneratorDumper would have written, and then asserts two things our own tables cannot fake: the replayed regex is identical to CompiledRoute::getRegex(), and the variables reported as having taken part are the ones Symfony's matcher would bind from that regex, computed in the test from Symfony's regex by doMatch()'s rule (a capture that is set in the match took part). The shapes cover one and two trailing optionals, an optional sharing a segment with a mandatory variable, three subparts in one segment, an important variable, a defaulted variable before static text, a declared trailing slash, an optional spanning the whole path, a non-slash separator, catch-alls whose requirement does and does not accept an empty value, a default that violates its requirement, and host variables. The last of those is the only shape where the regex is not replayed, so it also pins where the tag is omitted. replayRegexFromGeneratorData() becomes public @internal for the regex assertion, as the WordPress subject check did.
The assertion held the replayed regex against CompiledRoute::getRegex(), which is the regex Symfony's compiler emits, and every shape failed on the trailing slash the replay adds. The replay is right: the matcher is what we reproduce, and CompiledUrlMatcherDumper rewrites a declared '/$' to '/?$' while CompiledUrlMatcherTrait retries the trimmed path to tell a match from a redirect, which is why matcherRegexFromRouteRegex() exists and matchedParamsFromReplay() guards the redirect case. Hold the regex against that matcher form instead. The participation oracle keeps the compiler's regex, so that a path the route does not describe stays "not served" there: a trailing slash the route never declared is a redirect for Symfony and an omitted tag for us, and both sides of that are already asserted.
WordPress was the one integration that did not touch the routing cache.
Its per-rule safety scan sat in a PHP static instead, which under FPM,
mod_php and CGI is reset before it can be read again -- WordPress matches
one rule per request -- and which grows unbounded in runtimes that keep
PHP state across requests. The verdict is a pure function of the rule, so
it belongs in the process-lifetime cache the other three use, where it is
also bounded and evicted.
The route itself stays uncached, and the call site now says why rather
than asserting it: a rule plus the set of captures that took part does
not determine the route the way a Laravel or Symfony template does.
'^([^/]+)(?:/x)?/([^/]+)$' matches 'a/x/b' and 'a/b' with both captures
present and normalizes to '/{param1}/x/{param2}' and '/{param1}/{param2}',
so keying on rule and participation would serve one for the other.
Unit tests: [7.0] failed on '/opt/important/{!page}', expecting
'/opt/important/{page}' and getting '/opt/important'. Important variables
arrived in Symfony 4.1; 3.4 matches variables with '#\{\w+\}#', so the
'!' leaves the placeholder as static text and the route compiles with no
variable at all. PHP 7.0 resolves symfony/routing to 3.4, because 4.x
requires PHP 7.1.3, so that one shape cannot hold there.
Probe the capability by compiling '/{!x}' and skip the shape when the
compiled route has no variable, the same way the non-ASCII subpattern
name is probed rather than keyed to a version.
The normalized route is now an OpenAPI path template:
- static text within a segment is kept (/users/user-{id}, /post-{param1});
- parameters in one segment stay separate with the text between them
(/photos/{id}.{format}) instead of being combined with '+';
- parameter names keep only [A-Za-z0-9_], other characters become '_'.
The catch-all representation ({paramN}) is unchanged, as it is still an
open question in the RFC.
Where presence of optional parameters cannot be determined, the route
falls back to its mandatory parameters instead of omitting the tag:
- Laravel: no capture map was recorded for the request;
- Symfony: the route cannot be replayed (host variables, compiler
mismatch) or the replay does not resolve the path. The cache entry now
holds the fallback before the replay regex;
- Laminas: the matched routes were not recorded or cannot be replayed.
The fallback is built from the named route's definitions (Regex and
translated literals still cannot be, and stay omitted).
WordPress rules declare no optional parameters, so its omissions stay.
docs/appsec_normalized_route.md lists where each integration falls back.
RFC-1125 replaces RFC-1103's normalization rules. Changes:
- Parameter names: each Unicode code point outside [A-Za-z0-9_] becomes
'_' (föo -> f_o). Names that are already valid keep them; a replaced
name equal to another name in the route gets the smallest numeric
suffix not used in the route (/a/{user_id_2}/{user_id}), so replaced
names colliding with each other are suffixed in path order.
- Unnamed parameters and catch-alls get param<N> with the smallest N not
used, in path order, including WordPress unnamed captures (previously
named after their group number). A catch-all is placed where it
matched, so a Laminas Wildcard continuing a segment gives
/wildcard-keys{param1}, not /{param1}.
- Percent-encoding: Laravel and Symfony match the decoded path, so a '%'
in their routes is literal and encoded as %25. Laminas and WordPress
match the encoded path and keep existing escapes.
- Symfony: an optional variable bound to an empty value is absent
(/catchall/ with rest = '' -> /catchall). The cache entry now carries
the mandatory variables, which stay in the route whatever their value.
- Laminas Regex is a whole-route regex: the route comes from what the
regex matched (static text outside captures, captures as parameters),
not from the spec, so spec/regex mismatches no longer omit the tag.
When the match cannot be replayed, the fallback keeps the regex's
literal text and mandatory captures instead of omitting the tag.
- WordPress: like WP::parse_request(), the rule is retried on the
URL-decoded subject instead of omitting the tag, and a rule without
"$" is a prefix route whose rest is an unnamed catch-all.
docs/appsec_normalized_route.md is updated to the RFC-1125 rules.
A match of another URL by application code after routing records
nothing, so it took the mandatory-parts fallback and overwrote the
normalized route of the request. It now keeps the route set by the
request's own routing.
The shared-prototype tests now expect RFC-1125 output: static text
stays in its segment (/normalized-proto/users.{format},
/normalized-proto.{format}/users).
Since AppSec's settings joined the tracer's configuration table, the tracer's copy of DD_API_SECURITY_ENABLED (used by the normalized route integrations) redefined AppSec's and broke every combined build. The setting is now shared, next to DD_APPSEC_ENABLED, so both read it.
- Symfony and Laravel only take word characters (and non-ASCII bytes)
as a variable name, so braces around anything else, such as
{file-name}, are literal text: /docs/{file-name} is now
/docs/%7Bfile-name%7D, not /docs. The inline-constraint syntax
{name:regex}, which neither framework has, is no longer stripped.
- Adjacent static fragments are joined before they are encoded, so a
percent escape split across them is kept: the Laminas Regex fallback
for /caf%C3%A9/(?<id>[0-9]+) is /caf%C3%A9/{id}, as its replay is.
- Laminas route templates are cached on the route stack with
ObjectKVStore instead of under spl_object_hash(), which a later stack
can reuse once the first is destroyed.
SpanData::$meta is deprecated in favour of $attributes, which the integrations now use for every other tag.
- A segment is split on valid variable expressions only, so braces
around a variable stay literal: /items/{{id}} is /items/%7B{id}%7D,
as Symfony's RouteCompiler reads it, not /items/%7B%7Bid%7D%7D.
- The WordPress rule scan treats a ']' right after '[' or '[^' as a
literal, as PCRE does, so parentheses inside such a class no longer
throw off capture tracking: ^docs/([](])[^/]+[])]$ is rejected.
RFC-1125 forbids omitting the tag because optional parts cannot be resolved. When WordPress may have matched another subject (PATH_INFO), or the rule matches neither WP::$request nor its decoded form, which captures took part is unknown: the route is now the rule's literal text and mandatory captures, without its optional parts. A rule that cannot be expressed as a route still gets no tag.
The ']' of a POSIX class such as [:alpha:] does not end the enclosing character class, which the regex scanners do not model: parentheses inside the class were taken for groups, and uncaptured request text could reach the normalized route. A regex holding [: [. or [= is now rejected as a route that cannot be expressed (RFC-1125).
Rejecting every regex with [: [. or [= dropped the tag of routes that
RFC-1125 can express, such as ^docs/([[:alpha:]]+)$ -> /docs/{param1}.
The scanners now skip a POSIX class, collating element or equivalence
class inside a character class the way PCRE's check_posix_syntax()
does, so its ']' no longer ends the enclosing class.
ctype_alnum() and ctype_xdigit() throw where ctype is not installed, which dropped the normalized route of WordPress rules and percent-encoded paths. Use core strspn() checks over the same ASCII characters instead.
To set http.route and _dd.appsec.normalized_route, the Symfony integration reads Symfony's compiled URL generator file (url_generating_routes.php in the kernel cache directory), looks up the matched route in it, and stores the result in ddtrace's process-wide routing cache. The routing cache key is computed from the route's data as read from that file on the current request. It cannot be computed from the file's path and modification time instead: after a deploy replaces the file, opcache may keep returning the previous contents for a while, and an entry built from those contents, under a key naming the new file, would then be served for the life of the PHP process. So the integration reads the generator file on every request, whether or not the route is already in the routing cache. With opcache enabled, that read is cheap: under a microsecond, whatever the number of routes. With opcache disabled, PHP parses and compiles the whole file on every request: 0.3 ms with 100 routes, 3 ms with 1000, 43 ms with 10000 (PHP 8.3), more than the routing cache saves. Opcache is disabled by default in long-running CLI servers such as RoadRunner and Swoole (opcache.enable_cli=0). With opcache disabled, PHP always reads the generator file from disk, so the integration always gets the file's current contents, and the file's path and modification time are enough to identify them. In that case the integration now builds the routing cache key from the file's path, its modification time, the route name and the locale, and reads the file only when that key is not in the routing cache. It does not store an entry while the file's modification time is the current second, because a second write within that second would leave the modification time unchanged. With opcache enabled, the key is still computed from the route's data, now hashed with xxh128 on PHP 8.1 and later instead of md5 (0.15 µs instead of 1.9 µs for a route of 2 KB). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1c3cde1 to
01b7e02
Compare
There was a problem hiding this comment.
Certain regex routes can expose concrete request values in normalized tags or bypass the safety rejection through Laminas fallback handling. Focused PHP probes confirmed both behaviors and verified the localized suggestions.
🤖 Bits Code Review · Commit 01b7e02
01b7e02 to
8e9a3f1
Compare
There was a problem hiding this comment.
Laminas route replay can exhaust PHP memory on a short, valid request with repeated static optionals. The exponential work occurs before the normalization cache lookup, so caching does not protect affected requests.
🤖 Bits Code Review · Commit 8e9a3f1
| $captures, | ||
| [$state] | ||
| ); | ||
| foreach ($optionalStates as $optionalState) { |
There was a problem hiding this comment.
Bound Laminas optional-route replay states
With AppSec and API Security enabled, repeated static optionals cause this replay to materialize exponentially many states. The reviewer reproduced PHP exhausting a 64 MiB memory limit for /p followed by 18 [/a] blocks and its matching 38-byte path, although the route regex matched immediately. This turns an otherwise valid request into a fatal failure. replaySignature() performs the enumeration before the cache lookup, so cache hits cannot prevent it. Bound or deduplicate the replay traversal and fall back safely when its budget is exceeded.
React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it
What each reaction means
- 👍 Useful: correct, and you're fixing it or will.
- 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
- 😕 Unclear: you can't tell what it means or why it matters.
- 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.
🤖 Bits Code Review · Open Bits AI session
Description
Add
_dd.appsec.normalized_routetag to HTTP framework integrations (Laravel, Slim, Symfony, Laminas, CakePHP, Yii, CodeIgniter, WordPress) per RFC-1125. The tag exposes a normalized form of the matched route, stripping concrete parameter values and framework-specific syntax (regexconstraints, optional markers) into a canonical{param}notation suitable for security analysis.Reviewer checklist