Skip to content

Implement normalised http routes - #4101

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

Implement normalised http routes#4101
estringana wants to merge 7 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

🚦 6 Pipeline jobs failed

DataDog/apm-reliability/dd-trace-php | test_extension_ci: [8.0]   View in Datadog   GitLab

DataDog/apm-reliability/dd-trace-php | test_extension_ci: [8.1]   View in Datadog   GitLab

DataDog/apm-reliability/dd-trace-php | test_extension_ci: [8.2]   View in Datadog   GitLab

View all 6 failed jobs.

❄️ 49 New flaky tests detected

testCakePHPCatchAll from unit.DDTrace\Tests\Unit\Util\Normalizer\RouteNormalizerTest   View in Datadog
DDTrace
Exception: add DDTrace to bridge/_files.php or bridge/dd_register_optional_deps_autoloader.php

tests/bootstrap_common.php:47
tests/Unit/Util/Normalizer/RouteNormalizerTest.php:199
phpvfscomposer://tests/vendor/phpunit/phpunit/phpunit:52

New test introduced in this PR is flaky.

testCakePHPMixedSegment from unit.DDTrace\Tests\Unit\Util\Normalizer\RouteNormalizerTest   View in Datadog
DDTrace
Exception: add DDTrace to bridge/_files.php or bridge/dd_register_optional_deps_autoloader.php

tests/bootstrap_common.php:47
tests/Unit/Util/Normalizer/RouteNormalizerTest.php:193
phpvfscomposer://tests/vendor/phpunit/phpunit/phpunit:52

New test introduced in this PR is flaky.

View in Flaky Test Management

ℹ️ Info

No other issues found (see more)

🧪 All tests passed

🎯 Code Coverage (details)
Patch Coverage: 100.00%
Overall Coverage: 59.61% (-1.02%)

Useful? React with 👍 / 👎

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 7b7f971 | Docs | Datadog PR Page | 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-08-14 14:11:05

Comparing candidate commit 7b7f971 in PR branch estringana/normalise-http-route with baseline commit ce98f3a in branch master.

Found 0 performance improvements and 4 performance regressions! Performance is the same for 190 metrics, 0 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:EmptyFileBench/benchEmptyFileOverhead

  • 🟥 execution_time [+76.999µs; +241.701µs] or [+2.125%; +6.669%]

scenario:MessagePackSerializationBench/benchMessagePackSerialization

  • 🟥 execution_time [+5.242µs; +8.298µs] or [+5.237%; +8.288%]

scenario:MessagePackSerializationBench/benchMessagePackSerialization-opcache

  • 🟥 execution_time [+7.142µs; +8.438µs] or [+6.687%; +7.901%]

scenario:SamplingRuleMatchingBench/benchRegexMatching1

  • 🟥 execution_time [+51.554ns; +131.046ns] or [+3.437%; +8.736%]

estringana and others added 7 commits August 14, 2026 14:52
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
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".

}

$raw = ltrim($route, '/');
$parts = explode('/', $raw);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Parse constrained placeholders before splitting path segments

When a brace-style constraint contains /, such as the common Slim pattern /files/{name:[^/]+}, splitting the raw template first breaks the placeholder into multiple segments. The normalizer consequently returns /files/%7Bname%3A%5E/%2B%7D instead of /files/{name}, so constrained routes receive a corrupt AppSec route tag.

Useful? React with 👍 / 👎.

$rootSpan->meta[Tag::HTTP_ROUTE] = $return->getPattern();
$pattern = $return->getPattern();
$rootSpan->meta[Tag::HTTP_ROUTE] = $pattern;
$normalizedRoute = \DDTrace\Util\RouteNormalizer::normalizeFromSlim($pattern);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Refine Slim 3 routes after arguments are prepared

For Slim 3 routes containing optional sections, this call always supplies an empty matched-parameter array, and only the Slim 4 controller path later refines the result. Thus a request matching /users/{id}[/{format}] with format present is still tagged as /users/{id} rather than /users/{id}/{format}.

Useful? React with 👍 / 👎.

$rootSpan->meta[Tag::HTTP_ROUTE] = $This->matched_rule;
$matchedRule = $This->matched_rule;
$rootSpan->meta[Tag::HTTP_ROUTE] = $matchedRule;
$normalizedRoute = \DDTrace\Util\RouteNormalizer::normalizeFromWordPress($matchedRule);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Omit absent optional WordPress captures

