Skip to content

Implement normalised http routes - #4101

Open
estringana wants to merge 46 commits into
masterfrom
estringana/normalise-http-route
Open

Implement normalised http routes#4101
estringana wants to merge 46 commits into
masterfrom
estringana/normalise-http-route

Conversation

@estringana

@estringana estringana commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Description

Add _dd.appsec.normalized_route tag to HTTP framework integrations (Laravel, Slim, Symfony, Laminas, CakePHP, Yii, CodeIgniter, WordPress) per RFC-1103. 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

  • Test coverage seems ok.
  • Appropriate labels assigned.

@github-actions

github-actions Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Snapshots difference summary

The following differences have been observed in committed snapshots. It is meant to help the reviewer.
The diff is simplistic, so please check some files anyway while we improve it.

If you need to update snapshots, please refer to CONTRIBUTING.md

@datadog-datadog-prod-us1-2

datadog-datadog-prod-us1-2 Bot commented Aug 10, 2026

Copy link
Copy Markdown

Pipelines  Tests

Unblock PR with BitsAI

⚠️ Warnings

Your PR has failed checks. Please review the issues below and take necessary action before merging.

🚦 2 Pipeline jobs failed

DataDog/apm-reliability/dd-trace-php | ASAN test_c with multiple observers: [8.4] — 🔧 Needs a code fix, caused by this PR

View more details · View in GitLab

DataDog/apm-reliability/dd-trace-php | publish docker image for system tests

View more details · View in GitLab

❄️ 2 New flaky tests detected

tmp/build_extension/tests/ext/routing_cache/cache_capacity_eviction.phpt (DDTrace\routing_cache evicts the oldest inserted entry when capacity (500) is excee... from PHP.tmp.build_extension.tests.ext.routing_cache
005+ ==5978==LeakSanitizer has encountered a fatal error.
006+ ==5978==HINT: For debugging, try setting environment variable LSAN_OPTIONS=verbosity=1:log_threads=1
007+ ==5978==HINT: LeakSanitizer does not work under ptrace (strace, gdb, etc)
008+ Aborted
009+ 
010+ Termsig=6
tmp/build_extension/tests/ext/routing_cache/cache_capacity_eviction.phpt (DDTrace\routing_cache evicts the oldest inserted entry when capacity (500) is excee... from php.tmp.build_extension.tests.ext.routing_cache
--
     bool(false)
     string(6) "value1"
     string(8) "value500"
005+ ==3778==LeakSanitizer has encountered a fatal error.
006+ ==3778==HINT: For debugging, try setting environment variable LSAN_OPTIONS=verbosity=1:log_threads=1
007+ ==3778==HINT: LeakSanitizer does not work under ptrace (strace, gdb, etc)
008+ Aborted
009+ 
010+ Termsig=6

View in Flaky Test Management

ℹ️ Info

No other issues found (see more)

🧪 All tests passed

🎯 Code Coverage (details)
Patch Coverage: 100.00%
Overall Coverage: 60.63% (+0.01%)

Useful? React with 👍 / 👎

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 82db9a3 | Docs | View more details | Give us feedback!

@estringana
estringana force-pushed the estringana/normalise-http-route branch 3 times, most recently from 0cc69dd to 1fa5485 Compare August 14, 2026 10:19
@pr-commenter

pr-commenter Bot commented Aug 14, 2026

Copy link
Copy Markdown

Benchmarks [ tracer ]

Benchmark execution time: 2026-09-02 12:43:28

Comparing candidate commit 82db9a3 in PR branch estringana/normalise-http-route with baseline commit 9c2caf0 in branch master.

Found 5 performance improvements and 43 performance regressions! Performance is the same for 145 metrics, 1 unstable metrics.

Explanation

This is an A/B test comparing a candidate commit's performance against that of a baseline commit. Performance changes are noted in the tables below as:

  • 🟩 = significantly better candidate vs. baseline
  • 🟥 = significantly worse candidate vs. baseline

We compute a confidence interval (CI) over the relative difference of means between metrics from the candidate and baseline commits, considering the baseline as the reference.

If the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD), the change is considered significant.

Feel free to reach out to #apm-benchmarking-platform on Slack if you have any questions.

More details about the CI and significant changes

You can imagine this CI as a range of values that is likely to contain the true difference of means between the candidate and baseline commits.

CIs of the difference of means are often centered around 0%, because often changes are not that big:

---------------------------------(------|---^--------)-------------------------------->
                              -0.6%    0%  0.3%     +1.2%
                                 |          |        |
         lower bound of the CI --'          |        |
sample mean (center of the CI) -------------'        |
         upper bound of the CI ----------------------'

As described above, a change is considered significant if the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD).

For instance, for an execution time metric, this confidence interval indicates a significantly worse performance:

----------------------------------------|---------|---(---------^---------)---------->
                                       0%        1%  1.3%      2.2%      3.1%
                                                  |   |         |         |
       significant impact threshold --------------'   |         |         |
                      lower bound of CI --------------'         |         |
       sample mean (center of the CI) --------------------------'         |
                      upper bound of CI ----------------------------------'

scenario:ComposerTelemetryBench/benchTelemetryParsing

  • 🟥 mem_peak [+151.904KB; +151.904KB] or [+3.741%; +3.741%]

scenario:ContextPropagationBench/benchExtractHeaders128Bit

  • 🟥 mem_peak [+163.616KB; +163.616KB] or [+4.029%; +4.029%]

scenario:ContextPropagationBench/benchExtractHeaders128Bit-opcache

  • 🟩 execution_time [-910.590ns; -830.743ns] or [-52.696%; -48.075%]

scenario:ContextPropagationBench/benchExtractHeaders64Bit

  • 🟥 mem_peak [+163.616KB; +163.616KB] or [+4.029%; +4.029%]

scenario:ContextPropagationBench/benchExtractTraceContext128Bit

  • 🟥 mem_peak [+163.616KB; +163.616KB] or [+4.029%; +4.029%]

scenario:ContextPropagationBench/benchExtractTraceContext64Bit

  • 🟥 mem_peak [+163.616KB; +163.616KB] or [+4.029%; +4.029%]

scenario:ContextPropagationBench/benchInject128Bit

  • 🟥 mem_peak [+163.624KB; +163.624KB] or [+4.029%; +4.029%]

scenario:ContextPropagationBench/benchInject128Bit-opcache

  • 🟩 execution_time [-855.123ns; -750.877ns] or [-34.109%; -29.951%]

scenario:ContextPropagationBench/benchInject64Bit

  • 🟥 mem_peak [+163.624KB; +163.624KB] or [+4.029%; +4.029%]

scenario:EmptyFileBench/benchEmptyFileBaseline

  • 🟥 mem_peak [+171.232KB; +171.232KB] or [+3.262%; +3.262%]

scenario:EmptyFileBench/benchEmptyFileDdprof

  • 🟥 mem_peak [+170.589KB; +172.531KB] or [+3.245%; +3.282%]

scenario:EmptyFileBench/benchEmptyFileOverhead

  • 🟥 mem_peak [+171.232KB; +171.232KB] or [+3.262%; +3.262%]

scenario:HookBench/benchHookOverheadInstallHookOnFunction

  • 🟥 mem_peak [+163.488KB; +163.488KB] or [+4.026%; +4.026%]

scenario:HookBench/benchHookOverheadInstallHookOnMethod

  • 🟥 mem_peak [+163.488KB; +163.488KB] or [+4.026%; +4.026%]

scenario:HookBench/benchHookOverheadTraceFunction

  • 🟥 mem_peak [+172.240KB; +172.240KB] or [+3.821%; +3.821%]

scenario:HookBench/benchHookOverheadTraceMethod

  • 🟥 mem_peak [+172.239KB; +172.242KB] or [+3.768%; +3.768%]