When a WordPress rule contains an optional path capture, only the regex template is passed to the normalizer, so it cannot tell whether that capture participated in the match. For example, the ordinary rule ([^/]+)(?:/([0-9]+))?/?$ tags a /simple request as /{param1}/{param2}, incorrectly inventing a second path segment and grouping requests with different actual route shapes.

Useful? React with 👍 / 👎.

Comment on lines +262 to +264
$normalizedRoute = \DDTrace\Util\RouteNormalizer::normalizeFromCodeIgniter($uri);
if ($normalizedRoute !== null) {
$rootSpan->meta[Tag::APPSEC_NORMALIZED_ROUTE] = $normalizedRoute;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid normalizing unmatched CodeIgniter request URIs

When no configured route matches, $uri is the concrete request path rather than a route template. Normalizing it as static text means arbitrary requests such as /users/12345 or 404 paths are emitted verbatim in _dd.appsec.normalized_route, retaining parameter values and creating attacker-controlled high-cardinality route tags; this fallback should derive a framework route shape or omit the normalized tag.

Useful? React with 👍 / 👎.

Comment on lines +162 to +165
if (preg_match('/^\([^)]+\)$/', $segment)) {
$normalizedSegments[] = '{param' . $paramIndex++ . '}';
} elseif (preg_match('/[()[\].*+?|^${}\\\\]/', $segment)) {
$normalizedSegments[] = '{param' . $paramIndex++ . '}';

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve every capture in WordPress regex segments

The WordPress normalizer assigns one placeholder per regex-containing URL segment rather than per capturing group. A valid rule such as ^post-([^/]+)-([0-9]+)/?$ therefore becomes /{param1} even though the segment contains two dynamic values and should be represented as /{param1+param2}, causing distinct route structures to collapse to the same normalized tag.

Useful? React with 👍 / 👎.

Comment on lines +287 to +288
if ($isOptional && !array_key_exists($name, $matchedParams)) {
return null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Retain required parameters beside absent optional parameters

When an absent optional placeholder shares a segment with required placeholders, returning null discards the entire segment. For example, Laravel normalization of /files/{name}.{ext?} with only name matched currently produces /files rather than /files/{name}, removing a required part of the matched route.

Useful? React with 👍 / 👎.

Comment on lines +365 to +369
$innerWithValue = preg_replace(
'/' . preg_quote($paramPrefix . $param, '/') . '/',
$value,
$inner
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Substitute all parameters before matching Laminas optionals

For a Laminas optional section containing multiple parameters, this loop substitutes only one parameter at a time before comparing the section with the URL. Consequently /archive[/:year/:month] with both values present cannot match /archive/2024/08; nested patterns such as /foo[/:bar[/:baz]] collapse into the same multi-parameter case and are normalized as /foo even when both optional segments were requested.

Useful? React with 👍 / 👎.


if ($path !== null) {
$rootSpan->meta[Tag::HTTP_ROUTE] = $path;
$normalizedRoute = \DDTrace\Util\RouteNormalizer::normalizeFromSymfony($path);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Resolve omitted Symfony parameters from the request

With DD_TRACE_SYMFONY_HTTP_ROUTE enabled, the normalizer receives only the catalog template and no request path or route-default information. Symfony generator templates retain trailing defaulted variables, so a route such as /blog/{page} requested as /blog is tagged /blog/{page} even though page was absent; the request must be used to remove optional variables before setting the normalized tag.

Useful? React with 👍 / 👎.

Comment on lines +316 to +318
if (empty($innerParams)) {
return $inner;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Resolve pure-static Slim optional sections from the request

Slim/FastRoute permits optional portions that contain no placeholder, such as /feed[.json], but this branch unconditionally includes such a portion. Because matchedParams cannot indicate whether a static optional was matched, both /feed and /feed.json are normalized as /feed.json; the actual request path is needed to decide whether to retain the section.

Useful? React with 👍 / 👎.

/**
* Normalize a Laminas route template.
*
* Laminas uses :param for dynamic parameters and [...] for optional sections.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

According to https://docs.laminas.dev/laminas-router/routing/ the :colon syntax is not the only one and they also have e.g. Laminas\Router\Http\Regex.

@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)

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.

2 participants