scenario:HookBench/benchHookOverheadTraceMethod-opcache

  • 🟩 execution_time [-17.533µs; -9.506µs] or [-9.657%; -5.236%]

scenario:HookBench/benchWithoutHook

  • 🟥 mem_peak [+163.504KB; +163.504KB] or [+4.027%; +4.027%]

scenario:LaravelBench/benchLaravelBaseline

  • 🟥 mem_peak [+171.264KB; +171.264KB] or [+3.262%; +3.262%]

scenario:LaravelBench/benchLaravelDdprof

  • 🟥 mem_peak [+171.389KB; +173.105KB] or [+3.259%; +3.292%]

scenario:LaravelBench/benchLaravelOverhead

  • 🟥 mem_peak [+171.264KB; +171.264KB] or [+3.262%; +3.262%]

scenario:LogsInjectionBench/benchLogsInfoBaseline

  • 🟥 mem_peak [+90.320KB; +90.320KB] or [+2.120%; +2.120%]

scenario:LogsInjectionBench/benchLogsInfoBaseline-opcache

  • 🟥 execution_time [+139.269ns; +194.931ns] or [+8.835%; +12.366%]

scenario:LogsInjectionBench/benchLogsInfoInjection

  • 🟥 mem_peak [+90.336KB; +90.336KB] or [+2.115%; +2.115%]

scenario:LogsInjectionBench/benchLogsNullBaseline

  • 🟥 mem_peak [+90.320KB; +90.320KB] or [+2.120%; +2.120%]

scenario:LogsInjectionBench/benchLogsNullInjection

  • 🟥 mem_peak [+90.336KB; +90.336KB] or [+2.110%; +2.110%]

scenario:MessagePackSerializationBench/benchMessagePackSerialization

  • 🟥 mem_peak [+172.240KB; +172.240KB] or [+3.989%; +3.989%]
  • 🟩 execution_time [-4.791µs; -2.949µs] or [-4.149%; -2.553%]

scenario:PDOBench/benchPDOBaseline

  • 🟥 mem_peak [+172.240KB; +172.240KB] or [+4.204%; +4.204%]

scenario:PDOBench/benchPDOOverhead

  • 🟥 mem_peak [+90.320KB; +90.320KB] or [+2.105%; +2.105%]

scenario:PDOBench/benchPDOOverheadWithDBM

  • 🟥 mem_peak [+90.320KB; +90.320KB] or [+2.105%; +2.105%]

scenario:PHPRedisBench/benchRedisBaseline

  • 🟥 mem_peak [+162.744KB; +162.744KB] or [+4.007%; +4.007%]

scenario:SamplingRuleMatchingBench/benchGlobMatching1

  • 🟥 mem_peak [+166.744KB; +166.744KB] or [+4.107%; +4.107%]

scenario:SamplingRuleMatchingBench/benchGlobMatching2

  • 🟥 mem_peak [+166.744KB; +166.744KB] or [+4.107%; +4.107%]

scenario:SamplingRuleMatchingBench/benchGlobMatching3

  • 🟥 mem_peak [+166.744KB; +166.744KB] or [+4.107%; +4.107%]

scenario:SamplingRuleMatchingBench/benchGlobMatching4

  • 🟥 mem_peak [+166.744KB; +166.744KB] or [+4.107%; +4.107%]

scenario:SamplingRuleMatchingBench/benchRegexMatching1

  • 🟥 mem_peak [+166.744KB; +166.744KB] or [+4.106%; +4.106%]

scenario:SamplingRuleMatchingBench/benchRegexMatching2

  • 🟥 mem_peak [+166.744KB; +166.744KB] or [+4.106%; +4.106%]

scenario:SamplingRuleMatchingBench/benchRegexMatching3

  • 🟥 mem_peak [+166.744KB; +166.744KB] or [+4.106%; +4.106%]

scenario:SamplingRuleMatchingBench/benchRegexMatching4

  • 🟥 mem_peak [+166.744KB; +166.744KB] or [+4.106%; +4.106%]

scenario:SpanBench/benchDatadogAPI

  • 🟥 mem_peak [+164.976KB; +164.976KB] or [+4.063%; +4.063%]

scenario:SymfonyBench/benchSymfonyBaseline

  • 🟥 mem_peak [+171.264KB; +171.264KB] or [+3.262%; +3.262%]

scenario:SymfonyBench/benchSymfonyDdprof

  • 🟥 mem_peak [+167.924KB; +175.915KB] or [+3.192%; +3.344%]

scenario:SymfonyBench/benchSymfonyOverhead

  • 🟥 mem_peak [+171.264KB; +171.264KB] or [+3.262%; +3.262%]

scenario:TraceAnnotationsBench/benchTraceAnnotationOverhead

  • 🟥 mem_peak [+172.240KB; +172.240KB] or [+3.762%; +3.762%]

scenario:TraceAnnotationsBench/benchTraceAnnotationOverhead-opcache

  • 🟩 execution_time [-9.082µs; -3.644µs] or [-5.017%; -2.013%]

scenario:TraceFlushBench/benchFlushTrace

  • 🟥 mem_peak [+172.239KB; +172.240KB] or [+4.158%; +4.158%]

scenario:TraceSerializationBench/benchSerializeTrace

  • 🟥 mem_peak [+172.240KB; +172.240KB] or [+4.064%; +4.064%]

@estringana
estringana force-pushed the estringana/normalise-http-route branch from a2be41b to 7b7f971 Compare August 14, 2026 12:53
@estringana
estringana marked this pull request as ready for review August 14, 2026 14:55
@estringana
estringana requested review from a team as code owners August 14, 2026 14:55
@estringana
estringana requested review from tabgok and removed request for a team August 14, 2026 14:55

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/DDTrace/Util/RouteNormalizer.php
Comment thread src/DDTrace/Integrations/Slim/SlimIntegration.php Outdated
Comment thread src/DDTrace/Integrations/WordPress/WordPressIntegrationLoader.php Outdated
Comment thread src/DDTrace/Integrations/CodeIgniter/V2/CodeIgniterIntegration.php Outdated
Comment thread src/DDTrace/Util/RouteNormalizer.php Outdated
Comment thread src/DDTrace/Util/RouteNormalizer.php Outdated
Comment thread src/DDTrace/Util/RouteNormalizer.php Outdated
Comment thread src/DDTrace/Integrations/Symfony/SymfonyIntegration.php Outdated
Comment thread src/DDTrace/Util/RouteNormalizer.php Outdated
Comment thread src/DDTrace/Util/RouteNormalizer.php
@bwoebi

bwoebi commented Aug 14, 2026

Copy link
Copy Markdown
Collaborator

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.
E.g. for Symfony we could make it part of the logic used in #3676. Please check if other frameworks have similar, acceptable solutions. Or consider some caching in the C code. (a LRU cache of route to normalized route with e.g. 500 routes max)

@estringana
estringana force-pushed the estringana/normalise-http-route branch from ff7f8fe to 8632abe Compare August 18, 2026 10:21
@tabgok

tabgok commented Aug 18, 2026

Copy link
Copy Markdown

Approving from the stance of IDM, due to the new field being introduced

@estringana
estringana force-pushed the estringana/normalise-http-route branch from b57a9e9 to 2ab71bd Compare August 18, 2026 15:55
Comment thread tracer/routing_cache.c Outdated
@estringana
estringana force-pushed the estringana/normalise-http-route branch from 34e4e8b to f42c408 Compare August 26, 2026 10:13
@estringana
estringana requested review from a team as code owners August 26, 2026 10:13

@cataphract cataphract left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems there are many gaps in framework support. I asked AI for failing counterexamples against the spec and got many:

https://github.com/DataDog/dd-trace-php/compare/estringana/normalise-http-route...glopes/normalise-http-route-failing?expand=1

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

Comment thread tests/ext/routing_cache/cache_capacity_eviction.phpt
Comment thread src/DDTrace/Integrations/CakePHP/CakePHPIntegration.php Outdated
Comment thread src/DDTrace/Integrations/Symfony/SymfonyIntegration.php Outdated
@estringana
estringana force-pushed the estringana/normalise-http-route branch from 5d1199f to d5e909b Compare August 27, 2026 16:12
@estringana

Copy link
Copy Markdown
Contributor Author

@cataphract pr is ready back to you with all your comments addressed

@estringana
estringana force-pushed the estringana/normalise-http-route branch from bdadbff to eddfd4f Compare September 1, 2026 16:12
estringana and others added 3 commits September 2, 2026 13:19
Add missing Tag::APPSEC_NORMALIZED_ROUTE assertions to:
- Symfony TraceSearchConfigTest (V4_4, V5_0, V5_1, V5_2, V6_2)
- Laravel TraceSearchConfigTest (V4, V5_7, V5_8, V8_x)
- Laravel V8_x RouteCachingTest and InternalExceptionsTest
- Laravel Octane CommonScenariosTest
- Yii ParameterizedRouteTest, ModuleTest, LazyLoadingIntegrationsFromYiiTest
- CodeIgniter ExitTest and NoCI_ControllertTest
- Fix UserAvailableConstantsTest tag ordering (APPSEC_NORMALIZED_ROUTE
  must appear after HTTP_ROUTE to match Tag.php declaration order)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
estringana and others added 28 commits September 2, 2026 13:19
…coding, regex constraints

- expandBracketOptionals: use strpos > 0 (not != false) so optional sections
  whose text coincidentally appears in the mandatory route prefix are not falsely
  detected as present; add case-insensitive fallback for percent-encoded param
  values so %c3%a9 (lowercase hex from browsers) matches %C3%A9 (rawurlencode output)
- normalizeFromLaminas: accept pre-computed $urlMatchedParams to skip
  inferSymfonyRouteParams when the caller has better information
- LaminasIntegration cache key: use '/'+value prefix check at position > 0 so
  params whose default value equals the mandatory route text are not treated as
  present; include static-only optional sections ([/draft]) in the key so absent
  and present shapes get distinct entries; for Regex routes, extract the actual
  route regex via reflection and run it against the URL to get accurate named
  captures, avoiding inferSymfonyRouteParams which ignores Laminas constraints
- SymfonyIntegration: use $route->compile()->getRegex() when available to
  determine URL-matched params instead of generic URL inference, so routes with
  requirements (e.g. format=html|json with a default) correctly exclude defaulted
  params from the normalized route

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@estringana
estringana force-pushed the estringana/normalise-http-route branch from 4cbeed5 to 82db9a3 Compare September 2, 2026 11:26

@cataphract cataphract left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mostly unreviewed implementation of the suggestions is at 82db9a3...glopes/normalise-http-route


for ($k = $n; $k >= 1; $k--) {
$regexBody = '';
for ($ri = 0; $ri < $k; $ri++) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Infer optional participation with Laravel’s compiled matcher

This does not follow the RFC’s request-specific optional-shape rule for mixed segments: it replaces every parameter with (.+), which ignores Laravel where() requirements. The subsequent comparison against $allParams cannot recover capture provenance because Laravel has already merged ->defaults() into that map. Example of such a failure:

route:       Regex /normalized-regex-chain/%name%.%ext% + Literal /view
requirement: ext=pdf|json
default:     ext=txt
request:     /normalized-regex-chain/report.txt/view
captures:    name=report.txt, ext absent
post-default route params: name=report.txt, ext=txt
RFC-compliant: omit the tag, or emit /normalized-regex-chain/{name}/view
actual:      /normalized-regex-chain/{name+ext}/view

Suggestion: replace this parser with the framework matcher Laravel used to bind the route. It already preserves requirements and optional-group participation:

private static function laravelUrlMatchedParams($route, $request, array $allParams): array
{
    $matches = [];
    $path = '/' . ltrim($request->decodedPath(), '/');
    if (preg_match($route->getCompiled()->getRegex(), $path, $matches) !== 1) {
        return $allParams;
    }

    $matched = [];
    foreach ($route->parameterNames() as $name) {
        if (isset($matches[$name]) && $matches[$name] !== ''
            && key_exists($name, $allParams)) {
            $matched[$name] = $allParams[$name];
        }
    }
    return $matched;
}

for ($k = $n; $k >= 1; $k--) {
$regexBody = '';
for ($i = 0; $i < $k; $i++) {
$regexBody .= preg_quote($staticParts[$i], '/') . '(.+)';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do not infer dynamic participation without the framework matcher

This helper is not an RFC-compliant fallback for dynamic optional components. The RFC requires optional parameter participation to come from framework match metadata or an exact replay of the compiled matcher; this synthesized (.+) expression ignores route requirements, optional-capture semantics, and unmatched positions. It can therefore report a parameter as present even when the framework rejected that capture and supplied a default instead.

The inference logic here also fails in specific examples, which I can provide if you want.

Please make “accurate participation unavailable” explicit (for example, return null) and have dynamic-route callers omit _dd.appsec.normalized_route in that case. URL-only best effort should be limited to purely static optional components, as allowed by the RFC.

$_present = [];
foreach ($_pm[1] as $_p) {
if (isset($allParams[$_p]) && $urlPath !== null &&
strpos($urlPath, '/' . (string)$allParams[$_p]) > 0) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Match Laminas optionals with the compiled Segment matcher

This cache is bounded, but the optional parameter participation test is not equivalent to Laminas routing. $allParams comes from RouteMatch::getParams(), where captured parameters and route defaults have already been merged. Searching those values and static fragments anywhere in the URL loses both capture provenance and route position.

Two concrete false positives are:

template: /prefix/:id[/:value]
URL:      /prefix/foo
matcher:  id=foo; value=foo comes only from the route default
expected: /prefix/{id}
actual:   /prefix/{id}/{value}
template: /prefix/:id[/foo]
URL:      /prefix/foo
matcher:  id=foo; optional static /foo absent
expected: /prefix/{id}
actual:   /prefix/{id}/foo

Nested static groups also collide in the cache:

template: /archive[/draft[/preview]]
first URL:  /archive       -> key /archive# -> caches /archive
second URL: /archive/draft -> same key, because the one-pass bracket regex
                              sees only the inner [/preview]
expected: /archive/draft
actual:   /archive

For dynamic optionals, the RFC requires participation to come from framework match metadata or an exact replay of the framework matcher. A defaulted value occurring somewhere in the URL is not evidence that its capture participated.

I tested replacing this heuristic with a replay of Laminas Segment::match() before defaults are merged. The important part is to use the Segment's compiled regex and paramMap, retain capture offsets, and walk the Segment's parsed parts at those exact offsets to recover the expanded route shape:

public static function inferLaminasSegmentMatch(
    \Laminas\Router\Http\Segment $route,
    string $urlPath
) {
    $routeData = \Closure::bind(
        static function ($segment) {
            return [
                $segment->regex,
                $segment->paramMap,
                $segment->parts,
                $segment->translationKeys,
            ];
        },
        null,
        \Laminas\Router\Http\Segment::class
    )($route);

    if (!is_array($routeData) || count($routeData) !== 4 || !empty($routeData[3])) {
        return null;
    }

    $matches = [];
    if (@preg_match(
        '(^' . $routeData[0] . '$)',
        $urlPath,
        $matches,
        PREG_OFFSET_CAPTURE
    ) !== 1) {
        return null;
    }

    $captures = [];
    $params = [];
    foreach ($routeData[1] as $group => $name) {
        if (!isset($matches[$group][0]) || $matches[$group][0] === '') {
            continue;
        }
        $captures[$name][] = [
            'raw' => $matches[$group][0],
            'offset' => $matches[$group][1],
        ];
        $params[$name] = rawurldecode($matches[$group][0]);
    }

    $states = [[
        'offset' => 0,
        'template' => '',
        'capture_indexes' => [],
    ]];
    $states = self::matchLaminasSegmentParts(
        $routeData[2],
        $urlPath,
        $captures,
        $states
    );

    foreach ($states as $state) {
        if ($state['offset'] !== strlen($urlPath)) {
            continue;
        }
        foreach ($captures as $name => $values) {
            if (($state['capture_indexes'][$name] ?? 0) !== count($values)) {
                continue 2;
            }
        }
        return [
            'template' => $state['template'],
            'params' => $params,
        ];
    }

    return null;
}

matchLaminasSegmentParts() advances literal parts only at the current URL offset, consumes each parameter only at its matcher-reported capture offset, and branches structurally for each optional part. That preserves nested optional groups and repeated values without putting raw request values into the cache key. The call site then uses the exact expanded template as the bounded shape key and normalizes with only the pre-default captured parameters:

$segmentMatch = self::inferLaminasSegmentMatch($leafRoute, $urlPath);
$cacheKey = $httpRoute . '#' . $segmentMatch['template'];

$normalizedRoute = RouteNormalizer::normalizeFromLaminas(
    $segmentMatch['template'],
    $segmentMatch['params'],
    null,
    null
);

}
$_braceTemp = preg_replace('/%([a-zA-Z_][a-zA-Z0-9_]*)%/', '{$1}', $httpRoute);
$_urlMatchedKeys = array_keys(
$urlMatchedFromRegex ?? \DDTrace\Util\RouteNormalizer::inferSymfonyRouteParams($_braceTemp, $urlPath)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do not use constraint-free URL inference as a fallback

As mentioned in other comments, RFC-1103 says: “Tracers must use the framework's matched-parameter map,” “must not infer presence from the URL alone,” and must “fall back to omitting the tag rather than emitting an inaccurate value.” inferSymfonyRouteParams() does the prohibited URL-only inference with generic (.+) captures, so it loses matcher constraints and cannot distinguish an absent capture from a route default.

rule:     /x/{name}.{ext?}; ext=pdf|json; default ext=txt
request:  /x/report.txt
expected: /x/{name} (or no tag)
actual:   /x/{name+ext}
rule:     Regex /normalized-regex-chain/%name%.%ext% + Literal /view; ext=pdf|json; default ext=txt
request:  /normalized-regex-chain/report.txt/view
expected: /normalized-regex-chain/{name}/view (or no tag)
actual:   /normalized-regex-chain/{name+ext}/view

In both cases the framework captures the entire report.txt value as name; ext does not participate and is added only from the default. Please support each specific pattern by replaying its actual matcher before defaults are merged, or omit _dd.appsec.normalized_route.

* in the match, so phantom segments are not emitted.
* @return string|null
*/
public static function normalizeFromWordPress(string $matchedRule, $urlPath = null)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use PCRE's match result instead of parsing the rewrite expression

The cache now distinguishes capture participation, but the route plan feeding it is still produced by a partial PCRE parser. That parser misclassifies valid syntax:

^normalized-quoted-literal/\Qfile.json\E$
expected: /normalized-quoted-literal/file.json
actual:   /normalized-quoted-literal/Qfile.jsonE

^normalized-quoted-captures/(?'first'[^/]+)-(?'second'[^/]+)$
expected: /normalized-quoted-captures/{first+second}
actual:   /normalized-quoted-captures/{param1}

PHP's match result already provides the authoritative numeric captures, named aliases, participation, and byte offsets. We can build the request-specific route from that result instead of extracting literals and capture names from the regex source. Before retaining concrete gaps as constants, use a conservative rejection filter: if the rule can consume variable text outside a capture (for example an uncaptured character class, repetition, or backreference, say ^foo/[a-z]+/bar), return null and omit the tag. Fixed literal alternatives and optional literals like red|blue remain bounded.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants