From 7d7609f222d878a7dba7746f269f1aaa3e7623be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20Gonz=C3=A1lez=20Garc=C3=ADa?= Date: Thu, 26 Nov 2026 14:39:14 +0100 Subject: [PATCH 1/9] Add Vert.x route parser for the AppSec normalized route --- .../api/appsec/route/VertxRouteParser.java | 244 ++++++++++++++++++ .../route/VertxRouteParserCacheTest.java | 123 +++++++++ .../route/VertxRouteParserRfcVectorsTest.java | 51 ++++ .../appsec/route/VertxRouteParserTest.java | 161 ++++++++++++ 4 files changed, 579 insertions(+) create mode 100644 internal-api/src/main/java/datadog/trace/api/appsec/route/VertxRouteParser.java create mode 100644 internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserCacheTest.java create mode 100644 internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserRfcVectorsTest.java create mode 100644 internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserTest.java diff --git a/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxRouteParser.java b/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxRouteParser.java new file mode 100644 index 00000000000..8c0f708588c --- /dev/null +++ b/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxRouteParser.java @@ -0,0 +1,244 @@ +package datadog.trace.api.appsec.route; + +import static datadog.trace.api.appsec.route.RoutePart.catchAll; +import static datadog.trace.api.appsec.route.RoutePart.literal; +import static datadog.trace.api.appsec.route.RoutePart.param; + +import datadog.trace.api.cache.DDCache; +import datadog.trace.api.cache.DDCaches; +import datadog.trace.api.internal.VisibleForTesting; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Turns a Vert.x web route path, exactly as declared by the app ({@code router.route("/a/:id")}), + * into a {@link RouteTemplate}. Vert.x syntax: + * + * + * + * A path with a {@code :} is compiled by Vert.x into a regex that only escapes {@code ( ) $ + .}: + * there, any of {@code ? [ ] { } | ^ \} or a non-trailing {@code *} gives {@link + * RouteTemplate#NOT_EXPRESSIBLE}. Without {@code :}, every char but the trailing {@code *} is + * static. Empty segments are ignored; a trailing {@code /} is kept. + */ +public final class VertxRouteParser { + + private static final Logger log = LoggerFactory.getLogger(VertxRouteParser.class); + + /** Route paths are declared in code, so their cardinality is low; 256 bounds odd apps. */ + private static final int CACHE_CAPACITY = 256; + + /** + * Parameter name grammar of the Vert.x version. Vert.x escapes {@code $} before it looks for + * names, so {@code $} never ends up in a name, even in {@link #EXTENDED}. + */ + public enum Grammar { + /** Vert.x 3.x to 4.0.2: {@code [A-Za-z][A-Za-z0-9_]*}. */ + LEGACY, + /** Vert.x 4.0.3+ and 5.x: {@code [A-Za-z0-9_]+}. */ + DEFAULT, + /** + * Vert.x 4.0.3+ with {@code -Dio.vertx.web.route.param.extended-pattern=true}: {@code + * [A-Za-z_$][A-Za-z0-9_$-]*}. + */ + EXTENDED; + + private final DDCache cache = DDCaches.newFixedSizeCache(CACHE_CAPACITY); + + private final Function safeParse = + safely(path -> VertxRouteParser.parse(path, this)); + + boolean isNameStart(char c) { + if (isAsciiLetter(c)) { + return true; + } + switch (this) { + case DEFAULT: + return isDigit(c) || c == '_'; + case EXTENDED: + return c == '_'; + default: + return false; + } + } + + boolean isNamePart(char c) { + return isAsciiLetter(c) || isDigit(c) || c == '_' || (this == EXTENDED && c == '-'); + } + + private static boolean isAsciiLetter(char c) { + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); + } + + private static boolean isDigit(char c) { + return c >= '0' && c <= '9'; + } + } + + private VertxRouteParser() {} + + /** + * Same as {@link #parse(String, Grammar)} but backed by a bounded cache per grammar, for the + * request hot path. Never returns null or throws. + */ + public static RouteTemplate cached(String declaredPath, Grammar grammar) { + if (grammar == null) { + return RouteTemplate.NOT_EXPRESSIBLE; + } + return cached(grammar.cache, declaredPath, grammar.safeParse); + } + + @VisibleForTesting + static RouteTemplate cached( + DDCache cache, String declaredPath, Grammar grammar) { + return cached(cache, declaredPath, grammar.safeParse); + } + + @VisibleForTesting + static RouteTemplate cached( + DDCache cache, + String declaredPath, + Function producer) { + // null cannot be a cache key, and empty is not worth an entry + if (declaredPath == null || declaredPath.isEmpty()) { + return RouteTemplate.NOT_EXPRESSIBLE; + } + try { + return cache.computeIfAbsent(declaredPath, producer); + } catch (Throwable t) { + // an Error may be transient (e.g. OutOfMemoryError): the cache stores nothing when the + // producer throws, so the next request retries + log.debug("Failed to parse Vert.x route path {}", declaredPath, t); + return RouteTemplate.NOT_EXPRESSIBLE; + } + } + + /** + * Wraps {@code parser} so that a {@link RuntimeException} becomes a cached {@link + * RouteTemplate#NOT_EXPRESSIBLE}: parsing is deterministic, so it would fail again for the same + * path. Errors propagate so that {@link #cached} does not cache them. + */ + @VisibleForTesting + static Function safely(final Function parser) { + return path -> { + try { + return parser.apply(path); + } catch (RuntimeException e) { + log.debug("Failed to parse Vert.x route path {}", path, e); + return RouteTemplate.NOT_EXPRESSIBLE; + } + }; + } + + /** + * Parses a declared Vert.x route path in a single pass. Malformed input is not an error: it gives + * {@link RouteTemplate#NOT_EXPRESSIBLE}. + * + * @return the template, or {@link RouteTemplate#NOT_EXPRESSIBLE} for null, empty, relative or + * regex-like paths + */ + public static RouteTemplate parse(String declaredPath, Grammar grammar) { + if (declaredPath == null + || declaredPath.isEmpty() + || declaredPath.charAt(0) != '/' + || grammar == null) { + return RouteTemplate.NOT_EXPRESSIBLE; + } + int len = declaredPath.length(); + boolean trailingStar = declaredPath.charAt(len - 1) == '*'; + int end = trailingStar ? len - 1 : len; + // Vert.x compiles the path to a regex as soon as it holds a ':', valid name or not + boolean regex = declaredPath.indexOf(':') >= 0; + RouteTemplate.Builder builder = RouteTemplate.builder(); + List parts = new ArrayList<>(); + List names = null; + int literalStart = -1; + int i = 0; + while (i < end) { + char c = declaredPath.charAt(i); + if (c == '/') { + literalStart = flushLiteral(declaredPath, literalStart, i, parts); + endSegment(builder, parts); + i++; + } else if (regex && isRegexOperator(c)) { + return RouteTemplate.NOT_EXPRESSIBLE; + } else if (c == ':' && i + 1 < end && grammar.isNameStart(declaredPath.charAt(i + 1))) { + literalStart = flushLiteral(declaredPath, literalStart, i, parts); + int nameEnd = i + 2; + while (nameEnd < end && grammar.isNamePart(declaredPath.charAt(nameEnd))) { + nameEnd++; + } + String name = declaredPath.substring(i + 1, nameEnd); + if (names == null) { + names = new ArrayList<>(); + } else if (names.contains(name)) { + // Vert.x rejects a name used twice + return RouteTemplate.NOT_EXPRESSIBLE; + } + names.add(name); + parts.add(param(name)); + i = nameEnd; + } else { + if (literalStart < 0) { + literalStart = i; + } + i++; + } + } + flushLiteral(declaredPath, literalStart, end, parts); + if (trailingStar && declaredPath.charAt(end - 1) == '/') { + // "/a/*": the '/' before it already closed the previous segment + builder.segment(catchAll(null)); + } else { + if (trailingStar) { + parts.add(catchAll(null)); + } + endSegment(builder, parts); + } + return builder + .trailingSlash(!trailingStar && len > 1 && declaredPath.charAt(len - 1) == '/') + .build(); + } + + /** Regex syntax that Vert.x does not escape in a parameter path (besides a non-trailing '*'). */ + private static boolean isRegexOperator(char c) { + switch (c) { + case '?': + case '[': + case ']': + case '{': + case '}': + case '|': + case '^': + case '\\': + case '*': + return true; + default: + return false; + } + } + + private static int flushLiteral(String path, int start, int end, List parts) { + if (start >= 0 && end > start) { + parts.add(literal(RouteEncoding.decodePath(path.substring(start, end)))); + } + return -1; + } + + private static void endSegment(RouteTemplate.Builder builder, List parts) { + if (!parts.isEmpty()) { + builder.segment(parts.toArray(new RoutePart[0])); + parts.clear(); + } + } +} diff --git a/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserCacheTest.java b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserCacheTest.java new file mode 100644 index 00000000000..a2e7b54912a --- /dev/null +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserCacheTest.java @@ -0,0 +1,123 @@ +package datadog.trace.api.appsec.route; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import datadog.trace.api.appsec.route.VertxRouteParser.Grammar; +import datadog.trace.api.cache.DDCache; +import datadog.trace.api.cache.DDCaches; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import org.junit.jupiter.api.Test; + +class VertxRouteParserCacheTest { + + @Test + void samePathReturnsCachedInstance() { + RouteTemplate first = VertxRouteParser.cached("/users/:id", Grammar.DEFAULT); + assertSame(first, VertxRouteParser.cached(new String("/users/:id"), Grammar.DEFAULT)); + assertEquals("/users/{id}", first.staticRoute()); + } + + @Test + void differentPathsGiveDifferentTemplates() { + RouteTemplate users = VertxRouteParser.cached("/users/:id", Grammar.DEFAULT); + RouteTemplate orders = VertxRouteParser.cached("/orders/:id", Grammar.DEFAULT); + assertNotSame(users, orders); + assertEquals("/orders/{id}", orders.staticRoute()); + } + + @Test + void grammarsUseSeparateCaches() { + RouteTemplate legacy = VertxRouteParser.cached("/t/:1abc", Grammar.LEGACY); + RouteTemplate current = VertxRouteParser.cached("/t/:1abc", Grammar.DEFAULT); + RouteTemplate extended = VertxRouteParser.cached("/t/:1abc", Grammar.EXTENDED); + assertEquals("/t/%3A1abc", legacy.staticRoute()); + assertEquals("/t/{1abc}", current.staticRoute()); + assertEquals("/t/%3A1abc", extended.staticRoute()); + assertNotSame(legacy, extended); + assertSame(legacy, VertxRouteParser.cached("/t/:1abc", Grammar.LEGACY)); + assertSame(current, VertxRouteParser.cached("/t/:1abc", Grammar.DEFAULT)); + } + + @Test + void nullOrEmptyIsNotExpressible() { + for (Grammar grammar : Grammar.values()) { + assertSame(RouteTemplate.NOT_EXPRESSIBLE, VertxRouteParser.cached(null, grammar)); + assertSame(RouteTemplate.NOT_EXPRESSIBLE, VertxRouteParser.cached("", grammar)); + } + } + + @Test + void nullOrEmptyNeverReachesTheCache() { + DDCache cache = DDCaches.newFixedSizeCache(4); + VertxRouteParser.cached(cache, null, Grammar.DEFAULT); + VertxRouteParser.cached(cache, "", Grammar.DEFAULT); + assertEquals(0, size(cache)); + } + + @Test + void unparseablePathIsCachedAsNotExpressible() { + DDCache cache = DDCaches.newFixedSizeCache(4); + assertSame( + RouteTemplate.NOT_EXPRESSIBLE, VertxRouteParser.cached(cache, "/x/:id?", Grammar.DEFAULT)); + assertEquals(1, size(cache)); + assertSame( + RouteTemplate.NOT_EXPRESSIBLE, VertxRouteParser.cached(cache, "/x/:id?", Grammar.DEFAULT)); + assertEquals(1, size(cache)); + } + + @Test + void parserRuntimeExceptionIsCachedAsNotExpressible() { + DDCache cache = DDCaches.newFixedSizeCache(4); + AtomicInteger calls = new AtomicInteger(); + Function producer = + VertxRouteParser.safely(path -> { + calls.incrementAndGet(); + throw new IllegalStateException("parser bug"); + }); + + assertSame(RouteTemplate.NOT_EXPRESSIBLE, VertxRouteParser.cached(cache, "/a", producer)); + assertSame(RouteTemplate.NOT_EXPRESSIBLE, VertxRouteParser.cached(cache, "/a", producer)); + assertEquals(1, calls.get()); + assertEquals(1, size(cache)); + } + + @Test + void parserErrorIsNotCached() { + DDCache cache = DDCaches.newFixedSizeCache(4); + Function failing = + VertxRouteParser.safely(path -> { + throw new StackOverflowError("transient"); + }); + + assertSame(RouteTemplate.NOT_EXPRESSIBLE, VertxRouteParser.cached(cache, "/a/:id", failing)); + assertEquals(0, size(cache)); + + RouteTemplate retried = VertxRouteParser.cached(cache, "/a/:id", Grammar.DEFAULT); + assertEquals("/a/{id}", retried.staticRoute()); + assertEquals(1, size(cache)); + } + + @Test + void cacheStaysBounded() { + int capacity = 8; + DDCache cache = DDCaches.newFixedSizeCache(capacity); + for (int i = 0; i < 1000; i++) { + String path = "/p" + i + "/:id"; + RouteTemplate template = VertxRouteParser.cached(cache, path, Grammar.DEFAULT); + assertEquals("/p" + i + "/{id}", template.staticRoute()); + assertTrue(size(cache) <= capacity); + } + RouteTemplate last = VertxRouteParser.cached(cache, "/p999/:id", Grammar.DEFAULT); + assertSame(last, VertxRouteParser.cached(cache, "/p999/:id", Grammar.DEFAULT)); + } + + private static int size(DDCache cache) { + AtomicInteger count = new AtomicInteger(); + cache.visit((k, v) -> count.incrementAndGet()); + return count.get(); + } +} diff --git a/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserRfcVectorsTest.java b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserRfcVectorsTest.java new file mode 100644 index 00000000000..fc63a7151f8 --- /dev/null +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserRfcVectorsTest.java @@ -0,0 +1,51 @@ +package datadog.trace.api.appsec.route; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import datadog.trace.api.appsec.route.VertxRouteParser.Grammar; +import java.util.Set; +import org.tabletest.junit.TableTest; + +/** + * The RFC-1125 "Test cases" rows (see {@link NormalizedRouteRfcVectorsTest}) that Vert.x syntax can + * express, translated to {@code :name} paths and run through {@link VertxRouteParser}. Vert.x has + * no optional params or groups (rows 15-29, 39-45 as written), no regex constraints, no named + * catch-all (35), no {@code .} or non-ASCII names (31, 34) and no static {@code :} next to a name + * char (10). Catch-all rows use the unnamed trailing {@code *} instead (36, 37, 39, 49). + */ +class VertxRouteParserRfcVectorsTest { + + @TableTest({ + "Scenario | Grammar | Route | Hit URL | Present | Tag ", + "#1 Basics | DEFAULT | '/users' | '/users' | {} | '/users' ", + "#2 Basics | DEFAULT | '/' | '/' | {} | '/' ", + "#3 Basics | DEFAULT | '/users/:id' | '/users/42' | {} | '/users/{id}' ", + "#3 Basics | LEGACY | '/users/:id' | '/users/42' | {} | '/users/{id}' ", + "#4 Basics | DEFAULT | '/users/:id/posts/:post_id' | '/users/1/posts/5' | {} | '/users/{id}/posts/{post_id}'", + "#5 Basics | DEFAULT | '/users/:id/' | '/users/1/' | {} | '/users/{id}/' ", + "#6 Static text in a segment | DEFAULT | '/users/user-:id' | '/users/user-42' | {} | '/users/user-{id}' ", + "#7 Static text in a segment | DEFAULT | '/v:version/items' | '/v2/items' | {} | '/v{version}/items' ", + "#8 Static text in a segment | DEFAULT | '/files/:name.json' | '/files/report.json' | {} | '/files/{name}.json' ", + "#9 Static text in a segment | DEFAULT | '/caf%C3%A9' | '/caf%C3%A9' | {} | '/caf%C3%A9' ", + "#9 Static text in a segment (raw) | LEGACY | '/café' | '/caf%C3%A9' | {} | '/caf%C3%A9' ", + "#11 Static text in a segment | DEFAULT | '/a+b/:id' | '/a+b/1' | {} | '/a%2Bb/{id}' ", + "#12 Several parameters in one segment | DEFAULT | '/photos/:id.:format' | '/photos/1.jpg' | {} | '/photos/{id}.{format}' ", + "#13 Several parameters in one segment | DEFAULT | '/d/:a-:b-:c' | '/d/1-2-3' | {} | '/d/{a}-{b}-{c}' ", + "#13 Several parameters in one segment | LEGACY | '/d/:a-:b-:c' | '/d/1-2-3' | {} | '/d/{a}-{b}-{c}' ", + "#14 Several parameters in one segment | DEFAULT | '/v/:major:minor' | '/v/12' | {} | '/v/{major}{minor}' ", + "#30 Parameter names | EXTENDED | '/users/:user-id' | '/users/1' | {} | '/users/{user_id}' ", + "#32 Parameter names, collision | EXTENDED | '/a/:user-id/:user_id' | '/a/1/2' | {} | '/a/{user_id_2}/{user_id}' ", + "#33 Parameter names, collision (suffix _2 already used) | EXTENDED | '/a/:x-y/:x_y/:x_y_2' | '/a/1/2/3' | {} | '/a/{x_y_3}/{x_y}/{x_y_2}' ", + "#36 Catch-all, unnamed | DEFAULT | '/static/*' | '/static/css/app.css' | {anon} | '/static/{param1}' ", + "#37 Catch-all, unnamed, name already used | DEFAULT | '/w/:param1/*' | '/w/x/a/b' | {anon} | '/w/{param1}/{param2}' ", + "#39 Catch-all, absent (unnamed) | DEFAULT | '/files/*' | '/files' | {} | '/files' ", + "#49 Catch-all, empty value (unnamed) | DEFAULT | '/files/*' | '/files/' | {'anon=/'} | '/files/' " + }) + void rendersRfcRows( + Grammar grammar, String route, String hitUrl, Set present, String tag) { + assertEquals( + tag, + VertxRouteParser.parse(route, grammar).render(null, RfcRouteNotation.presence(present)), + hitUrl); + } +} diff --git a/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserTest.java b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserTest.java new file mode 100644 index 00000000000..33ccf7ed98e --- /dev/null +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserTest.java @@ -0,0 +1,161 @@ +package datadog.trace.api.appsec.route; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import datadog.trace.api.appsec.route.VertxRouteParser.Grammar; +import java.util.Set; +import org.junit.jupiter.api.Test; +import org.tabletest.junit.TableTest; + +class VertxRouteParserTest { + + @TableTest({ + "Scenario | Path | Expected ", + "two params with dot | '/a/:id.:format' | '/a/{id}.{format}' ", + "three params with dashes | '/three/:a-:b-:c' | '/three/{a}-{b}-{c}' ", + "static prefix in segment | '/u/user-:id' | '/u/user-{id}' ", + "param inside first segment | '/v:version/items' | '/v{version}/items' ", + "static suffix after dot | '/files/:name.json' | '/files/{name}.json' ", + "suffix param | '/search.:format' | '/search.{format}' ", + "adjacent params | '/v/:major:minor' | '/v/{major}{minor}' ", + "root | '/' | '/' ", + "trailing slash | '/x/' | '/x/' ", + "param and trailing slash | '/x/:id/' | '/x/{id}/' ", + "empty segments ignored | '//a//:id' | '/a/{id}' ", + "encoded literal | '/caf%C3%A9' | '/caf%C3%A9' ", + "raw non-ASCII literal | '/café' | '/caf%C3%A9' ", + "encoded spaces | '/encoded%20path%20query' | '/encoded%20path%20query'", + "encoded literal next to param | '/caf%C3%A9/:id' | '/caf%C3%A9/{id}' ", + "escaped regex chars are literals | '/a+b/(x)/:id$' | '/a%2Bb/%28x%29/{id}%24' ", + "colon alone | '/a/:' | '/a/%3A' ", + "colon at end of segment | '/a:/b' | '/a%3A/b' ", + "plain path, mid star literal | '/a/*/b' | '/a/%2A/b' ", + "plain path, question mark literal | '/a/b?' | '/a/b%3F' ", + "plain path, braces literal | '/a/{b}' | '/a/%7Bb%7D' ", + "plain path, double star unknown | '/a/**' | '/a/%2A' " + }) + void parsesDefaultGrammarPaths(String path, String expected) { + assertEquals( + expected, + VertxRouteParser.parse(path, Grammar.DEFAULT).render(null, PresenceResolver.UNKNOWN)); + } + + @TableTest({ + "Scenario | Path | Present | Expected ", + "whole-segment catch-all present | '/a/*' | {anon} | '/a/{param1}' ", + "whole-segment catch-all absent | '/a/*' | {} | '/a' ", + "whole-segment catch-all unknown | '/a/*' | | '/a' ", + "whole-segment catch-all slash | '/a/*' | {'anon=/'} | '/a/' ", + "in-segment catch-all present | '/img*' | {anon} | '/img{param1}' ", + "in-segment catch-all absent | '/img*' | {} | '/img' ", + "in-segment catch-all slash | '/img*' | {'anon=/'} | '/img' ", + "root catch-all present | '/*' | {anon} | '/{param1}' ", + "root catch-all absent | '/*' | {} | '/' ", + "root catch-all slash | '/*' | {'anon=/'} | '/' ", + "catch-all after param | '/users/:id/*' | {anon} | '/users/{id}/{param1}'", + "catch-all after param absent | '/users/:id/*' | {} | '/users/{id}' ", + "catch-all after param1 name | '/w/:param1/*' | {anon} | '/w/{param1}/{param2}'", + "catch-all after in-segment param | '/f/:id*' | {anon} | '/f/{id}{param1}' ", + "plain double star, present | '/a/**' | {anon} | '/a/%2A{param1}' " + }) + void parsesTrailingCatchAll(String path, Set present, String expected) { + assertEquals( + expected, + VertxRouteParser.parse(path, Grammar.DEFAULT) + .render(null, RfcRouteNotation.presence(present))); + } + + @TableTest({ + "Scenario | Grammar | Path | Expected ", + "digit-first name, legacy | LEGACY | '/t/:1abc' | '/t/%3A1abc'", + "digit-first name, default | DEFAULT | '/t/:1abc' | '/t/{1abc}' ", + "digit-first name, extended | EXTENDED | '/t/:1abc' | '/t/%3A1abc'", + "letter name, legacy | LEGACY | '/t/:id' | '/t/{id}' ", + "underscore-first name, legacy | LEGACY | '/t/:_id' | '/t/%3A_id' ", + "underscore-first name, default | DEFAULT | '/t/:_id' | '/t/{_id}' ", + "underscore-first name, extended | EXTENDED | '/t/:_id' | '/t/{_id}' ", + "dash ends name, legacy | LEGACY | '/t/:id-x' | '/t/{id}-x' ", + "dash ends name, default | DEFAULT | '/t/:id-x' | '/t/{id}-x' ", + "dash in name, extended | EXTENDED | '/t/:id-x' | '/t/{id_x}' ", + "dollar never starts a name | EXTENDED | '/t/:$a' | '/t/%3A%24a'", + "dollar never starts a name | DEFAULT | '/t/:$a' | '/t/%3A%24a'", + "dollar ends a name, extended | EXTENDED | '/t/:a$b' | '/t/{a}%24b'", + "colon with dash, extended | EXTENDED | '/t/:a-:b' | '/t/{a_}{b}'" + }) + void nameGrammarDependsOnTheVersion(Grammar grammar, String path, String expected) { + assertEquals( + expected, VertxRouteParser.parse(path, grammar).render(null, PresenceResolver.UNKNOWN)); + } + + @Test + void extendedNameKeepsItsFrameworkName() { + RouteTemplate template = VertxRouteParser.parse("/t/:a-:b", Grammar.EXTENDED); + assertEquals("a-", template.params().get(0).frameworkName()); + assertEquals("a_", template.params().get(0).name()); + assertEquals("b", template.params().get(1).frameworkName()); + } + + @TableTest({ + "Scenario | Path ", + "null | ", + "empty | '' ", + "relative | 'abc' ", + "relative param | 'a/:id' ", + "optional param | '/x/:id?' ", + "character class | '/x/:id[0-9]' ", + "alternation | '/x/:id|y' ", + "mid star in param path | '/a/*/:id' ", + "star in param segment | '/a/:id*x' ", + "double trailing star | '/a/:id/**' ", + "quantifier | '/x/:id{2}' ", + "backslash escape | '/x/:id\\d' ", + "anchor | '/x/^:id' ", + "regex char with invalid name | '/x/:1?' ", + "duplicate name | '/x/:id/y/:id'" + }) + void rejectsPathsThatCannotBeExpressed(String path) { + for (Grammar grammar : Grammar.values()) { + assertSame( + RouteTemplate.NOT_EXPRESSIBLE, VertxRouteParser.parse(path, grammar), grammar.name()); + } + } + + @Test + void nullGrammarIsNotExpressible() { + assertSame(RouteTemplate.NOT_EXPRESSIBLE, VertxRouteParser.parse("/a", null)); + assertSame(RouteTemplate.NOT_EXPRESSIBLE, VertxRouteParser.cached("/a", null)); + } + + @Test + void encodedSlashInLiteralStaysInItsSegment() { + assertEquals( + "/a%2Fb/{id}", VertxRouteParser.parse("/a%2Fb/:id", Grammar.DEFAULT).render(null, null)); + } + + @Test + void routesWithoutCatchAllArePreRendered() { + assertEquals( + "/a/{id}.{format}", + VertxRouteParser.parse("/a/:id.:format", Grammar.DEFAULT).staticRoute()); + assertNull(VertxRouteParser.parse("/a/*", Grammar.DEFAULT).staticRoute()); + } + + @Test + void trailingWholeSegmentCatchAllNeedsTheRemainder() { + assertTrue(VertxRouteParser.parse("/a/*", Grammar.DEFAULT).needsUnnamedCatchAllRemainder()); + assertTrue( + VertxRouteParser.parse("/users/:id/*", Grammar.DEFAULT).needsUnnamedCatchAllRemainder()); + assertFalse(VertxRouteParser.parse("/img*", Grammar.DEFAULT).needsUnnamedCatchAllRemainder()); + } + + @Test + void rendersWithMountPrefix() { + assertEquals( + "/sub/users/{id}", + VertxRouteParser.parse("/users/:id", Grammar.DEFAULT).render("/sub/", null)); + } +} From 3aabe1473095695f436f6a54213d3eaff1e5b457 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20Gonz=C3=A1lez=20Garc=C3=ADa?= Date: Thu, 26 Nov 2026 14:54:14 +0100 Subject: [PATCH 2/9] Add Vert.x normalized route entry point for AppSec --- .../appsec/route/VertxNormalizedRoute.java | 309 ++++++++++++++++++ .../api/appsec/route/VertxRouteParser.java | 33 ++ .../route/VertxNormalizedRouteForkedTest.java | 99 ++++++ .../route/VertxNormalizedRouteTest.java | 126 +++++++ .../appsec/route/VertxRouteParserTest.java | 31 ++ 5 files changed, 598 insertions(+) create mode 100644 internal-api/src/main/java/datadog/trace/api/appsec/route/VertxNormalizedRoute.java create mode 100644 internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteForkedTest.java create mode 100644 internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteTest.java diff --git a/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxNormalizedRoute.java b/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxNormalizedRoute.java new file mode 100644 index 00000000000..1b665086b9f --- /dev/null +++ b/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxNormalizedRoute.java @@ -0,0 +1,309 @@ +package datadog.trace.api.appsec.route; + +import datadog.trace.api.appsec.route.VertxRouteParser.Grammar; +import datadog.trace.api.internal.VisibleForTesting; +import datadog.trace.bootstrap.instrumentation.api.AgentSpan; +import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Entry point of the Vert.x web integrations for {@code _dd.appsec.normalized_route}: they collect + * plain values from the {@code RoutingContext} and this class builds the template, the mount prefix + * and the catch-all presence. The catch-all remainder follows Vert.x' own matching: {@code + * startsWith} for routes without parameters, the {@code [^/]+} segments of the compiled regex + * otherwise, with the mount joined as {@code RouteState.pathMatches} does. + */ +public final class VertxNormalizedRoute { + + private static final Logger log = LoggerFactory.getLogger(VertxNormalizedRoute.class); + + /** System property that selects the {@link Grammar#EXTENDED} name grammar on Vert.x 4.0.3+. */ + static final String EXTENDED_PATTERN_PROPERTY = "io.vertx.web.route.param.extended-pattern"; + + /** Path param Vert.x binds to the catch-all match; never used for presence. */ + private static final String REST_PARAM = "*"; + + /** Catch-all resolvers by {@link RoutePresence#ordinal()}, so rendering allocates none. */ + private static final PresenceResolver[] CATCH_ALL_RESOLVERS; + + static { + RoutePresence[] values = RoutePresence.values(); + CATCH_ALL_RESOLVERS = new PresenceResolver[values.length]; + for (RoutePresence presence : values) { + CATCH_ALL_RESOLVERS[presence.ordinal()] = new CatchAllResolver(presence); + } + } + + private VertxNormalizedRoute() {} + + /** + * Replaces the normalized route tag of {@code span}: any previous value is removed first, then + * the route is tagged when it can be expressed. Call it after {@code http.route} is set and only + * when {@link NormalizedRouteHelper#isEnabled()}. Never throws. + * + * @param declaredPath route path exactly as declared by the app (with its trailing {@code *}), or + * null when unknown (regex route, no path) + * @param grammar parameter name grammar: {@link Grammar#LEGACY} on 3.x, {@link #vertx4Grammar()} + * on 4.x and 5.x + * @param mountPoint {@code RoutingContext.mountPoint()}, null at the top level + * @param normalizedPath {@code RoutingContext.normalisedPath()} (3.x) or {@code normalizedPath()} + * (4.x, 5.x): the full request path, mount included + * @param pathParams {@code RoutingContext.pathParams()} + */ + public static void tag( + AgentSpan span, + String declaredPath, + Grammar grammar, + String mountPoint, + String normalizedPath, + Map pathParams) { + if (span == null) { + return; + } + try { + // a later route that cannot be expressed must not keep the tag of an earlier one + span.setTag(NormalizedRouteHelper.NORMALIZED_ROUTE_TAG, (String) null); + RouteTemplate template = template(declaredPath, grammar, mountPoint, pathParams); + if (template != null) { + NormalizedRouteHelper.tag( + span, + template, + NormalizedRouteHelper.decodePath(mountPoint), + resolver(template, declaredPath, grammar, mountPoint, normalizedPath)); + } + } catch (Throwable t) { + log.debug("Failed to set the Vert.x normalized route tag", t); + } + } + + /** Same computation as {@link #tag}; returns the rendered route, or null when there is no tag. */ + @VisibleForTesting + static String render( + String declaredPath, + Grammar grammar, + String mountPoint, + String normalizedPath, + Map pathParams) { + RouteTemplate template = template(declaredPath, grammar, mountPoint, pathParams); + if (template == null) { + return null; + } + return template.render( + NormalizedRouteHelper.decodePath(mountPoint), + resolver(template, declaredPath, grammar, mountPoint, normalizedPath)); + } + + /** + * Name grammar of the running Vert.x 4.x or 5.x: {@link Grammar#EXTENDED} when {@code + * -Dio.vertx.web.route.param.extended-pattern=true}, else {@link Grammar#DEFAULT}. The property + * is read once, as Vert.x does. + */ + public static Grammar vertx4Grammar() { + return Vertx4GrammarHolder.GRAMMAR; + } + + @VisibleForTesting + static Grammar vertx4Grammar(boolean extendedPattern) { + return extendedPattern ? Grammar.EXTENDED : Grammar.DEFAULT; + } + + /** + * Template to render, or null when there is no tag: the route cannot be expressed, or the mount + * point holds request values. A mount with parameters returns the concrete matched prefix and + * shares its {@code pathParams()} with the sub-router, so a bound parameter that the route does + * not declare means a parameter mount (conservative: a middleware route may also have left it). + */ + private static RouteTemplate template( + String declaredPath, Grammar grammar, String mountPoint, Map pathParams) { + RouteTemplate template = VertxRouteParser.cached(declaredPath, grammar); + if (!template.isExpressible()) { + return null; + } + if (mountPoint != null && !mountPoint.isEmpty() && pathParams != null) { + for (String name : pathParams.keySet()) { + if (!REST_PARAM.equals(name) + && !VertxRouteParser.declaresParam(declaredPath, name, grammar)) { + return null; + } + } + } + return template; + } + + /** + * Presence of the trailing catch-all, or null for templates that do not depend on the request. + */ + private static PresenceResolver resolver( + RouteTemplate template, + String declaredPath, + Grammar grammar, + String mountPoint, + String normalizedPath) { + // the trailing '*' is the only optional part of a Vert.x template + if (template.staticRoute() != null) { + return null; + } + int start = remainderStart(declaredPath, grammar, mountPoint, normalizedPath); + RoutePresence presence = + start < 0 + ? RoutePresence.UNKNOWN + : RoutePresence.ofCatchAllValue(normalizedPath.substring(start)); + return catchAllResolver(presence); + } + + /** Shared resolver that answers {@code presence} for the unnamed catch-all. */ + @VisibleForTesting + static PresenceResolver catchAllResolver(RoutePresence presence) { + return CATCH_ALL_RESOLVERS[presence.ordinal()]; + } + + /** + * Index of {@code normalizedPath} where the trailing {@code *} match starts, or -1 when unknown. + * The static base is the declared path without the {@code *} and the {@code /} right before it; + * the full base is the mount (without its trailing {@code /}) followed by the base, which is + * Vert.x' join: {@code mount + path.substring(1)} for a mount ending with {@code /}, the mount + * alone for the route path {@code /}, else {@code mount + path}. + */ + private static int remainderStart( + String declaredPath, Grammar grammar, String mountPoint, String normalizedPath) { + if (normalizedPath == null) { + return -1; + } + int baseEnd = declaredPath.length() - 1; + boolean wholeSegment = baseEnd > 0 && declaredPath.charAt(baseEnd - 1) == '/'; + if (wholeSegment) { + baseEnd--; + } + int mountLength = mountPoint == null ? 0 : mountPoint.length(); + if (mountLength > 0 && mountPoint.charAt(mountLength - 1) == '/') { + mountLength--; + } + if (mountLength > 0 && !normalizedPath.regionMatches(0, mountPoint, 0, mountLength)) { + return -1; + } + int start; + if (declaredPath.indexOf(':') < 0) { + // no parameter: Vert.x matches the joined path with startsWith + if (!normalizedPath.regionMatches(mountLength, declaredPath, 0, baseEnd)) { + return -1; + } + start = mountLength + baseEnd; + } else { + start = + skipSegments(declaredPath, baseEnd, wholeSegment, grammar, normalizedPath, mountLength); + if (start < 0) { + return -1; + } + } + if (wholeSegment && start < normalizedPath.length() && normalizedPath.charAt(start) != '/') { + // "/a/*" never matches "/ab" + return -1; + } + return start; + } + + /** + * Mirrors the regex Vert.x compiles for a parameter path: each declared segment of the base is a + * single request segment (parameters match {@code [^/]+}, literals hold no {@code /}). For an + * in-segment {@code *} ({@code /u/:id*}), the last segment is matched as the greedy regex does. + * Returns the index after the base, or -1 when the path does not match it. + */ + private static int skipSegments( + String declaredPath, + int baseEnd, + boolean wholeSegment, + Grammar grammar, + String path, + int position) { + int pathLength = path.length(); + int segmentStart = 0; + while (segmentStart < baseEnd) { + // declaredPath.charAt(segmentStart) == '/': the parser only accepts absolute paths + if (position >= pathLength || path.charAt(position) != '/') { + return -1; + } + int segmentEnd = declaredPath.indexOf('/', segmentStart + 1); + if (segmentEnd < 0 || segmentEnd > baseEnd) { + segmentEnd = baseEnd; + } + int pathSegmentEnd = path.indexOf('/', position + 1); + if (pathSegmentEnd < 0) { + pathSegmentEnd = pathLength; + } + if (segmentEnd == baseEnd && !wholeSegment) { + return partialSegmentEnd( + declaredPath, segmentStart + 1, baseEnd, grammar, path, position + 1, pathSegmentEnd); + } + position = pathSegmentEnd; + segmentStart = segmentEnd; + } + return position; + } + + /** + * Where {@code .*} starts after the last declared segment {@code [from, to)} of an in-segment + * {@code *}, matched against the request segment {@code [pathFrom, pathTo)}. Greedy {@code [^/]+} + * parameters take as much of the segment as they can: after a final parameter the match starts at + * the end of the segment, after a final literal at its last occurrence. A segment without + * parameter must start with its literal. + */ + private static int partialSegmentEnd( + String declaredPath, + int from, + int to, + Grammar grammar, + String path, + int pathFrom, + int pathTo) { + int lastParamEnd = -1; + for (int i = declaredPath.indexOf(':', from); + i >= 0 && i < to; + i = declaredPath.indexOf(':', i + 1)) { + int nameEnd = VertxRouteParser.nameEnd(declaredPath, i, to, grammar); + if (nameEnd >= 0) { + lastParamEnd = nameEnd; + } + } + if (lastParamEnd < 0) { + // a literal holds no '/', so it can only match inside the segment + int length = to - from; + return path.regionMatches(pathFrom, declaredPath, from, length) ? pathFrom + length : -1; + } + if (lastParamEnd == to) { + return pathTo; + } + int literalLength = to - lastParamEnd; + // the parameters before the literal match at least one char + for (int i = pathTo - literalLength; i > pathFrom; i--) { + if (path.regionMatches(i, declaredPath, lastParamEnd, literalLength)) { + return i + literalLength; + } + } + return -1; + } + + /** Presence of the unnamed catch-all; every other optional part is unknown. */ + private static final class CatchAllResolver implements PresenceResolver { + private final RoutePresence presence; + + CatchAllResolver(RoutePresence presence) { + this.presence = presence; + } + + @Override + public RoutePresence presenceOf(RoutePart.Param param) { + return param.isCatchAll() && param.frameworkName() == null ? presence : RoutePresence.UNKNOWN; + } + + @Override + public RoutePresence presenceOf(RoutePart.Group group) { + return RoutePresence.UNKNOWN; + } + } + + /** Reads {@link #EXTENDED_PATTERN_PROPERTY} on first use only, like Vert.x' own static init. */ + private static final class Vertx4GrammarHolder { + static final Grammar GRAMMAR = vertx4Grammar(Boolean.getBoolean(EXTENDED_PATTERN_PROPERTY)); + } +} diff --git a/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxRouteParser.java b/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxRouteParser.java index 8c0f708588c..2f88b841de2 100644 --- a/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxRouteParser.java +++ b/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxRouteParser.java @@ -210,6 +210,39 @@ public static RouteTemplate parse(String declaredPath, Grammar grammar) { .build(); } + /** + * Whether {@code declaredPath} declares a {@code :name} parameter called {@code name} under + * {@code grammar}. Never allocates. + */ + static boolean declaresParam(String declaredPath, String name, Grammar grammar) { + if (declaredPath == null || name == null || grammar == null) { + return false; + } + int len = declaredPath.length(); + for (int i = declaredPath.indexOf(':'); i >= 0; i = declaredPath.indexOf(':', i + 1)) { + int nameEnd = nameEnd(declaredPath, i, len, grammar); + if (nameEnd - i - 1 == name.length() && declaredPath.startsWith(name, i + 1)) { + return true; + } + } + return false; + } + + /** + * End (exclusive) of the parameter name that starts after the {@code :} at {@code colon}, within + * {@code end}; -1 when that {@code :} does not start a name (static text). + */ + static int nameEnd(String path, int colon, int end, Grammar grammar) { + if (colon + 1 >= end || !grammar.isNameStart(path.charAt(colon + 1))) { + return -1; + } + int nameEnd = colon + 2; + while (nameEnd < end && grammar.isNamePart(path.charAt(nameEnd))) { + nameEnd++; + } + return nameEnd; + } + /** Regex syntax that Vert.x does not escape in a parameter path (besides a non-trailing '*'). */ private static boolean isRegexOperator(char c) { switch (c) { diff --git a/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteForkedTest.java b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteForkedTest.java new file mode 100644 index 00000000000..00fb6113496 --- /dev/null +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteForkedTest.java @@ -0,0 +1,99 @@ +package datadog.trace.api.appsec.route; + +import static datadog.trace.api.KnownTags.DD_APPSEC_NORMALIZED_ROUTE; +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import datadog.trace.api.appsec.route.VertxRouteParser.Grammar; +import datadog.trace.bootstrap.ActiveSubsystems; +import datadog.trace.bootstrap.instrumentation.api.AgentSpan; +import datadog.trace.bootstrap.instrumentation.api.Tags; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +/** Mutates the global {@link ActiveSubsystems#APPSEC_ACTIVE}, so it runs in its own JVM. */ +class VertxNormalizedRouteForkedTest { + + private static final Map NO_PARAMS = Collections.emptyMap(); + + private boolean previousAppSecActive; + + @BeforeEach + void activateAppSec() { + previousAppSecActive = ActiveSubsystems.APPSEC_ACTIVE; + ActiveSubsystems.APPSEC_ACTIVE = true; + } + + @AfterEach + void restoreAppSec() { + ActiveSubsystems.APPSEC_ACTIVE = previousAppSecActive; + } + + @Test + void clearsThePreviousTagThenSetsTheNewOne() { + AgentSpan span = spanWithRoute("/sub/catch-all/"); + + VertxNormalizedRoute.tag( + span, + "/catch-all/*", + Grammar.DEFAULT, + "/sub/", + "/sub/catch-all/a", + Collections.singletonMap("*", "a")); + + InOrder order = inOrder(span); + order.verify(span).setTag(NORMALIZED_ROUTE_TAG, (String) null); + order.verify(span).setTag(DD_APPSEC_NORMALIZED_ROUTE, "/sub/catch-all/{param1}"); + } + + @Test + void onlyClearsForANullDeclaredPath() { + AgentSpan span = spanWithRoute("/a"); + + VertxNormalizedRoute.tag(span, null, Grammar.DEFAULT, null, "/a", NO_PARAMS); + + verify(span).setTag(NORMALIZED_ROUTE_TAG, (String) null); + verify(span, never()).setTag(anyLong(), anyString()); + } + + @Test + void onlyClearsForARegexLikeRoute() { + AgentSpan span = spanWithRoute("/a/:id?"); + + VertxNormalizedRoute.tag(span, "/a/:id?", Grammar.DEFAULT, null, "/a/1", NO_PARAMS); + + verify(span).setTag(NORMALIZED_ROUTE_TAG, (String) null); + verify(span, never()).setTag(anyLong(), anyString()); + } + + @Test + void onlyClearsUnderAParamMount() { + AgentSpan span = spanWithRoute("/acme/api/users/:id"); + Map params = new HashMap<>(); + params.put("tenant", "acme"); + params.put("id", "1"); + + VertxNormalizedRoute.tag( + span, "/users/:id", Grammar.DEFAULT, "/acme/api/", "/acme/api/users/1", params); + + verify(span).setTag(NORMALIZED_ROUTE_TAG, (String) null); + verify(span, never()).setTag(anyLong(), anyString()); + } + + private static AgentSpan spanWithRoute(String route) { + AgentSpan span = mock(AgentSpan.class); + when(span.getTag(Tags.HTTP_ROUTE)).thenReturn(route); + return span; + } +} diff --git a/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteTest.java b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteTest.java new file mode 100644 index 00000000000..94cb0c6f033 --- /dev/null +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteTest.java @@ -0,0 +1,126 @@ +package datadog.trace.api.appsec.route; + +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import datadog.trace.api.appsec.route.VertxRouteParser.Grammar; +import datadog.trace.bootstrap.instrumentation.api.AgentSpan; +import java.util.Collections; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.tabletest.junit.TableTest; + +class VertxNormalizedRouteTest { + + @TableTest({ + "Scenario | Declared | Grammar | Mount | Path | Params | Normalized ", + "static route | '/users' | DEFAULT | | '/users' | [:] | '/users' ", + "static route, mount with slash | '/users' | DEFAULT | '/sub/' | '/sub/users' | [:] | '/sub/users' ", + "static route, mount without slash | '/users' | LEGACY | '/sub' | '/sub/users' | [:] | '/sub/users' ", + "root route | '/' | DEFAULT | | '/' | [:] | '/' ", + "root route under a mount | '/' | DEFAULT | '/sub/' | '/sub/' | [:] | '/sub/' ", + "multi params per segment | '/a/:id.:format' | DEFAULT | | '/a/1.json' | [id: '1', format: json] | '/a/{id}.{format}' ", + "dashed params, extended grammar | '/t/:a-b' | EXTENDED | | '/t/1' | [a-b: '1'] | '/t/{a_b}' ", + "encoded literal | '/caf%C3%A9' | DEFAULT | | '/caf%C3%A9' | [:] | '/caf%C3%A9' ", + "encoded mount | '/x' | DEFAULT | '/caf%C3%A9/' | '/caf%C3%A9/x' | [:] | '/caf%C3%A9/x' ", + "catch-all, base only | '/catch-all/*' | DEFAULT | | '/catch-all' | ['*': '/'] | '/catch-all' ", + "catch-all, trailing slash | '/catch-all/*' | DEFAULT | | '/catch-all/' | ['*': ''] | '/catch-all/' ", + "catch-all, present | '/catch-all/*' | DEFAULT | | '/catch-all/a/b' | ['*': 'a/b'] | '/catch-all/{param1}' ", + "catch-all, double slash normalized | '/api_security/catch-all/*' | DEFAULT | | '/api_security/catch-all/' | [:] | '/api_security/catch-all/'", + "catch-all, other segment | '/catch-all/*' | DEFAULT | | '/catch-allx' | [:] | '/catch-all' ", + "catch-all, path outside the base | '/catch-all/*' | DEFAULT | | '/other/a' | [:] | '/catch-all' ", + "catch-all, no normalized path | '/catch-all/*' | DEFAULT | | | [:] | '/catch-all' ", + "catch-all under mount with slash | '/catch-all/*' | DEFAULT | '/sub/' | '/sub/catch-all/a' | ['*': 'a'] | '/sub/catch-all/{param1}' ", + "catch-all under mount without slash | '/catch-all/*' | LEGACY | '/sub' | '/sub/catch-all/a' | [:] | '/sub/catch-all/{param1}' ", + "catch-all under mount, base only | '/catch-all/*' | DEFAULT | '/sub/' | '/sub/catch-all' | [:] | '/sub/catch-all' ", + "catch-all, path outside the mount | '/catch-all/*' | DEFAULT | '/sub/' | '/other/catch-all/a' | [:] | '/sub/catch-all' ", + "root catch-all, root path | '/*' | DEFAULT | | '/' | [:] | '/' ", + "root catch-all, present | '/*' | DEFAULT | | '/x' | [:] | '/{param1}' ", + "root catch-all under mount, present | '/*' | DEFAULT | '/sub/' | '/sub/x' | [:] | '/sub/{param1}' ", + "root catch-all under mount, slash | '/*' | DEFAULT | '/sub/' | '/sub/' | [:] | '/sub/' ", + "root catch-all under mount, base only | '/*' | LEGACY | '/sub' | '/sub' | [:] | '/sub' ", + "in-segment catch-all, present | '/img*' | DEFAULT | | '/img42' | [:] | '/img{param1}' ", + "in-segment catch-all, absent | '/img*' | DEFAULT | | '/img' | [:] | '/img' ", + "param prefix route, slash | '/users/:id/*' | DEFAULT | | '/users/5/' | [id: '5'] | '/users/{id}/' ", + "param prefix route, present | '/users/:id/*' | DEFAULT | | '/users/5/a/b' | [id: '5', '*': 'a/b'] | '/users/{id}/{param1}' ", + "param prefix route, absent | '/users/:id/*' | DEFAULT | | '/users/5' | [id: '5'] | '/users/{id}' ", + "param prefix route, too few segments | '/users/:id/*' | DEFAULT | | '/users' | [:] | '/users/{id}' ", + "param prefix route, no leading slash | '/users/:id/*' | DEFAULT | | 'users/5/a' | [:] | '/users/{id}' ", + "param prefix route under mount | '/users/:id/*' | DEFAULT | '/sub/' | '/sub/users/5/a' | [id: '5'] | '/sub/users/{id}/{param1}'", + "param prefix route outside the mount | '/users/:id/*' | DEFAULT | '/sub/' | '/users/5/a' | [id: '5'] | '/sub/users/{id}' ", + "in-segment star after param, present | '/u/:id*' | DEFAULT | | '/u/5/x' | [id: '5'] | '/u/{id}{param1}' ", + "in-segment star after param, absent | '/u/:id*' | DEFAULT | | '/u/5' | [id: '5'] | '/u/{id}' ", + "in-segment star after literal, present | '/f/:id.json*' | DEFAULT | | '/f/a.json.jsonx' | [id: a.json] | '/f/{id}.json{param1}' ", + "in-segment star after literal, absent | '/f/:id.json*' | DEFAULT | | '/f/a.json' | [id: a] | '/f/{id}.json' ", + "in-segment star after literal, no match | '/f/:id.json*' | DEFAULT | | '/f/.json' | [:] | '/f/{id}.json' ", + "in-segment star, literal segment, present | '/u/:id/img*' | DEFAULT | | '/u/5/img1' | [id: '5'] | '/u/{id}/img{param1}' ", + "in-segment star, literal segment, absent | '/u/:id/img*' | DEFAULT | | '/u/5/img' | [id: '5'] | '/u/{id}/img' ", + "in-segment star, literal segment mismatch | '/u/:id/img*' | DEFAULT | | '/u/5/pic1' | [id: '5'] | '/u/{id}/img' ", + "in-segment star, legacy colon literal | '/u/:id/a:*' | LEGACY | | '/u/5/a:x' | [id: '5'] | '/u/{id}/a%3A{param1}' ", + "not expressible regex metachar | '/a/:id?' | DEFAULT | | '/a/1' | [:] | ", + "null declared path | | DEFAULT | | '/a' | [:] | ", + "null grammar | '/a' | | | '/a' | [:] | ", + "param mount: undeclared bound param | '/users/:id' | DEFAULT | '/acme/api/' | '/acme/api/users/1' | [tenant: acme, id: '1'] | ", + "same params without mount | '/users/:id' | DEFAULT | | '/users/1' | [tenant: acme, id: '1'] | '/users/{id}' ", + "same params with empty mount | '/users/:id' | DEFAULT | '' | '/users/1' | [tenant: acme, id: '1'] | '/users/{id}' ", + "mount: rest param ignored | '/users/:id' | DEFAULT | '/sub/' | '/sub/users/1' | [id: '1', '*': x] | '/sub/users/{id}' ", + "mount: no params | '/users/:id' | DEFAULT | '/sub/' | '/sub/users/1' | | '/sub/users/{id}' " + }) + void rendersTheNormalizedRoute( + String declared, + Grammar grammar, + String mount, + String path, + Map params, + String normalized) { + assertEquals(normalized, VertxNormalizedRoute.render(declared, grammar, mount, path, params)); + } + + @Test + void clearsThePreviousTagBeforeTagging() { + AgentSpan span = mock(AgentSpan.class); + + VertxNormalizedRoute.tag( + span, "/users/:id", Grammar.DEFAULT, null, "/users/1", Collections.emptyMap()); + + // the tag is only set when NormalizedRouteHelper is enabled (see the forked test) + verify(span).setTag(NORMALIZED_ROUTE_TAG, (String) null); + } + + @Test + void neverThrows() { + AgentSpan span = mock(AgentSpan.class); + when(span.setTag(anyString(), (String) isNull())).thenThrow(new IllegalStateException("boom")); + + assertDoesNotThrow(() -> + VertxNormalizedRoute.tag( + span, "/users/:id", Grammar.DEFAULT, null, "/users/1", Collections.emptyMap())); + assertDoesNotThrow(() -> + VertxNormalizedRoute.tag( + null, "/users/:id", Grammar.DEFAULT, null, "/users/1", Collections.emptyMap())); + } + + @Test + void catchAllResolverOnlyAnswersForTheUnnamedCatchAll() { + PresenceResolver resolver = VertxNormalizedRoute.catchAllResolver(RoutePresence.PRESENT); + + assertEquals(RoutePresence.PRESENT, resolver.presenceOf(RoutePart.catchAll(null))); + assertEquals(RoutePresence.UNKNOWN, resolver.presenceOf(RoutePart.catchAll("rest"))); + assertEquals(RoutePresence.UNKNOWN, resolver.presenceOf(RoutePart.optionalParam("id"))); + assertEquals( + RoutePresence.UNKNOWN, resolver.presenceOf(RoutePart.group(RoutePart.literal("a")))); + } + + @Test + void vertx4GrammarDefaultsToDefault() { + assertEquals(Grammar.DEFAULT, VertxNormalizedRoute.vertx4Grammar()); + assertEquals(Grammar.DEFAULT, VertxNormalizedRoute.vertx4Grammar(false)); + assertEquals(Grammar.EXTENDED, VertxNormalizedRoute.vertx4Grammar(true)); + } +} diff --git a/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserTest.java b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserTest.java index 33ccf7ed98e..5114ea79369 100644 --- a/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserTest.java +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserTest.java @@ -152,6 +152,37 @@ void trailingWholeSegmentCatchAllNeedsTheRemainder() { assertFalse(VertxRouteParser.parse("/img*", Grammar.DEFAULT).needsUnnamedCatchAllRemainder()); } + @TableTest({ + "Scenario | Grammar | Path | Name | Declared", + "single param | DEFAULT | '/users/:id' | id | true ", + "second param in segment | DEFAULT | '/a/:id.:format' | format | true ", + "name prefix of a longer name | DEFAULT | '/a/:idx' | id | false ", + "longer name than declared | DEFAULT | '/a/:id' | idx | false ", + "name before a trailing star | DEFAULT | '/a/:id*' | id | true ", + "undeclared name | DEFAULT | '/users/:id' | tenant | false ", + "no param | DEFAULT | '/users' | id | false ", + "colon without a name | LEGACY | '/a/:1/:id' | id | true ", + "digit name, legacy | LEGACY | '/a/:1abc' | 1abc | false ", + "digit name, default | DEFAULT | '/a/:1abc' | 1abc | true ", + "dashed name, extended | EXTENDED | '/a/:a-b' | a-b | true ", + "dashed name, default | DEFAULT | '/a/:a-b' | a-b | false ", + "empty name | DEFAULT | '/a/:id' | '' | false ", + "null name | DEFAULT | '/a/:id' | | false ", + "null path | DEFAULT | | id | false ", + "null grammar | | '/a/:id' | id | false " + }) + void findsDeclaredParams(Grammar grammar, String path, String name, boolean declared) { + assertEquals(declared, VertxRouteParser.declaresParam(path, name, grammar)); + } + + @Test + void findsTheEndOfAParamName() { + assertEquals(6, VertxRouteParser.nameEnd("/a/:id.json", 3, 11, Grammar.DEFAULT)); + assertEquals(5, VertxRouteParser.nameEnd("/a/:id.json", 3, 5, Grammar.DEFAULT)); + assertEquals(-1, VertxRouteParser.nameEnd("/a/:", 3, 4, Grammar.DEFAULT)); + assertEquals(-1, VertxRouteParser.nameEnd("/a/:.x", 3, 6, Grammar.DEFAULT)); + } + @Test void rendersWithMountPrefix() { assertEquals( From b09675059476152c84f1e7863b11ca7214110b81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20Gonz=C3=A1lez=20Garc=C3=ADa?= Date: Thu, 26 Nov 2026 16:04:47 +0100 Subject: [PATCH 3/9] Tag Vert.x 3 server spans with _dd.appsec.normalized_route --- .../server/RouteHandlerInstrumentation.java | 18 +++ .../vertx_3_4/server/RouteHandlerWrapper.java | 35 ++++- .../server/RouteHandlerWrapperAdvice.java | 5 +- .../vertx_3_4/server/RouteSetPathAdvice.java | 21 +++ .../vertx_3_4/server/RouteSetRegexAdvice.java | 13 ++ .../AbstractVertxNormalizedRouteTest.java | 139 ++++++++++++++++++ ...zedRouteApiSecurityDisabledForkedTest.java | 25 ++++ .../VertxNormalizedRouteTest.java | 112 ++++++++++++++ 8 files changed, 366 insertions(+), 2 deletions(-) create mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteSetPathAdvice.java create mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteSetRegexAdvice.java create mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java create mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java create mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerInstrumentation.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerInstrumentation.java index ed4b4072038..b90d195e0a5 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerInstrumentation.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerInstrumentation.java @@ -5,10 +5,13 @@ import static net.bytebuddy.matcher.ElementMatchers.isMethod; import static net.bytebuddy.matcher.ElementMatchers.isPublic; import static net.bytebuddy.matcher.ElementMatchers.takesArgument; +import static net.bytebuddy.matcher.ElementMatchers.takesArguments; import com.google.auto.service.AutoService; import datadog.trace.agent.tooling.Instrumenter; import datadog.trace.agent.tooling.InstrumenterModule; +import java.util.Collections; +import java.util.Map; @AutoService(InstrumenterModule.class) public class RouteHandlerInstrumentation extends InstrumenterModule.Tracing @@ -22,6 +25,12 @@ public String instrumentedType() { return "io.vertx.ext.web.impl.RouteImpl"; } + /** Declared path of each route, as the app wrote it (with its trailing {@code *}). */ + @Override + public Map contextStore() { + return Collections.singletonMap("io.vertx.ext.web.Route", String.class.getName()); + } + @Override public void methodAdvice(MethodTransformer transformer) { transformer.applyAdvice( @@ -30,5 +39,14 @@ public void methodAdvice(MethodTransformer transformer) { .and(isPublic()) .and(takesArgument(0, named("io.vertx.core.Handler"))), packageName + ".RouteHandlerWrapperAdvice"); + transformer.applyAdvice( + isMethod().and(named("setPath")).and(takesArguments(1)).and(takesArgument(0, String.class)), + packageName + ".RouteSetPathAdvice"); + transformer.applyAdvice( + isMethod() + .and(named("setRegex")) + .and(takesArguments(1)) + .and(takesArgument(0, String.class)), + packageName + ".RouteSetRegexAdvice"); } } diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerWrapper.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerWrapper.java index 7af44b78e9d..4e6ba9479c4 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerWrapper.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerWrapper.java @@ -8,14 +8,23 @@ import static datadog.trace.instrumentation.vertx_3_4.server.VertxDecorator.INSTRUMENTATION_NAME; import datadog.context.ContextScope; +import datadog.trace.api.appsec.route.NormalizedRouteHelper; +import datadog.trace.api.appsec.route.VertxNormalizedRoute; +import datadog.trace.api.appsec.route.VertxRouteParser; +import datadog.trace.bootstrap.ContextStore; import datadog.trace.bootstrap.instrumentation.api.AgentSpan; import datadog.trace.bootstrap.instrumentation.api.Tags; import io.vertx.core.Handler; +import io.vertx.ext.web.Route; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.impl.RouteImpl; import io.vertx.ext.web.impl.RouterImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class RouteHandlerWrapper implements Handler { + private static final Logger log = LoggerFactory.getLogger(RouteHandlerWrapper.class); + static final String PARENT_SPAN_CONTEXT_KEY = AgentSpan.class.getName() + ".parent"; static final String HANDLER_SPAN_CONTEXT_KEY = AgentSpan.class.getName() + ".handler"; static final String ROUTE_CONTEXT_KEY = "dd." + Tags.HTTP_ROUTE; @@ -23,8 +32,13 @@ public class RouteHandlerWrapper implements Handler { private final Handler actual; private final boolean spanStarter; - public RouteHandlerWrapper(final Handler handler) { + /** Declared path of each route, null when the instrumentation could not provide it. */ + private final ContextStore declaredPaths; + + public RouteHandlerWrapper( + final Handler handler, final ContextStore declaredPaths) { actual = handler; + this.declaredPaths = declaredPaths; // When mounting a sub router, the handler is a lambda in either RouterImpl or RouteImpl, so // this skips that. This prevents routers from creating a span during handling. In the event // a route is not found, without this code, a span would be created for the router when it @@ -106,6 +120,25 @@ private void setRoute(RoutingContext routingContext) { if (method != null && path != null && shouldUpdateRoute(routingContext, parentSpan, path)) { routingContext.put(ROUTE_CONTEXT_KEY, path); HTTP_RESOURCE_DECORATOR.withRoute(parentSpan, method, path, true); + if (NormalizedRouteHelper.isEnabled()) { + tagNormalizedRoute(routingContext, parentSpan); + } + } + } + + private void tagNormalizedRoute(final RoutingContext routingContext, final AgentSpan span) { + try { + final String declared = + declaredPaths != null ? declaredPaths.get(routingContext.currentRoute()) : null; + VertxNormalizedRoute.tag( + span, + declared, + VertxRouteParser.Grammar.LEGACY, + routingContext.mountPoint(), + routingContext.normalisedPath(), + routingContext.pathParams()); + } catch (Throwable t) { + log.debug("Failed to collect the Vert.x normalized route", t); } } diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerWrapperAdvice.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerWrapperAdvice.java index 69b745a8287..7564f8da838 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerWrapperAdvice.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerWrapperAdvice.java @@ -1,6 +1,8 @@ package datadog.trace.instrumentation.vertx_3_4.server; +import datadog.trace.bootstrap.InstrumentationContext; import io.vertx.core.Handler; +import io.vertx.ext.web.Route; import io.vertx.ext.web.RoutingContext; import net.bytebuddy.asm.Advice; @@ -8,6 +10,7 @@ public class RouteHandlerWrapperAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) public static void wrapHandler( @Advice.Argument(value = 0, readOnly = false) Handler handler) { - handler = new RouteHandlerWrapper(handler); + handler = + new RouteHandlerWrapper(handler, InstrumentationContext.get(Route.class, String.class)); } } diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteSetPathAdvice.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteSetPathAdvice.java new file mode 100644 index 00000000000..522526bae65 --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteSetPathAdvice.java @@ -0,0 +1,21 @@ +package datadog.trace.instrumentation.vertx_3_4.server; + +import datadog.trace.bootstrap.InstrumentationContext; +import io.vertx.ext.web.Route; +import net.bytebuddy.asm.Advice; + +/** + * Keeps the path of {@code RouteImpl.setPath(String)} as declared: {@code Route.getPath()} drops + * the trailing {@code *}, so a catch-all route would look like an exact one. + */ +public class RouteSetPathAdvice { + @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class) + public static void onExit( + @Advice.This final Route route, + @Advice.Argument(0) final String path, + @Advice.Thrown final Throwable thrown) { + if (thrown == null) { + InstrumentationContext.get(Route.class, String.class).put(route, path); + } + } +} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteSetRegexAdvice.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteSetRegexAdvice.java new file mode 100644 index 00000000000..8d9609f5a35 --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteSetRegexAdvice.java @@ -0,0 +1,13 @@ +package datadog.trace.instrumentation.vertx_3_4.server; + +import datadog.trace.bootstrap.InstrumentationContext; +import io.vertx.ext.web.Route; +import net.bytebuddy.asm.Advice; + +/** A regex route has no declared path: drops any path stored by an earlier {@code path(..)}. */ +public class RouteSetRegexAdvice { + @Advice.OnMethodExit(suppress = Throwable.class) + public static void onExit(@Advice.This final Route route) { + InstrumentationContext.get(Route.class, String.class).remove(route); + } +} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java new file mode 100644 index 00000000000..45765ca137b --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java @@ -0,0 +1,139 @@ +package server.normalizedroute; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; + +import datadog.trace.agent.test.AbstractInstrumentationTest; +import datadog.trace.agent.test.utils.OkHttpUtils; +import datadog.trace.bootstrap.ActiveSubsystems; +import datadog.trace.core.DDSpan; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpServer; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; +import java.net.ServerSocket; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestInstance; + +/** + * Runs a Vert.x 3.x server with the normalized route test routes, with AppSec forced active like + * the Spock {@code InstrumentationSpecification}, and returns the tags of the server span. + */ +@TestInstance(PER_CLASS) +abstract class AbstractVertxNormalizedRouteTest extends AbstractInstrumentationTest { + + private final OkHttpClient client = OkHttpUtils.client(); + private Vertx vertx; + private HttpServer server; + private int port; + private boolean appSecActiveBefore; + + @BeforeAll + void startServer() throws Exception { + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); + } + vertx = Vertx.vertx(); + Router router = Router.router(vertx); + router.route("/").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/multi/:id.:format").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/three/:a-:b-:c").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/static-text/user-:id").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/catch-all/*").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/encoded/caf%C3%A9").handler(AbstractVertxNormalizedRouteTest::ok); + router.routeWithRegex("/regex/(\\d+)").handler(AbstractVertxNormalizedRouteTest::ok); + // middleware with a declared path, then a regex route: the regex route must not keep its tag + router.route("/stale/*").handler(RoutingContext::next); + router.routeWithRegex("/stale/(\\d+)").handler(AbstractVertxNormalizedRouteTest::ok); + // same, but the regex route also has a path, so http.route is updated by the regex route + router.route("/stale-path/*").handler(RoutingContext::next); + router + .route("/stale-path/x") + .pathRegex("/stale-path/(\\d+)") + .handler(AbstractVertxNormalizedRouteTest::ok); + + Router sub = Router.router(vertx); + sub.route("/users/:id").handler(AbstractVertxNormalizedRouteTest::ok); + sub.route("/files/*").handler(AbstractVertxNormalizedRouteTest::ok); + router.mountSubRouter("/sub", sub); + + CountDownLatch ready = new CountDownLatch(1); + server = + vertx + .createHttpServer() + .requestHandler(router::accept) + .listen( + port, + result -> { + if (result.failed()) { + throw new RuntimeException("Failed to start Vert.x server", result.cause()); + } + ready.countDown(); + }); + if (!ready.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Vert.x server did not start in time"); + } + } + + @AfterAll + void stopServer() throws Exception { + if (server != null) { + CountDownLatch closed = new CountDownLatch(1); + server.close(ar -> closed.countDown()); + closed.await(10, TimeUnit.SECONDS); + } + if (vertx != null) { + CountDownLatch closed = new CountDownLatch(1); + vertx.close(ar -> closed.countDown()); + closed.await(10, TimeUnit.SECONDS); + } + } + + @BeforeEach + void forceAppSecActive() { + appSecActiveBefore = ActiveSubsystems.APPSEC_ACTIVE; + ActiveSubsystems.APPSEC_ACTIVE = true; + } + + @AfterEach + void restoreAppSecActive() { + ActiveSubsystems.APPSEC_ACTIVE = appSecActiveBefore; + } + + private static void ok(RoutingContext ctx) { + ctx.response().setStatusCode(200).end("ok"); + } + + /** Sends {@code GET path} and returns the HTTP status. */ + int get(String path) throws Exception { + Request request = new Request.Builder().url("http://localhost:" + port + path).get().build(); + try (Response response = client.newCall(request).execute()) { + return response.code(); + } + } + + /** Tags of the {@code netty.request} span of the single trace written. */ + Map serverSpanTags() throws Exception { + writer.waitForTraces(1); + DDSpan serverSpan = null; + for (List trace : writer) { + for (DDSpan span : trace) { + if ("netty.request".equals(span.getOperationName().toString())) { + serverSpan = span; + } + } + } + assertNotNull(serverSpan, "netty.request span"); + return serverSpan.getTags(); + } +} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java new file mode 100644 index 00000000000..a8825bac467 --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java @@ -0,0 +1,25 @@ +package server.normalizedroute; + +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import datadog.trace.api.config.AppSecConfig; +import datadog.trace.test.junit.utils.config.WithConfig; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** With API Security disabled the normalized route is not set; {@code http.route} still is. */ +@WithConfig(key = AppSecConfig.API_SECURITY_ENABLED, value = "false") +class VertxNormalizedRouteApiSecurityDisabledForkedTest extends AbstractVertxNormalizedRouteTest { + + @Test + void noNormalizedRouteWhenApiSecurityIsDisabled() throws Exception { + assertEquals(200, get("/multi/1.json")); + Map tags = serverSpanTags(); + + assertEquals("/multi/:id.:format", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } +} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java new file mode 100644 index 00000000000..69a893c60c9 --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java @@ -0,0 +1,112 @@ +package server.normalizedroute; + +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import datadog.trace.bootstrap.ActiveSubsystems; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.tabletest.junit.TableTest; + +/** Normalized route of Vert.x 3.x routes, top level and under {@code mountSubRouter("/sub")}. */ +class VertxNormalizedRouteTest extends AbstractVertxNormalizedRouteTest { + + @TableTest({ + "Scenario | Request | Route | Normalized ", + "root | '/' | '/' | '/' ", + "two params in a segment | '/multi/1.json' | '/multi/:id.:format' | '/multi/{id}.{format}' ", + "three params in a segment | '/three/1-2-3' | '/three/:a-:b-:c' | '/three/{a}-{b}-{c}' ", + "static text before a param | '/static-text/user-1' | '/static-text/user-:id' | '/static-text/user-{id}'", + "catch-all present | '/catch-all/a/b/c.txt' | '/catch-all/' | '/catch-all/{param1}' ", + "catch-all matched a slash | '/catch-all/' | '/catch-all/' | '/catch-all/' ", + "catch-all after a collapsed slash | '/catch-all//' | '/catch-all/' | '/catch-all/' ", + "encoded literal | '/encoded/caf%C3%A9' | '/encoded/café' | '/encoded/caf%C3%A9' ", + "sub-router param | '/sub/users/1' | '/sub/users/:id' | '/sub/users/{id}' ", + "sub-router catch-all | '/sub/files/a' | '/sub/files/' | '/sub/files/{param1}' " + }) + void normalizedRoute(String request, String route, String normalized) throws Exception { + assertEquals(200, get(request)); + Map tags = serverSpanTags(); + + assertEquals(route, String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals(normalized, String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } + + /** + * The store holds the declared {@code /catch-all/*}: {@code getPath()} drops the trailing {@code + * *} (http.route {@code /catch-all/}), so only the declared path gives {@code {param1}}. + */ + @Test + void storeKeepsTheTrailingStarOfTheDeclaredPath() throws Exception { + assertEquals(200, get("/catch-all/x")); + Map tags = serverSpanTags(); + + assertEquals("/catch-all/", String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals("/catch-all/{param1}", String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } + + @Test + void noNormalizedRouteForRegexRoute() throws Exception { + assertEquals(200, get("/regex/123")); + Map tags = serverSpanTags(); + + assertNull(tags.get(HTTP_ROUTE)); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + /** The regex route has a path, so it updates {@code http.route} and clears the stale tag. */ + @Test + void staleNormalizedRouteIsClearedByLaterRegexRoute() throws Exception { + assertEquals(200, get("/stale-path/1")); + Map tags = serverSpanTags(); + + assertEquals("/stale-path/x", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + @Test + void noNormalizedRouteWhenAppSecIsInactive() throws Exception { + ActiveSubsystems.APPSEC_ACTIVE = false; + + assertEquals(200, get("/multi/1.json")); + Map tags = serverSpanTags(); + + assertEquals("/multi/:id.:format", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + /** + * {@code /catch-all} for {@code /catch-all/*}: Vert.x 3.4 matches it (catch-all removed), later + * 3.x versions do not (404, no route handler, no tag). + */ + @Test + void catchAllWithoutTrailingSlash() throws Exception { + int status = get("/catch-all"); + Map tags = serverSpanTags(); + + if (status == 200) { + assertEquals("/catch-all/", String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals("/catch-all", String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } else { + assertEquals(404, status); + assertNull(tags.get(HTTP_ROUTE)); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + } + + /** + * A regex route without a path does not update {@code http.route}, so both tags keep the values + * of the {@code /stale/*} middleware: the normalized route stays consistent with {@code + * http.route}. + */ + @Test + void regexRouteWithoutPathKeepsBothTagsOfTheMiddleware() throws Exception { + assertEquals(200, get("/stale/1")); + Map tags = serverSpanTags(); + + assertEquals("/stale/", String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals("/stale/{param1}", String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } +} From 8b0179c08039eaba71671495641f0159ae8cca2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20Gonz=C3=A1lez=20Garc=C3=ADa?= Date: Thu, 26 Nov 2026 16:13:17 +0100 Subject: [PATCH 4/9] Tag Vert.x 4 and 5 server spans with _dd.appsec.normalized_route --- .../AbstractVertxNormalizedRouteTest.java | 144 ++++++++++++++++++ ...zedRouteApiSecurityDisabledForkedTest.java | 25 +++ .../VertxNormalizedRouteTest.java | 116 ++++++++++++++ .../server/RouteHandlerInstrumentation.java | 18 +++ .../vertx_4_0/server/RouteHandlerWrapper.java | 34 ++++- .../server/RouteHandlerWrapperAdvice.java | 5 +- .../vertx_4_0/server/RouteSetPathAdvice.java | 21 +++ .../vertx_4_0/server/RouteSetRegexAdvice.java | 13 ++ .../AbstractVertxNormalizedRouteTest.java | 144 ++++++++++++++++++ ...zedRouteApiSecurityDisabledForkedTest.java | 25 +++ .../VertxNormalizedRouteTest.java | 116 ++++++++++++++ .../AbstractVertxNormalizedRouteTest.java | 144 ++++++++++++++++++ ...zedRouteApiSecurityDisabledForkedTest.java | 25 +++ .../VertxNormalizedRouteTest.java | 116 ++++++++++++++ 14 files changed, 944 insertions(+), 2 deletions(-) create mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java create mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java create mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/VertxNormalizedRouteTest.java create mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteSetPathAdvice.java create mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteSetRegexAdvice.java create mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java create mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java create mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java create mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java create mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java create mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java new file mode 100644 index 00000000000..cccd95728da --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java @@ -0,0 +1,144 @@ +package server.normalizedroute; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; + +import datadog.trace.agent.test.AbstractInstrumentationTest; +import datadog.trace.agent.test.utils.OkHttpUtils; +import datadog.trace.bootstrap.ActiveSubsystems; +import datadog.trace.core.DDSpan; +import io.vertx.core.Future; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpServer; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; +import java.net.ServerSocket; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestInstance; + +/** + * Runs a Vert.x 4.x or 5.x server with the normalized route test routes, with AppSec forced active + * like the Spock {@code InstrumentationSpecification}, and returns the tags of the server span. + * Only APIs shared by Vert.x 4.0.0 and 5.x are used, so the same source runs on every version. + */ +@TestInstance(PER_CLASS) +abstract class AbstractVertxNormalizedRouteTest extends AbstractInstrumentationTest { + + private final OkHttpClient client = OkHttpUtils.client(); + private Vertx vertx; + private HttpServer server; + private int port; + private boolean appSecActiveBefore; + + @BeforeAll + void startServer() throws Exception { + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); + } + vertx = Vertx.vertx(); + Router router = Router.router(vertx); + router.route("/").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/multi/:id.:format").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/three/:a-:b-:c").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/static-text/user-:id").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/catch-all/*").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/encoded/caf%C3%A9").handler(AbstractVertxNormalizedRouteTest::ok); + router.routeWithRegex("/regex/(\\d+)").handler(AbstractVertxNormalizedRouteTest::ok); + // middleware with a declared path, then a regex route: the regex route must not keep its tag + router.route("/stale/*").handler(RoutingContext::next); + router.routeWithRegex("/stale/(\\d+)").handler(AbstractVertxNormalizedRouteTest::ok); + + // what mountSubRouter("/sub/", sub) does on 4.x (mountSubRouter is gone in 5.x) + Router sub = Router.router(vertx); + sub.route("/users/:id").handler(AbstractVertxNormalizedRouteTest::ok); + sub.route("/files/*").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/sub/*").subRouter(sub); + + // a mount with a parameter: the mount point is the concrete matched prefix + Router tenant = Router.router(vertx); + tenant.route("/items/:id").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/:tenant/api/*").subRouter(tenant); + + server = await(vertx.createHttpServer().requestHandler(router).listen(port)); + } + + @AfterAll + void stopServer() throws Exception { + if (server != null) { + await(server.close()); + } + if (vertx != null) { + await(vertx.close()); + } + } + + @BeforeEach + void forceAppSecActive() { + appSecActiveBefore = ActiveSubsystems.APPSEC_ACTIVE; + ActiveSubsystems.APPSEC_ACTIVE = true; + } + + @AfterEach + void restoreAppSecActive() { + ActiveSubsystems.APPSEC_ACTIVE = appSecActiveBefore; + } + + private static void ok(RoutingContext ctx) { + ctx.response().setStatusCode(200).end("ok"); + } + + private static T await(Future future) throws Exception { + CountDownLatch done = new CountDownLatch(1); + AtomicReference result = new AtomicReference<>(); + AtomicReference failure = new AtomicReference<>(); + future.onComplete(ar -> { + if (ar.succeeded()) { + result.set(ar.result()); + } else { + failure.set(ar.cause()); + } + done.countDown(); + }); + if (!done.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Vert.x operation did not complete in time"); + } + if (failure.get() != null) { + throw new RuntimeException("Vert.x operation failed", failure.get()); + } + return result.get(); + } + + /** Sends {@code GET path} and returns the HTTP status. */ + int get(String path) throws Exception { + Request request = new Request.Builder().url("http://localhost:" + port + path).get().build(); + try (Response response = client.newCall(request).execute()) { + return response.code(); + } + } + + /** Tags of the {@code netty.request} span of the single trace written. */ + Map serverSpanTags() throws Exception { + writer.waitForTraces(1); + DDSpan serverSpan = null; + for (List trace : writer) { + for (DDSpan span : trace) { + if ("netty.request".equals(span.getOperationName().toString())) { + serverSpan = span; + } + } + } + assertNotNull(serverSpan, "netty.request span"); + return serverSpan.getTags(); + } +} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java new file mode 100644 index 00000000000..a8825bac467 --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java @@ -0,0 +1,25 @@ +package server.normalizedroute; + +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import datadog.trace.api.config.AppSecConfig; +import datadog.trace.test.junit.utils.config.WithConfig; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** With API Security disabled the normalized route is not set; {@code http.route} still is. */ +@WithConfig(key = AppSecConfig.API_SECURITY_ENABLED, value = "false") +class VertxNormalizedRouteApiSecurityDisabledForkedTest extends AbstractVertxNormalizedRouteTest { + + @Test + void noNormalizedRouteWhenApiSecurityIsDisabled() throws Exception { + assertEquals(200, get("/multi/1.json")); + Map tags = serverSpanTags(); + + assertEquals("/multi/:id.:format", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } +} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/VertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/VertxNormalizedRouteTest.java new file mode 100644 index 00000000000..9d4f84fb2c6 --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/VertxNormalizedRouteTest.java @@ -0,0 +1,116 @@ +package server.normalizedroute; + +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import datadog.trace.bootstrap.ActiveSubsystems; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.tabletest.junit.TableTest; + +/** Normalized route of Vert.x 4.x and 5.x routes, top level and under the {@code /sub} mount. */ +class VertxNormalizedRouteTest extends AbstractVertxNormalizedRouteTest { + + @TableTest({ + "Scenario | Request | Route | Normalized ", + "root | '/' | '/' | '/' ", + "two params in a segment | '/multi/1.json' | '/multi/:id.:format' | '/multi/{id}.{format}' ", + "three params in a segment | '/three/1-2-3' | '/three/:a-:b-:c' | '/three/{a}-{b}-{c}' ", + "static text before a param | '/static-text/user-1' | '/static-text/user-:id' | '/static-text/user-{id}'", + "catch-all present | '/catch-all/a/b/c.txt' | '/catch-all/' | '/catch-all/{param1}' ", + "catch-all matched a slash | '/catch-all/' | '/catch-all/' | '/catch-all/' ", + "catch-all after a collapsed slash | '/catch-all//' | '/catch-all/' | '/catch-all/' ", + "encoded literal | '/encoded/caf%C3%A9' | '/encoded/café' | '/encoded/caf%C3%A9' ", + "sub-router param | '/sub/users/1' | '/sub/users/:id' | '/sub/users/{id}' ", + "sub-router catch-all | '/sub/files/a' | '/sub/files/' | '/sub/files/{param1}' " + }) + void normalizedRoute(String request, String route, String normalized) throws Exception { + assertEquals(200, get(request)); + Map tags = serverSpanTags(); + + assertEquals(route, String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals(normalized, String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } + + /** + * The store holds the declared {@code /catch-all/*}: {@code getPath()} drops the trailing {@code + * *} (http.route {@code /catch-all/}), so only the declared path gives {@code {param1}}. + */ + @Test + void storeKeepsTheTrailingStarOfTheDeclaredPath() throws Exception { + assertEquals(200, get("/catch-all/x")); + Map tags = serverSpanTags(); + + assertEquals("/catch-all/", String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals("/catch-all/{param1}", String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } + + /** {@code http.route} falls back to the regex of the route; a regex has no normalized route. */ + @Test + void noNormalizedRouteForRegexRoute() throws Exception { + assertEquals(200, get("/regex/123")); + Map tags = serverSpanTags(); + + assertEquals("/regex/(\\d+)", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + /** + * The {@code /stale/*} middleware tags the span first; the regex route then updates {@code + * http.route} with its regex and must clear the normalized route of the middleware. + */ + @Test + void staleNormalizedRouteIsClearedByLaterRegexRoute() throws Exception { + assertEquals(200, get("/stale/1")); + Map tags = serverSpanTags(); + + assertEquals("/stale/(\\d+)", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + /** + * Under {@code route("/:tenant/api/*").subRouter(..)} the mount point is the concrete prefix + * ({@code /acme/api/}), which holds a request value: no normalized route, {@code http.route} + * unchanged. + */ + @Test + void noNormalizedRouteUnderAParameterMount() throws Exception { + assertEquals(200, get("/acme/api/items/1")); + Map tags = serverSpanTags(); + + assertEquals("/acme/api/items/:id", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + @Test + void noNormalizedRouteWhenAppSecIsInactive() throws Exception { + ActiveSubsystems.APPSEC_ACTIVE = false; + + assertEquals(200, get("/multi/1.json")); + Map tags = serverSpanTags(); + + assertEquals("/multi/:id.:format", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + /** + * {@code /catch-all} for {@code /catch-all/*}: Vert.x 4.0.3+ matches it (catch-all removed), + * 4.0.0 to 4.0.2 do not (404, no route handler, no tag). + */ + @Test + void catchAllWithoutTrailingSlash() throws Exception { + int status = get("/catch-all"); + Map tags = serverSpanTags(); + + if (status == 200) { + assertEquals("/catch-all/", String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals("/catch-all", String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } else { + assertEquals(404, status); + assertNull(tags.get(HTTP_ROUTE)); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + } +} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerInstrumentation.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerInstrumentation.java index cbce0265a27..5f3d6e09472 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerInstrumentation.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerInstrumentation.java @@ -5,11 +5,14 @@ import static net.bytebuddy.matcher.ElementMatchers.isMethod; import static net.bytebuddy.matcher.ElementMatchers.isPublic; import static net.bytebuddy.matcher.ElementMatchers.takesArgument; +import static net.bytebuddy.matcher.ElementMatchers.takesArguments; import com.google.auto.service.AutoService; import datadog.trace.agent.tooling.Instrumenter; import datadog.trace.agent.tooling.InstrumenterModule; import datadog.trace.agent.tooling.muzzle.Reference; +import java.util.Collections; +import java.util.Map; @AutoService(InstrumenterModule.class) public class RouteHandlerInstrumentation extends InstrumenterModule.Tracing @@ -28,6 +31,12 @@ public String instrumentedType() { return "io.vertx.ext.web.impl.RouteImpl"; } + /** Declared path of each route, as the app wrote it (with its trailing {@code *}). */ + @Override + public Map contextStore() { + return Collections.singletonMap("io.vertx.ext.web.Route", String.class.getName()); + } + @Override public void methodAdvice(MethodTransformer transformer) { transformer.applyAdvice( @@ -36,5 +45,14 @@ public void methodAdvice(MethodTransformer transformer) { .and(isPublic()) .and(takesArgument(0, named("io.vertx.core.Handler"))), packageName + ".RouteHandlerWrapperAdvice"); + transformer.applyAdvice( + isMethod().and(named("setPath")).and(takesArguments(1)).and(takesArgument(0, String.class)), + packageName + ".RouteSetPathAdvice"); + transformer.applyAdvice( + isMethod() + .and(named("setRegex")) + .and(takesArguments(1)) + .and(takesArgument(0, String.class)), + packageName + ".RouteSetRegexAdvice"); } } diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerWrapper.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerWrapper.java index 28e79e35a27..a489982ae4a 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerWrapper.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerWrapper.java @@ -9,13 +9,21 @@ import datadog.appsec.api.blocking.BlockingException; import datadog.context.ContextScope; +import datadog.trace.api.appsec.route.NormalizedRouteHelper; +import datadog.trace.api.appsec.route.VertxNormalizedRoute; +import datadog.trace.bootstrap.ContextStore; import datadog.trace.bootstrap.instrumentation.api.AgentSpan; import datadog.trace.bootstrap.instrumentation.api.Tags; import io.vertx.core.Handler; +import io.vertx.ext.web.Route; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.impl.RouteImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class RouteHandlerWrapper implements Handler { + private static final Logger log = LoggerFactory.getLogger(RouteHandlerWrapper.class); + static final String PARENT_SPAN_CONTEXT_KEY = AgentSpan.class.getName() + ".parent"; static final String HANDLER_SPAN_CONTEXT_KEY = AgentSpan.class.getName() + ".handler"; static final String ROUTE_CONTEXT_KEY = "dd." + Tags.HTTP_ROUTE; @@ -23,8 +31,13 @@ public class RouteHandlerWrapper implements Handler { private final Handler actual; private final boolean spanStarter; - public RouteHandlerWrapper(final Handler handler) { + /** Declared path of each route, null when the instrumentation could not provide it. */ + private final ContextStore declaredPaths; + + public RouteHandlerWrapper( + final Handler handler, final ContextStore declaredPaths) { actual = handler; + this.declaredPaths = declaredPaths; // When mounting a sub router, the handler is a method reference to the routers handleContext // method this skips that. This prevents routers from creating a span during handling. In the // event a route is not found, without this code, a span would be created for the router when @@ -114,6 +127,25 @@ private void setRoute(RoutingContext routingContext) { if (method != null && path != null && shouldUpdateRoute(routingContext, parentSpan, path)) { routingContext.put(ROUTE_CONTEXT_KEY, path); HTTP_RESOURCE_DECORATOR.withRoute(parentSpan, method, path, true); + if (NormalizedRouteHelper.isEnabled()) { + tagNormalizedRoute(routingContext, parentSpan); + } + } + } + + private void tagNormalizedRoute(final RoutingContext routingContext, final AgentSpan span) { + try { + final String declared = + declaredPaths != null ? declaredPaths.get(routingContext.currentRoute()) : null; + VertxNormalizedRoute.tag( + span, + declared, + VertxNormalizedRoute.vertx4Grammar(), + routingContext.mountPoint(), + routingContext.normalizedPath(), + routingContext.pathParams()); + } catch (Throwable t) { + log.debug("Failed to collect the Vert.x normalized route", t); } } diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerWrapperAdvice.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerWrapperAdvice.java index fd45f5d59b7..adf5adde7e6 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerWrapperAdvice.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerWrapperAdvice.java @@ -1,6 +1,8 @@ package datadog.trace.instrumentation.vertx_4_0.server; +import datadog.trace.bootstrap.InstrumentationContext; import io.vertx.core.Handler; +import io.vertx.ext.web.Route; import io.vertx.ext.web.RoutingContext; import net.bytebuddy.asm.Advice; @@ -8,6 +10,7 @@ public class RouteHandlerWrapperAdvice { @Advice.OnMethodEnter(suppress = Throwable.class) public static void wrapHandler( @Advice.Argument(value = 0, readOnly = false) Handler handler) { - handler = new RouteHandlerWrapper(handler); + handler = + new RouteHandlerWrapper(handler, InstrumentationContext.get(Route.class, String.class)); } } diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteSetPathAdvice.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteSetPathAdvice.java new file mode 100644 index 00000000000..d7678b8ef1b --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteSetPathAdvice.java @@ -0,0 +1,21 @@ +package datadog.trace.instrumentation.vertx_4_0.server; + +import datadog.trace.bootstrap.InstrumentationContext; +import io.vertx.ext.web.Route; +import net.bytebuddy.asm.Advice; + +/** + * Keeps the path of {@code RouteImpl.setPath(String)} as declared: {@code Route.getPath()} drops + * the trailing {@code *}, so a catch-all route would look like an exact one. + */ +public class RouteSetPathAdvice { + @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class) + public static void onExit( + @Advice.This final Route route, + @Advice.Argument(0) final String path, + @Advice.Thrown final Throwable thrown) { + if (thrown == null) { + InstrumentationContext.get(Route.class, String.class).put(route, path); + } + } +} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteSetRegexAdvice.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteSetRegexAdvice.java new file mode 100644 index 00000000000..0c018736818 --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteSetRegexAdvice.java @@ -0,0 +1,13 @@ +package datadog.trace.instrumentation.vertx_4_0.server; + +import datadog.trace.bootstrap.InstrumentationContext; +import io.vertx.ext.web.Route; +import net.bytebuddy.asm.Advice; + +/** A regex route has no declared path: drops any path stored by an earlier {@code path(..)}. */ +public class RouteSetRegexAdvice { + @Advice.OnMethodExit(suppress = Throwable.class) + public static void onExit(@Advice.This final Route route) { + InstrumentationContext.get(Route.class, String.class).remove(route); + } +} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java new file mode 100644 index 00000000000..cccd95728da --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java @@ -0,0 +1,144 @@ +package server.normalizedroute; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; + +import datadog.trace.agent.test.AbstractInstrumentationTest; +import datadog.trace.agent.test.utils.OkHttpUtils; +import datadog.trace.bootstrap.ActiveSubsystems; +import datadog.trace.core.DDSpan; +import io.vertx.core.Future; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpServer; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; +import java.net.ServerSocket; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestInstance; + +/** + * Runs a Vert.x 4.x or 5.x server with the normalized route test routes, with AppSec forced active + * like the Spock {@code InstrumentationSpecification}, and returns the tags of the server span. + * Only APIs shared by Vert.x 4.0.0 and 5.x are used, so the same source runs on every version. + */ +@TestInstance(PER_CLASS) +abstract class AbstractVertxNormalizedRouteTest extends AbstractInstrumentationTest { + + private final OkHttpClient client = OkHttpUtils.client(); + private Vertx vertx; + private HttpServer server; + private int port; + private boolean appSecActiveBefore; + + @BeforeAll + void startServer() throws Exception { + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); + } + vertx = Vertx.vertx(); + Router router = Router.router(vertx); + router.route("/").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/multi/:id.:format").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/three/:a-:b-:c").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/static-text/user-:id").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/catch-all/*").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/encoded/caf%C3%A9").handler(AbstractVertxNormalizedRouteTest::ok); + router.routeWithRegex("/regex/(\\d+)").handler(AbstractVertxNormalizedRouteTest::ok); + // middleware with a declared path, then a regex route: the regex route must not keep its tag + router.route("/stale/*").handler(RoutingContext::next); + router.routeWithRegex("/stale/(\\d+)").handler(AbstractVertxNormalizedRouteTest::ok); + + // what mountSubRouter("/sub/", sub) does on 4.x (mountSubRouter is gone in 5.x) + Router sub = Router.router(vertx); + sub.route("/users/:id").handler(AbstractVertxNormalizedRouteTest::ok); + sub.route("/files/*").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/sub/*").subRouter(sub); + + // a mount with a parameter: the mount point is the concrete matched prefix + Router tenant = Router.router(vertx); + tenant.route("/items/:id").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/:tenant/api/*").subRouter(tenant); + + server = await(vertx.createHttpServer().requestHandler(router).listen(port)); + } + + @AfterAll + void stopServer() throws Exception { + if (server != null) { + await(server.close()); + } + if (vertx != null) { + await(vertx.close()); + } + } + + @BeforeEach + void forceAppSecActive() { + appSecActiveBefore = ActiveSubsystems.APPSEC_ACTIVE; + ActiveSubsystems.APPSEC_ACTIVE = true; + } + + @AfterEach + void restoreAppSecActive() { + ActiveSubsystems.APPSEC_ACTIVE = appSecActiveBefore; + } + + private static void ok(RoutingContext ctx) { + ctx.response().setStatusCode(200).end("ok"); + } + + private static T await(Future future) throws Exception { + CountDownLatch done = new CountDownLatch(1); + AtomicReference result = new AtomicReference<>(); + AtomicReference failure = new AtomicReference<>(); + future.onComplete(ar -> { + if (ar.succeeded()) { + result.set(ar.result()); + } else { + failure.set(ar.cause()); + } + done.countDown(); + }); + if (!done.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Vert.x operation did not complete in time"); + } + if (failure.get() != null) { + throw new RuntimeException("Vert.x operation failed", failure.get()); + } + return result.get(); + } + + /** Sends {@code GET path} and returns the HTTP status. */ + int get(String path) throws Exception { + Request request = new Request.Builder().url("http://localhost:" + port + path).get().build(); + try (Response response = client.newCall(request).execute()) { + return response.code(); + } + } + + /** Tags of the {@code netty.request} span of the single trace written. */ + Map serverSpanTags() throws Exception { + writer.waitForTraces(1); + DDSpan serverSpan = null; + for (List trace : writer) { + for (DDSpan span : trace) { + if ("netty.request".equals(span.getOperationName().toString())) { + serverSpan = span; + } + } + } + assertNotNull(serverSpan, "netty.request span"); + return serverSpan.getTags(); + } +} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java new file mode 100644 index 00000000000..a8825bac467 --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java @@ -0,0 +1,25 @@ +package server.normalizedroute; + +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import datadog.trace.api.config.AppSecConfig; +import datadog.trace.test.junit.utils.config.WithConfig; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** With API Security disabled the normalized route is not set; {@code http.route} still is. */ +@WithConfig(key = AppSecConfig.API_SECURITY_ENABLED, value = "false") +class VertxNormalizedRouteApiSecurityDisabledForkedTest extends AbstractVertxNormalizedRouteTest { + + @Test + void noNormalizedRouteWhenApiSecurityIsDisabled() throws Exception { + assertEquals(200, get("/multi/1.json")); + Map tags = serverSpanTags(); + + assertEquals("/multi/:id.:format", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } +} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java new file mode 100644 index 00000000000..9d4f84fb2c6 --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java @@ -0,0 +1,116 @@ +package server.normalizedroute; + +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import datadog.trace.bootstrap.ActiveSubsystems; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.tabletest.junit.TableTest; + +/** Normalized route of Vert.x 4.x and 5.x routes, top level and under the {@code /sub} mount. */ +class VertxNormalizedRouteTest extends AbstractVertxNormalizedRouteTest { + + @TableTest({ + "Scenario | Request | Route | Normalized ", + "root | '/' | '/' | '/' ", + "two params in a segment | '/multi/1.json' | '/multi/:id.:format' | '/multi/{id}.{format}' ", + "three params in a segment | '/three/1-2-3' | '/three/:a-:b-:c' | '/three/{a}-{b}-{c}' ", + "static text before a param | '/static-text/user-1' | '/static-text/user-:id' | '/static-text/user-{id}'", + "catch-all present | '/catch-all/a/b/c.txt' | '/catch-all/' | '/catch-all/{param1}' ", + "catch-all matched a slash | '/catch-all/' | '/catch-all/' | '/catch-all/' ", + "catch-all after a collapsed slash | '/catch-all//' | '/catch-all/' | '/catch-all/' ", + "encoded literal | '/encoded/caf%C3%A9' | '/encoded/café' | '/encoded/caf%C3%A9' ", + "sub-router param | '/sub/users/1' | '/sub/users/:id' | '/sub/users/{id}' ", + "sub-router catch-all | '/sub/files/a' | '/sub/files/' | '/sub/files/{param1}' " + }) + void normalizedRoute(String request, String route, String normalized) throws Exception { + assertEquals(200, get(request)); + Map tags = serverSpanTags(); + + assertEquals(route, String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals(normalized, String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } + + /** + * The store holds the declared {@code /catch-all/*}: {@code getPath()} drops the trailing {@code + * *} (http.route {@code /catch-all/}), so only the declared path gives {@code {param1}}. + */ + @Test + void storeKeepsTheTrailingStarOfTheDeclaredPath() throws Exception { + assertEquals(200, get("/catch-all/x")); + Map tags = serverSpanTags(); + + assertEquals("/catch-all/", String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals("/catch-all/{param1}", String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } + + /** {@code http.route} falls back to the regex of the route; a regex has no normalized route. */ + @Test + void noNormalizedRouteForRegexRoute() throws Exception { + assertEquals(200, get("/regex/123")); + Map tags = serverSpanTags(); + + assertEquals("/regex/(\\d+)", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + /** + * The {@code /stale/*} middleware tags the span first; the regex route then updates {@code + * http.route} with its regex and must clear the normalized route of the middleware. + */ + @Test + void staleNormalizedRouteIsClearedByLaterRegexRoute() throws Exception { + assertEquals(200, get("/stale/1")); + Map tags = serverSpanTags(); + + assertEquals("/stale/(\\d+)", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + /** + * Under {@code route("/:tenant/api/*").subRouter(..)} the mount point is the concrete prefix + * ({@code /acme/api/}), which holds a request value: no normalized route, {@code http.route} + * unchanged. + */ + @Test + void noNormalizedRouteUnderAParameterMount() throws Exception { + assertEquals(200, get("/acme/api/items/1")); + Map tags = serverSpanTags(); + + assertEquals("/acme/api/items/:id", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + @Test + void noNormalizedRouteWhenAppSecIsInactive() throws Exception { + ActiveSubsystems.APPSEC_ACTIVE = false; + + assertEquals(200, get("/multi/1.json")); + Map tags = serverSpanTags(); + + assertEquals("/multi/:id.:format", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + /** + * {@code /catch-all} for {@code /catch-all/*}: Vert.x 4.0.3+ matches it (catch-all removed), + * 4.0.0 to 4.0.2 do not (404, no route handler, no tag). + */ + @Test + void catchAllWithoutTrailingSlash() throws Exception { + int status = get("/catch-all"); + Map tags = serverSpanTags(); + + if (status == 200) { + assertEquals("/catch-all/", String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals("/catch-all", String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } else { + assertEquals(404, status); + assertNull(tags.get(HTTP_ROUTE)); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + } +} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java new file mode 100644 index 00000000000..cccd95728da --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java @@ -0,0 +1,144 @@ +package server.normalizedroute; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; + +import datadog.trace.agent.test.AbstractInstrumentationTest; +import datadog.trace.agent.test.utils.OkHttpUtils; +import datadog.trace.bootstrap.ActiveSubsystems; +import datadog.trace.core.DDSpan; +import io.vertx.core.Future; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpServer; +import io.vertx.ext.web.Router; +import io.vertx.ext.web.RoutingContext; +import java.net.ServerSocket; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestInstance; + +/** + * Runs a Vert.x 4.x or 5.x server with the normalized route test routes, with AppSec forced active + * like the Spock {@code InstrumentationSpecification}, and returns the tags of the server span. + * Only APIs shared by Vert.x 4.0.0 and 5.x are used, so the same source runs on every version. + */ +@TestInstance(PER_CLASS) +abstract class AbstractVertxNormalizedRouteTest extends AbstractInstrumentationTest { + + private final OkHttpClient client = OkHttpUtils.client(); + private Vertx vertx; + private HttpServer server; + private int port; + private boolean appSecActiveBefore; + + @BeforeAll + void startServer() throws Exception { + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); + } + vertx = Vertx.vertx(); + Router router = Router.router(vertx); + router.route("/").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/multi/:id.:format").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/three/:a-:b-:c").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/static-text/user-:id").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/catch-all/*").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/encoded/caf%C3%A9").handler(AbstractVertxNormalizedRouteTest::ok); + router.routeWithRegex("/regex/(\\d+)").handler(AbstractVertxNormalizedRouteTest::ok); + // middleware with a declared path, then a regex route: the regex route must not keep its tag + router.route("/stale/*").handler(RoutingContext::next); + router.routeWithRegex("/stale/(\\d+)").handler(AbstractVertxNormalizedRouteTest::ok); + + // what mountSubRouter("/sub/", sub) does on 4.x (mountSubRouter is gone in 5.x) + Router sub = Router.router(vertx); + sub.route("/users/:id").handler(AbstractVertxNormalizedRouteTest::ok); + sub.route("/files/*").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/sub/*").subRouter(sub); + + // a mount with a parameter: the mount point is the concrete matched prefix + Router tenant = Router.router(vertx); + tenant.route("/items/:id").handler(AbstractVertxNormalizedRouteTest::ok); + router.route("/:tenant/api/*").subRouter(tenant); + + server = await(vertx.createHttpServer().requestHandler(router).listen(port)); + } + + @AfterAll + void stopServer() throws Exception { + if (server != null) { + await(server.close()); + } + if (vertx != null) { + await(vertx.close()); + } + } + + @BeforeEach + void forceAppSecActive() { + appSecActiveBefore = ActiveSubsystems.APPSEC_ACTIVE; + ActiveSubsystems.APPSEC_ACTIVE = true; + } + + @AfterEach + void restoreAppSecActive() { + ActiveSubsystems.APPSEC_ACTIVE = appSecActiveBefore; + } + + private static void ok(RoutingContext ctx) { + ctx.response().setStatusCode(200).end("ok"); + } + + private static T await(Future future) throws Exception { + CountDownLatch done = new CountDownLatch(1); + AtomicReference result = new AtomicReference<>(); + AtomicReference failure = new AtomicReference<>(); + future.onComplete(ar -> { + if (ar.succeeded()) { + result.set(ar.result()); + } else { + failure.set(ar.cause()); + } + done.countDown(); + }); + if (!done.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Vert.x operation did not complete in time"); + } + if (failure.get() != null) { + throw new RuntimeException("Vert.x operation failed", failure.get()); + } + return result.get(); + } + + /** Sends {@code GET path} and returns the HTTP status. */ + int get(String path) throws Exception { + Request request = new Request.Builder().url("http://localhost:" + port + path).get().build(); + try (Response response = client.newCall(request).execute()) { + return response.code(); + } + } + + /** Tags of the {@code netty.request} span of the single trace written. */ + Map serverSpanTags() throws Exception { + writer.waitForTraces(1); + DDSpan serverSpan = null; + for (List trace : writer) { + for (DDSpan span : trace) { + if ("netty.request".equals(span.getOperationName().toString())) { + serverSpan = span; + } + } + } + assertNotNull(serverSpan, "netty.request span"); + return serverSpan.getTags(); + } +} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java new file mode 100644 index 00000000000..a8825bac467 --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java @@ -0,0 +1,25 @@ +package server.normalizedroute; + +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import datadog.trace.api.config.AppSecConfig; +import datadog.trace.test.junit.utils.config.WithConfig; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** With API Security disabled the normalized route is not set; {@code http.route} still is. */ +@WithConfig(key = AppSecConfig.API_SECURITY_ENABLED, value = "false") +class VertxNormalizedRouteApiSecurityDisabledForkedTest extends AbstractVertxNormalizedRouteTest { + + @Test + void noNormalizedRouteWhenApiSecurityIsDisabled() throws Exception { + assertEquals(200, get("/multi/1.json")); + Map tags = serverSpanTags(); + + assertEquals("/multi/:id.:format", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } +} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java new file mode 100644 index 00000000000..9d4f84fb2c6 --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java @@ -0,0 +1,116 @@ +package server.normalizedroute; + +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import datadog.trace.bootstrap.ActiveSubsystems; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.tabletest.junit.TableTest; + +/** Normalized route of Vert.x 4.x and 5.x routes, top level and under the {@code /sub} mount. */ +class VertxNormalizedRouteTest extends AbstractVertxNormalizedRouteTest { + + @TableTest({ + "Scenario | Request | Route | Normalized ", + "root | '/' | '/' | '/' ", + "two params in a segment | '/multi/1.json' | '/multi/:id.:format' | '/multi/{id}.{format}' ", + "three params in a segment | '/three/1-2-3' | '/three/:a-:b-:c' | '/three/{a}-{b}-{c}' ", + "static text before a param | '/static-text/user-1' | '/static-text/user-:id' | '/static-text/user-{id}'", + "catch-all present | '/catch-all/a/b/c.txt' | '/catch-all/' | '/catch-all/{param1}' ", + "catch-all matched a slash | '/catch-all/' | '/catch-all/' | '/catch-all/' ", + "catch-all after a collapsed slash | '/catch-all//' | '/catch-all/' | '/catch-all/' ", + "encoded literal | '/encoded/caf%C3%A9' | '/encoded/café' | '/encoded/caf%C3%A9' ", + "sub-router param | '/sub/users/1' | '/sub/users/:id' | '/sub/users/{id}' ", + "sub-router catch-all | '/sub/files/a' | '/sub/files/' | '/sub/files/{param1}' " + }) + void normalizedRoute(String request, String route, String normalized) throws Exception { + assertEquals(200, get(request)); + Map tags = serverSpanTags(); + + assertEquals(route, String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals(normalized, String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } + + /** + * The store holds the declared {@code /catch-all/*}: {@code getPath()} drops the trailing {@code + * *} (http.route {@code /catch-all/}), so only the declared path gives {@code {param1}}. + */ + @Test + void storeKeepsTheTrailingStarOfTheDeclaredPath() throws Exception { + assertEquals(200, get("/catch-all/x")); + Map tags = serverSpanTags(); + + assertEquals("/catch-all/", String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals("/catch-all/{param1}", String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } + + /** {@code http.route} falls back to the regex of the route; a regex has no normalized route. */ + @Test + void noNormalizedRouteForRegexRoute() throws Exception { + assertEquals(200, get("/regex/123")); + Map tags = serverSpanTags(); + + assertEquals("/regex/(\\d+)", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + /** + * The {@code /stale/*} middleware tags the span first; the regex route then updates {@code + * http.route} with its regex and must clear the normalized route of the middleware. + */ + @Test + void staleNormalizedRouteIsClearedByLaterRegexRoute() throws Exception { + assertEquals(200, get("/stale/1")); + Map tags = serverSpanTags(); + + assertEquals("/stale/(\\d+)", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + /** + * Under {@code route("/:tenant/api/*").subRouter(..)} the mount point is the concrete prefix + * ({@code /acme/api/}), which holds a request value: no normalized route, {@code http.route} + * unchanged. + */ + @Test + void noNormalizedRouteUnderAParameterMount() throws Exception { + assertEquals(200, get("/acme/api/items/1")); + Map tags = serverSpanTags(); + + assertEquals("/acme/api/items/:id", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + @Test + void noNormalizedRouteWhenAppSecIsInactive() throws Exception { + ActiveSubsystems.APPSEC_ACTIVE = false; + + assertEquals(200, get("/multi/1.json")); + Map tags = serverSpanTags(); + + assertEquals("/multi/:id.:format", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + /** + * {@code /catch-all} for {@code /catch-all/*}: Vert.x 4.0.3+ matches it (catch-all removed), + * 4.0.0 to 4.0.2 do not (404, no route handler, no tag). + */ + @Test + void catchAllWithoutTrailingSlash() throws Exception { + int status = get("/catch-all"); + Map tags = serverSpanTags(); + + if (status == 200) { + assertEquals("/catch-all/", String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals("/catch-all", String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } else { + assertEquals(404, status); + assertNull(tags.get(HTTP_ROUTE)); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + } +} From 7ff062e8b609e22940fd9a1faef70fa445538944 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20Gonz=C3=A1lez=20Garc=C3=ADa?= Date: Thu, 26 Nov 2026 16:27:06 +0100 Subject: [PATCH 5/9] Expect the normalized route in the Vert.x server test suites --- .../src/test/groovy/server/VertxHttpServerForkedTest.groovy | 6 ++++++ .../groovy/server/VertxHttpServerForkedTest.groovy | 6 ++++++ .../src/test/groovy/server/VertxHttpServerForkedTest.groovy | 6 ++++++ .../src/test/groovy/server/VertxHttpServerForkedTest.groovy | 6 ++++++ 4 files changed, 24 insertions(+) diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/groovy/server/VertxHttpServerForkedTest.groovy b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/groovy/server/VertxHttpServerForkedTest.groovy index 1e821c066ce..57cefba5d6f 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/groovy/server/VertxHttpServerForkedTest.groovy +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/groovy/server/VertxHttpServerForkedTest.groovy @@ -201,6 +201,12 @@ class VertxHttpServerForkedTest extends HttpServerTest { } } + @Override + Serializable expectedNormalizedRoute(ServerEndpoint endpoint) { + def route = endpoint == PATH_PARAM ? routerBasePath() + "path/{id}/param" : expectedServerSpanRoute(endpoint) + normalizedRouteOf('', route) + } + @Override void handlerSpan(TraceAssert trace, ServerEndpoint endpoint = SUCCESS) { if (endpoint == NOT_FOUND) { diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/groovy/server/VertxHttpServerForkedTest.groovy b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/groovy/server/VertxHttpServerForkedTest.groovy index f08e9dd7fd2..33f2160d85d 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/groovy/server/VertxHttpServerForkedTest.groovy +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/groovy/server/VertxHttpServerForkedTest.groovy @@ -195,6 +195,12 @@ class VertxHttpServerForkedTest extends HttpServerTest { } } + @Override + Serializable expectedNormalizedRoute(ServerEndpoint endpoint) { + def route = endpoint == PATH_PARAM ? routerBasePath() + "path/{id}/param" : expectedServerSpanRoute(endpoint) + normalizedRouteOf('', route) + } + @Override void handlerSpan(TraceAssert trace, ServerEndpoint endpoint = SUCCESS) { if (endpoint == NOT_FOUND) { diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/groovy/server/VertxHttpServerForkedTest.groovy b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/groovy/server/VertxHttpServerForkedTest.groovy index 4e4c815a5c1..16c85c29969 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/groovy/server/VertxHttpServerForkedTest.groovy +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/groovy/server/VertxHttpServerForkedTest.groovy @@ -215,6 +215,12 @@ class VertxHttpServerForkedTest extends HttpServerTest { } } + @Override + Serializable expectedNormalizedRoute(ServerEndpoint endpoint) { + def route = endpoint == PATH_PARAM ? routerBasePath() + "path/{id}/param" : expectedServerSpanRoute(endpoint) + normalizedRouteOf('', route) + } + @Override void handlerSpan(TraceAssert trace, ServerEndpoint endpoint = SUCCESS) { if (endpoint == NOT_FOUND) { diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/groovy/server/VertxHttpServerForkedTest.groovy b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/groovy/server/VertxHttpServerForkedTest.groovy index 3b784751929..05654e04f33 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/groovy/server/VertxHttpServerForkedTest.groovy +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/groovy/server/VertxHttpServerForkedTest.groovy @@ -207,6 +207,12 @@ class VertxHttpServerForkedTest extends HttpServerTest { } } + @Override + Serializable expectedNormalizedRoute(ServerEndpoint endpoint) { + def route = endpoint == PATH_PARAM ? routerBasePath() + "path/{id}/param" : expectedServerSpanRoute(endpoint) + normalizedRouteOf('', route) + } + @Override void handlerSpan(TraceAssert trace, ServerEndpoint endpoint = SUCCESS) { if (endpoint == NOT_FOUND) { From 835983f89cb06b64595d6955456bacf5d714c058 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20Gonz=C3=A1lez=20Garc=C3=ADa?= Date: Fri, 27 Nov 2026 09:33:37 +0100 Subject: [PATCH 6/9] Simplify the Vert.x normalized route code and tests --- .../server/RouteHandlerInstrumentation.java | 7 +- .../vertx_3_4/server/RouteHandlerWrapper.java | 5 +- .../AbstractVertxNormalizedRouteTest.java | 106 +++++++++---- ...zedRouteApiSecurityDisabledForkedTest.java | 12 +- .../VertxNormalizedRouteTest.java | 50 +++--- .../vertx-web/vertx-web-4.0/build.gradle | 5 + ...zedRouteApiSecurityDisabledForkedTest.java | 25 --- .../VertxNormalizedRouteTest.java | 116 -------------- .../server/RouteHandlerInstrumentation.java | 7 +- .../vertx_4_0/server/RouteHandlerWrapper.java | 5 +- .../AbstractVertxNormalizedRouteTest.java | 144 ------------------ ...zedRouteApiSecurityDisabledForkedTest.java | 25 --- .../AbstractVertxNormalizedRouteTest.java | 39 +++-- ...zedRouteApiSecurityDisabledForkedTest.java | 15 ++ .../VertxNormalizedRouteTest.java | 45 ++---- .../AbstractVertxNormalizedRouteTest.java | 39 +++-- ...zedRouteApiSecurityDisabledForkedTest.java | 12 +- .../VertxNormalizedRouteTest.java | 45 ++---- .../appsec/route/VertxNormalizedRoute.java | 94 ++++++++---- .../api/appsec/route/VertxRouteParser.java | 86 +++++++---- .../route/VertxNormalizedRouteForkedTest.java | 54 ++----- .../route/VertxNormalizedRouteTest.java | 30 ++-- .../route/VertxRouteParserCacheTest.java | 5 + 23 files changed, 362 insertions(+), 609 deletions(-) delete mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java delete mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/VertxNormalizedRouteTest.java delete mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java delete mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java rename dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/{latestDepTest => testNormalizedRoute}/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java (78%) create mode 100644 dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java rename dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/{test => testNormalizedRoute}/java/server/normalizedroute/VertxNormalizedRouteTest.java (68%) diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerInstrumentation.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerInstrumentation.java index b90d195e0a5..dd247c46f63 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerInstrumentation.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerInstrumentation.java @@ -40,13 +40,10 @@ public void methodAdvice(MethodTransformer transformer) { .and(takesArgument(0, named("io.vertx.core.Handler"))), packageName + ".RouteHandlerWrapperAdvice"); transformer.applyAdvice( - isMethod().and(named("setPath")).and(takesArguments(1)).and(takesArgument(0, String.class)), + isMethod().and(named("setPath")).and(takesArguments(String.class)), packageName + ".RouteSetPathAdvice"); transformer.applyAdvice( - isMethod() - .and(named("setRegex")) - .and(takesArguments(1)) - .and(takesArgument(0, String.class)), + isMethod().and(named("setRegex")).and(takesArguments(String.class)), packageName + ".RouteSetRegexAdvice"); } } diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerWrapper.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerWrapper.java index 4e6ba9479c4..657d98e7cc0 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerWrapper.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerWrapper.java @@ -32,7 +32,7 @@ public class RouteHandlerWrapper implements Handler { private final Handler actual; private final boolean spanStarter; - /** Declared path of each route, null when the instrumentation could not provide it. */ + /** Declared path of each route. */ private final ContextStore declaredPaths; public RouteHandlerWrapper( @@ -128,8 +128,7 @@ private void setRoute(RoutingContext routingContext) { private void tagNormalizedRoute(final RoutingContext routingContext, final AgentSpan span) { try { - final String declared = - declaredPaths != null ? declaredPaths.get(routingContext.currentRoute()) : null; + final String declared = declaredPaths.get(routingContext.currentRoute()); VertxNormalizedRoute.tag( span, declared, diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java index 45765ca137b..d3e5d6f6813 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java @@ -1,21 +1,29 @@ package server.normalizedroute; +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; import datadog.trace.agent.test.AbstractInstrumentationTest; import datadog.trace.agent.test.utils.OkHttpUtils; import datadog.trace.bootstrap.ActiveSubsystems; import datadog.trace.core.DDSpan; +import io.vertx.core.AsyncResult; +import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServer; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; -import java.net.ServerSocket; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; @@ -32,17 +40,20 @@ @TestInstance(PER_CLASS) abstract class AbstractVertxNormalizedRouteTest extends AbstractInstrumentationTest { + private static final long TIMEOUT_SECONDS = 10; + + /** Operation name of the server span, which carries both route tags. */ + private static final String SERVER_SPAN = "netty.request"; + private final OkHttpClient client = OkHttpUtils.client(); private Vertx vertx; private HttpServer server; private int port; private boolean appSecActiveBefore; + private boolean paramMountSupported; @BeforeAll void startServer() throws Exception { - try (ServerSocket socket = new ServerSocket(0)) { - port = socket.getLocalPort(); - } vertx = Vertx.vertx(); Router router = Router.router(vertx); router.route("/").handler(AbstractVertxNormalizedRouteTest::ok); @@ -67,35 +78,30 @@ void startServer() throws Exception { sub.route("/files/*").handler(AbstractVertxNormalizedRouteTest::ok); router.mountSubRouter("/sub", sub); - CountDownLatch ready = new CountDownLatch(1); - server = - vertx - .createHttpServer() - .requestHandler(router::accept) - .listen( - port, - result -> { - if (result.failed()) { - throw new RuntimeException("Failed to start Vert.x server", result.cause()); - } - ready.countDown(); - }); - if (!ready.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException("Vert.x server did not start in time"); + // a mount with a parameter (3.8.2+; 3.4 rejects patterns in sub-router mounts): the mount point + // is the concrete matched prefix + Router tenant = Router.router(vertx); + tenant.route("/items/:id").handler(AbstractVertxNormalizedRouteTest::ok); + try { + router.mountSubRouter("/:tenant/api", tenant); + paramMountSupported = true; + } catch (IllegalArgumentException e) { + paramMountSupported = false; } + + server = + await( + handler -> vertx.createHttpServer().requestHandler(router::accept).listen(0, handler)); + port = server.actualPort(); } @AfterAll void stopServer() throws Exception { if (server != null) { - CountDownLatch closed = new CountDownLatch(1); - server.close(ar -> closed.countDown()); - closed.await(10, TimeUnit.SECONDS); + AbstractVertxNormalizedRouteTest.await(server::close); } if (vertx != null) { - CountDownLatch closed = new CountDownLatch(1); - vertx.close(ar -> closed.countDown()); - closed.await(10, TimeUnit.SECONDS); + AbstractVertxNormalizedRouteTest.await(vertx::close); } } @@ -114,6 +120,36 @@ private static void ok(RoutingContext ctx) { ctx.response().setStatusCode(200).end("ok"); } + /** + * Starts the callback-style Vert.x {@code operation} and waits for its result; a failure is + * rethrown on the test thread. + */ + private static T await(Consumer>> operation) throws Exception { + CountDownLatch done = new CountDownLatch(1); + AtomicReference result = new AtomicReference<>(); + AtomicReference failure = new AtomicReference<>(); + operation.accept(ar -> { + if (ar.succeeded()) { + result.set(ar.result()); + } else { + failure.set(ar.cause()); + } + done.countDown(); + }); + if (!done.await(TIMEOUT_SECONDS, SECONDS)) { + throw new IllegalStateException("Vert.x operation did not complete in time"); + } + if (failure.get() != null) { + throw new RuntimeException("Vert.x operation failed", failure.get()); + } + return result.get(); + } + + /** Whether this Vert.x version accepted the {@code /:tenant/api} sub-router mount. */ + boolean paramMountSupported() { + return paramMountSupported; + } + /** Sends {@code GET path} and returns the HTTP status. */ int get(String path) throws Exception { Request request = new Request.Builder().url("http://localhost:" + port + path).get().build(); @@ -122,18 +158,30 @@ int get(String path) throws Exception { } } - /** Tags of the {@code netty.request} span of the single trace written. */ + /** Tags of the {@link #SERVER_SPAN} span of the single trace written. */ Map serverSpanTags() throws Exception { writer.waitForTraces(1); DDSpan serverSpan = null; for (List trace : writer) { for (DDSpan span : trace) { - if ("netty.request".equals(span.getOperationName().toString())) { + if (SERVER_SPAN.equals(span.getOperationName().toString())) { serverSpan = span; } } } - assertNotNull(serverSpan, "netty.request span"); + assertNotNull(serverSpan, SERVER_SPAN + " span"); return serverSpan.getTags(); } + + /** + * Sends {@code GET request}, expects a 200 with {@code expectedHttpRoute} (null for none) as + * {@code http.route} and no normalized route. + */ + void assertNoNormalizedRoute(String request, String expectedHttpRoute) throws Exception { + assertEquals(200, get(request)); + Map tags = serverSpanTags(); + + assertEquals(expectedHttpRoute, Objects.toString(tags.get(HTTP_ROUTE), null)); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } } diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java index a8825bac467..0cdebbd2602 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java @@ -1,13 +1,7 @@ package server.normalizedroute; -import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; -import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - import datadog.trace.api.config.AppSecConfig; import datadog.trace.test.junit.utils.config.WithConfig; -import java.util.Map; import org.junit.jupiter.api.Test; /** With API Security disabled the normalized route is not set; {@code http.route} still is. */ @@ -16,10 +10,6 @@ class VertxNormalizedRouteApiSecurityDisabledForkedTest extends AbstractVertxNor @Test void noNormalizedRouteWhenApiSecurityIsDisabled() throws Exception { - assertEquals(200, get("/multi/1.json")); - Map tags = serverSpanTags(); - - assertEquals("/multi/:id.:format", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + assertNoNormalizedRoute("/multi/1.json", "/multi/:id.:format"); } } diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java index 69a893c60c9..48381708d30 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java @@ -4,6 +4,7 @@ import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import datadog.trace.bootstrap.ActiveSubsystems; import java.util.Map; @@ -14,11 +15,13 @@ class VertxNormalizedRouteTest extends AbstractVertxNormalizedRouteTest { @TableTest({ - "Scenario | Request | Route | Normalized ", + "Scenario | Request | HttpRoute | Normalized ", "root | '/' | '/' | '/' ", "two params in a segment | '/multi/1.json' | '/multi/:id.:format' | '/multi/{id}.{format}' ", "three params in a segment | '/three/1-2-3' | '/three/:a-:b-:c' | '/three/{a}-{b}-{c}' ", "static text before a param | '/static-text/user-1' | '/static-text/user-:id' | '/static-text/user-{id}'", + // getPath() drops the trailing '*' (http.route '/catch-all/'), so '{param1}' proves the + // declared '/catch-all/*' was captured from setPath "catch-all present | '/catch-all/a/b/c.txt' | '/catch-all/' | '/catch-all/{param1}' ", "catch-all matched a slash | '/catch-all/' | '/catch-all/' | '/catch-all/' ", "catch-all after a collapsed slash | '/catch-all//' | '/catch-all/' | '/catch-all/' ", @@ -26,55 +29,42 @@ class VertxNormalizedRouteTest extends AbstractVertxNormalizedRouteTest { "sub-router param | '/sub/users/1' | '/sub/users/:id' | '/sub/users/{id}' ", "sub-router catch-all | '/sub/files/a' | '/sub/files/' | '/sub/files/{param1}' " }) - void normalizedRoute(String request, String route, String normalized) throws Exception { + void normalizedRoute(String request, String httpRoute, String normalized) throws Exception { assertEquals(200, get(request)); Map tags = serverSpanTags(); - assertEquals(route, String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals(httpRoute, String.valueOf(tags.get(HTTP_ROUTE))); assertEquals(normalized, String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); } - /** - * The store holds the declared {@code /catch-all/*}: {@code getPath()} drops the trailing {@code - * *} (http.route {@code /catch-all/}), so only the declared path gives {@code {param1}}. - */ - @Test - void storeKeepsTheTrailingStarOfTheDeclaredPath() throws Exception { - assertEquals(200, get("/catch-all/x")); - Map tags = serverSpanTags(); - - assertEquals("/catch-all/", String.valueOf(tags.get(HTTP_ROUTE))); - assertEquals("/catch-all/{param1}", String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); - } - @Test void noNormalizedRouteForRegexRoute() throws Exception { - assertEquals(200, get("/regex/123")); - Map tags = serverSpanTags(); - - assertNull(tags.get(HTTP_ROUTE)); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + assertNoNormalizedRoute("/regex/123", null); } /** The regex route has a path, so it updates {@code http.route} and clears the stale tag. */ @Test void staleNormalizedRouteIsClearedByLaterRegexRoute() throws Exception { - assertEquals(200, get("/stale-path/1")); - Map tags = serverSpanTags(); - - assertEquals("/stale-path/x", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + assertNoNormalizedRoute("/stale-path/1", "/stale-path/x"); } @Test void noNormalizedRouteWhenAppSecIsInactive() throws Exception { ActiveSubsystems.APPSEC_ACTIVE = false; - assertEquals(200, get("/multi/1.json")); - Map tags = serverSpanTags(); + assertNoNormalizedRoute("/multi/1.json", "/multi/:id.:format"); + } + + /** + * Under {@code mountSubRouter("/:tenant/api", ..)} (3.8.2+) the mount point is the concrete + * prefix ({@code /acme/api}), which holds a request value: no normalized route, {@code + * http.route} unchanged. + */ + @Test + void noNormalizedRouteUnderAParameterMount() throws Exception { + assumeTrue(paramMountSupported(), "this Vert.x version rejects patterns in sub-router mounts"); - assertEquals("/multi/:id.:format", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + assertNoNormalizedRoute("/acme/api/items/1", "/acme/api/items/:id"); } /** diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/build.gradle b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/build.gradle index 72f66e0ce3d..2f707682703 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/build.gradle +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/build.gradle @@ -23,6 +23,11 @@ muzzle { addTestSuiteForDir('latestDepTest', 'latestDepTest') +// The normalized route tests use APIs shared by Vert.x 4.0.0 and 4.x latest, so both suites compile them +sourceSets.matching { it.name == 'test' || it.name == 'latestDepTest' }.configureEach { + java.srcDir 'src/testNormalizedRoute/java' +} + configurations { testArtifacts } diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java deleted file mode 100644 index a8825bac467..00000000000 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package server.normalizedroute; - -import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; -import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -import datadog.trace.api.config.AppSecConfig; -import datadog.trace.test.junit.utils.config.WithConfig; -import java.util.Map; -import org.junit.jupiter.api.Test; - -/** With API Security disabled the normalized route is not set; {@code http.route} still is. */ -@WithConfig(key = AppSecConfig.API_SECURITY_ENABLED, value = "false") -class VertxNormalizedRouteApiSecurityDisabledForkedTest extends AbstractVertxNormalizedRouteTest { - - @Test - void noNormalizedRouteWhenApiSecurityIsDisabled() throws Exception { - assertEquals(200, get("/multi/1.json")); - Map tags = serverSpanTags(); - - assertEquals("/multi/:id.:format", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); - } -} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/VertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/VertxNormalizedRouteTest.java deleted file mode 100644 index 9d4f84fb2c6..00000000000 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/VertxNormalizedRouteTest.java +++ /dev/null @@ -1,116 +0,0 @@ -package server.normalizedroute; - -import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; -import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -import datadog.trace.bootstrap.ActiveSubsystems; -import java.util.Map; -import org.junit.jupiter.api.Test; -import org.tabletest.junit.TableTest; - -/** Normalized route of Vert.x 4.x and 5.x routes, top level and under the {@code /sub} mount. */ -class VertxNormalizedRouteTest extends AbstractVertxNormalizedRouteTest { - - @TableTest({ - "Scenario | Request | Route | Normalized ", - "root | '/' | '/' | '/' ", - "two params in a segment | '/multi/1.json' | '/multi/:id.:format' | '/multi/{id}.{format}' ", - "three params in a segment | '/three/1-2-3' | '/three/:a-:b-:c' | '/three/{a}-{b}-{c}' ", - "static text before a param | '/static-text/user-1' | '/static-text/user-:id' | '/static-text/user-{id}'", - "catch-all present | '/catch-all/a/b/c.txt' | '/catch-all/' | '/catch-all/{param1}' ", - "catch-all matched a slash | '/catch-all/' | '/catch-all/' | '/catch-all/' ", - "catch-all after a collapsed slash | '/catch-all//' | '/catch-all/' | '/catch-all/' ", - "encoded literal | '/encoded/caf%C3%A9' | '/encoded/café' | '/encoded/caf%C3%A9' ", - "sub-router param | '/sub/users/1' | '/sub/users/:id' | '/sub/users/{id}' ", - "sub-router catch-all | '/sub/files/a' | '/sub/files/' | '/sub/files/{param1}' " - }) - void normalizedRoute(String request, String route, String normalized) throws Exception { - assertEquals(200, get(request)); - Map tags = serverSpanTags(); - - assertEquals(route, String.valueOf(tags.get(HTTP_ROUTE))); - assertEquals(normalized, String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); - } - - /** - * The store holds the declared {@code /catch-all/*}: {@code getPath()} drops the trailing {@code - * *} (http.route {@code /catch-all/}), so only the declared path gives {@code {param1}}. - */ - @Test - void storeKeepsTheTrailingStarOfTheDeclaredPath() throws Exception { - assertEquals(200, get("/catch-all/x")); - Map tags = serverSpanTags(); - - assertEquals("/catch-all/", String.valueOf(tags.get(HTTP_ROUTE))); - assertEquals("/catch-all/{param1}", String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); - } - - /** {@code http.route} falls back to the regex of the route; a regex has no normalized route. */ - @Test - void noNormalizedRouteForRegexRoute() throws Exception { - assertEquals(200, get("/regex/123")); - Map tags = serverSpanTags(); - - assertEquals("/regex/(\\d+)", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); - } - - /** - * The {@code /stale/*} middleware tags the span first; the regex route then updates {@code - * http.route} with its regex and must clear the normalized route of the middleware. - */ - @Test - void staleNormalizedRouteIsClearedByLaterRegexRoute() throws Exception { - assertEquals(200, get("/stale/1")); - Map tags = serverSpanTags(); - - assertEquals("/stale/(\\d+)", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); - } - - /** - * Under {@code route("/:tenant/api/*").subRouter(..)} the mount point is the concrete prefix - * ({@code /acme/api/}), which holds a request value: no normalized route, {@code http.route} - * unchanged. - */ - @Test - void noNormalizedRouteUnderAParameterMount() throws Exception { - assertEquals(200, get("/acme/api/items/1")); - Map tags = serverSpanTags(); - - assertEquals("/acme/api/items/:id", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); - } - - @Test - void noNormalizedRouteWhenAppSecIsInactive() throws Exception { - ActiveSubsystems.APPSEC_ACTIVE = false; - - assertEquals(200, get("/multi/1.json")); - Map tags = serverSpanTags(); - - assertEquals("/multi/:id.:format", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); - } - - /** - * {@code /catch-all} for {@code /catch-all/*}: Vert.x 4.0.3+ matches it (catch-all removed), - * 4.0.0 to 4.0.2 do not (404, no route handler, no tag). - */ - @Test - void catchAllWithoutTrailingSlash() throws Exception { - int status = get("/catch-all"); - Map tags = serverSpanTags(); - - if (status == 200) { - assertEquals("/catch-all/", String.valueOf(tags.get(HTTP_ROUTE))); - assertEquals("/catch-all", String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); - } else { - assertEquals(404, status); - assertNull(tags.get(HTTP_ROUTE)); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); - } - } -} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerInstrumentation.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerInstrumentation.java index 5f3d6e09472..44982d0e851 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerInstrumentation.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerInstrumentation.java @@ -46,13 +46,10 @@ public void methodAdvice(MethodTransformer transformer) { .and(takesArgument(0, named("io.vertx.core.Handler"))), packageName + ".RouteHandlerWrapperAdvice"); transformer.applyAdvice( - isMethod().and(named("setPath")).and(takesArguments(1)).and(takesArgument(0, String.class)), + isMethod().and(named("setPath")).and(takesArguments(String.class)), packageName + ".RouteSetPathAdvice"); transformer.applyAdvice( - isMethod() - .and(named("setRegex")) - .and(takesArguments(1)) - .and(takesArgument(0, String.class)), + isMethod().and(named("setRegex")).and(takesArguments(String.class)), packageName + ".RouteSetRegexAdvice"); } } diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerWrapper.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerWrapper.java index a489982ae4a..0dc56b7d1c9 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerWrapper.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/main/java/datadog/trace/instrumentation/vertx_4_0/server/RouteHandlerWrapper.java @@ -31,7 +31,7 @@ public class RouteHandlerWrapper implements Handler { private final Handler actual; private final boolean spanStarter; - /** Declared path of each route, null when the instrumentation could not provide it. */ + /** Declared path of each route. */ private final ContextStore declaredPaths; public RouteHandlerWrapper( @@ -135,8 +135,7 @@ private void setRoute(RoutingContext routingContext) { private void tagNormalizedRoute(final RoutingContext routingContext, final AgentSpan span) { try { - final String declared = - declaredPaths != null ? declaredPaths.get(routingContext.currentRoute()) : null; + final String declared = declaredPaths.get(routingContext.currentRoute()); VertxNormalizedRoute.tag( span, declared, diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java deleted file mode 100644 index cccd95728da..00000000000 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java +++ /dev/null @@ -1,144 +0,0 @@ -package server.normalizedroute; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; - -import datadog.trace.agent.test.AbstractInstrumentationTest; -import datadog.trace.agent.test.utils.OkHttpUtils; -import datadog.trace.bootstrap.ActiveSubsystems; -import datadog.trace.core.DDSpan; -import io.vertx.core.Future; -import io.vertx.core.Vertx; -import io.vertx.core.http.HttpServer; -import io.vertx.ext.web.Router; -import io.vertx.ext.web.RoutingContext; -import java.net.ServerSocket; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.TestInstance; - -/** - * Runs a Vert.x 4.x or 5.x server with the normalized route test routes, with AppSec forced active - * like the Spock {@code InstrumentationSpecification}, and returns the tags of the server span. - * Only APIs shared by Vert.x 4.0.0 and 5.x are used, so the same source runs on every version. - */ -@TestInstance(PER_CLASS) -abstract class AbstractVertxNormalizedRouteTest extends AbstractInstrumentationTest { - - private final OkHttpClient client = OkHttpUtils.client(); - private Vertx vertx; - private HttpServer server; - private int port; - private boolean appSecActiveBefore; - - @BeforeAll - void startServer() throws Exception { - try (ServerSocket socket = new ServerSocket(0)) { - port = socket.getLocalPort(); - } - vertx = Vertx.vertx(); - Router router = Router.router(vertx); - router.route("/").handler(AbstractVertxNormalizedRouteTest::ok); - router.route("/multi/:id.:format").handler(AbstractVertxNormalizedRouteTest::ok); - router.route("/three/:a-:b-:c").handler(AbstractVertxNormalizedRouteTest::ok); - router.route("/static-text/user-:id").handler(AbstractVertxNormalizedRouteTest::ok); - router.route("/catch-all/*").handler(AbstractVertxNormalizedRouteTest::ok); - router.route("/encoded/caf%C3%A9").handler(AbstractVertxNormalizedRouteTest::ok); - router.routeWithRegex("/regex/(\\d+)").handler(AbstractVertxNormalizedRouteTest::ok); - // middleware with a declared path, then a regex route: the regex route must not keep its tag - router.route("/stale/*").handler(RoutingContext::next); - router.routeWithRegex("/stale/(\\d+)").handler(AbstractVertxNormalizedRouteTest::ok); - - // what mountSubRouter("/sub/", sub) does on 4.x (mountSubRouter is gone in 5.x) - Router sub = Router.router(vertx); - sub.route("/users/:id").handler(AbstractVertxNormalizedRouteTest::ok); - sub.route("/files/*").handler(AbstractVertxNormalizedRouteTest::ok); - router.route("/sub/*").subRouter(sub); - - // a mount with a parameter: the mount point is the concrete matched prefix - Router tenant = Router.router(vertx); - tenant.route("/items/:id").handler(AbstractVertxNormalizedRouteTest::ok); - router.route("/:tenant/api/*").subRouter(tenant); - - server = await(vertx.createHttpServer().requestHandler(router).listen(port)); - } - - @AfterAll - void stopServer() throws Exception { - if (server != null) { - await(server.close()); - } - if (vertx != null) { - await(vertx.close()); - } - } - - @BeforeEach - void forceAppSecActive() { - appSecActiveBefore = ActiveSubsystems.APPSEC_ACTIVE; - ActiveSubsystems.APPSEC_ACTIVE = true; - } - - @AfterEach - void restoreAppSecActive() { - ActiveSubsystems.APPSEC_ACTIVE = appSecActiveBefore; - } - - private static void ok(RoutingContext ctx) { - ctx.response().setStatusCode(200).end("ok"); - } - - private static T await(Future future) throws Exception { - CountDownLatch done = new CountDownLatch(1); - AtomicReference result = new AtomicReference<>(); - AtomicReference failure = new AtomicReference<>(); - future.onComplete(ar -> { - if (ar.succeeded()) { - result.set(ar.result()); - } else { - failure.set(ar.cause()); - } - done.countDown(); - }); - if (!done.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException("Vert.x operation did not complete in time"); - } - if (failure.get() != null) { - throw new RuntimeException("Vert.x operation failed", failure.get()); - } - return result.get(); - } - - /** Sends {@code GET path} and returns the HTTP status. */ - int get(String path) throws Exception { - Request request = new Request.Builder().url("http://localhost:" + port + path).get().build(); - try (Response response = client.newCall(request).execute()) { - return response.code(); - } - } - - /** Tags of the {@code netty.request} span of the single trace written. */ - Map serverSpanTags() throws Exception { - writer.waitForTraces(1); - DDSpan serverSpan = null; - for (List trace : writer) { - for (DDSpan span : trace) { - if ("netty.request".equals(span.getOperationName().toString())) { - serverSpan = span; - } - } - } - assertNotNull(serverSpan, "netty.request span"); - return serverSpan.getTags(); - } -} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java deleted file mode 100644 index a8825bac467..00000000000 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package server.normalizedroute; - -import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; -import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -import datadog.trace.api.config.AppSecConfig; -import datadog.trace.test.junit.utils.config.WithConfig; -import java.util.Map; -import org.junit.jupiter.api.Test; - -/** With API Security disabled the normalized route is not set; {@code http.route} still is. */ -@WithConfig(key = AppSecConfig.API_SECURITY_ENABLED, value = "false") -class VertxNormalizedRouteApiSecurityDisabledForkedTest extends AbstractVertxNormalizedRouteTest { - - @Test - void noNormalizedRouteWhenApiSecurityIsDisabled() throws Exception { - assertEquals(200, get("/multi/1.json")); - Map tags = serverSpanTags(); - - assertEquals("/multi/:id.:format", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); - } -} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java similarity index 78% rename from dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java rename to dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java index cccd95728da..e437a02957c 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/latestDepTest/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java @@ -1,6 +1,11 @@ package server.normalizedroute; +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; import datadog.trace.agent.test.AbstractInstrumentationTest; @@ -12,11 +17,10 @@ import io.vertx.core.http.HttpServer; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; -import java.net.ServerSocket; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import okhttp3.OkHttpClient; import okhttp3.Request; @@ -35,6 +39,11 @@ @TestInstance(PER_CLASS) abstract class AbstractVertxNormalizedRouteTest extends AbstractInstrumentationTest { + private static final long TIMEOUT_SECONDS = 10; + + /** Operation name of the server span, which carries both route tags. */ + private static final String SERVER_SPAN = "netty.request"; + private final OkHttpClient client = OkHttpUtils.client(); private Vertx vertx; private HttpServer server; @@ -43,9 +52,6 @@ abstract class AbstractVertxNormalizedRouteTest extends AbstractInstrumentationT @BeforeAll void startServer() throws Exception { - try (ServerSocket socket = new ServerSocket(0)) { - port = socket.getLocalPort(); - } vertx = Vertx.vertx(); Router router = Router.router(vertx); router.route("/").handler(AbstractVertxNormalizedRouteTest::ok); @@ -70,7 +76,8 @@ void startServer() throws Exception { tenant.route("/items/:id").handler(AbstractVertxNormalizedRouteTest::ok); router.route("/:tenant/api/*").subRouter(tenant); - server = await(vertx.createHttpServer().requestHandler(router).listen(port)); + server = await(vertx.createHttpServer().requestHandler(router).listen(0)); + port = server.actualPort(); } @AfterAll @@ -110,7 +117,7 @@ private static T await(Future future) throws Exception { } done.countDown(); }); - if (!done.await(10, TimeUnit.SECONDS)) { + if (!done.await(TIMEOUT_SECONDS, SECONDS)) { throw new IllegalStateException("Vert.x operation did not complete in time"); } if (failure.get() != null) { @@ -127,18 +134,30 @@ int get(String path) throws Exception { } } - /** Tags of the {@code netty.request} span of the single trace written. */ + /** Tags of the {@link #SERVER_SPAN} span of the single trace written. */ Map serverSpanTags() throws Exception { writer.waitForTraces(1); DDSpan serverSpan = null; for (List trace : writer) { for (DDSpan span : trace) { - if ("netty.request".equals(span.getOperationName().toString())) { + if (SERVER_SPAN.equals(span.getOperationName().toString())) { serverSpan = span; } } } - assertNotNull(serverSpan, "netty.request span"); + assertNotNull(serverSpan, SERVER_SPAN + " span"); return serverSpan.getTags(); } + + /** + * Sends {@code GET request}, expects a 200 with {@code expectedHttpRoute} (null for none) as + * {@code http.route} and no normalized route. + */ + void assertNoNormalizedRoute(String request, String expectedHttpRoute) throws Exception { + assertEquals(200, get(request)); + Map tags = serverSpanTags(); + + assertEquals(expectedHttpRoute, Objects.toString(tags.get(HTTP_ROUTE), null)); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } } diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java new file mode 100644 index 00000000000..0cdebbd2602 --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java @@ -0,0 +1,15 @@ +package server.normalizedroute; + +import datadog.trace.api.config.AppSecConfig; +import datadog.trace.test.junit.utils.config.WithConfig; +import org.junit.jupiter.api.Test; + +/** With API Security disabled the normalized route is not set; {@code http.route} still is. */ +@WithConfig(key = AppSecConfig.API_SECURITY_ENABLED, value = "false") +class VertxNormalizedRouteApiSecurityDisabledForkedTest extends AbstractVertxNormalizedRouteTest { + + @Test + void noNormalizedRouteWhenApiSecurityIsDisabled() throws Exception { + assertNoNormalizedRoute("/multi/1.json", "/multi/:id.:format"); + } +} diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/VertxNormalizedRouteTest.java similarity index 68% rename from dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java rename to dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/VertxNormalizedRouteTest.java index 9d4f84fb2c6..3d09551bfb3 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/VertxNormalizedRouteTest.java @@ -14,11 +14,13 @@ class VertxNormalizedRouteTest extends AbstractVertxNormalizedRouteTest { @TableTest({ - "Scenario | Request | Route | Normalized ", + "Scenario | Request | HttpRoute | Normalized ", "root | '/' | '/' | '/' ", "two params in a segment | '/multi/1.json' | '/multi/:id.:format' | '/multi/{id}.{format}' ", "three params in a segment | '/three/1-2-3' | '/three/:a-:b-:c' | '/three/{a}-{b}-{c}' ", "static text before a param | '/static-text/user-1' | '/static-text/user-:id' | '/static-text/user-{id}'", + // getPath() drops the trailing '*' (http.route '/catch-all/'), so '{param1}' proves the + // declared '/catch-all/*' was captured from setPath "catch-all present | '/catch-all/a/b/c.txt' | '/catch-all/' | '/catch-all/{param1}' ", "catch-all matched a slash | '/catch-all/' | '/catch-all/' | '/catch-all/' ", "catch-all after a collapsed slash | '/catch-all//' | '/catch-all/' | '/catch-all/' ", @@ -26,35 +28,18 @@ class VertxNormalizedRouteTest extends AbstractVertxNormalizedRouteTest { "sub-router param | '/sub/users/1' | '/sub/users/:id' | '/sub/users/{id}' ", "sub-router catch-all | '/sub/files/a' | '/sub/files/' | '/sub/files/{param1}' " }) - void normalizedRoute(String request, String route, String normalized) throws Exception { + void normalizedRoute(String request, String httpRoute, String normalized) throws Exception { assertEquals(200, get(request)); Map tags = serverSpanTags(); - assertEquals(route, String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals(httpRoute, String.valueOf(tags.get(HTTP_ROUTE))); assertEquals(normalized, String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); } - /** - * The store holds the declared {@code /catch-all/*}: {@code getPath()} drops the trailing {@code - * *} (http.route {@code /catch-all/}), so only the declared path gives {@code {param1}}. - */ - @Test - void storeKeepsTheTrailingStarOfTheDeclaredPath() throws Exception { - assertEquals(200, get("/catch-all/x")); - Map tags = serverSpanTags(); - - assertEquals("/catch-all/", String.valueOf(tags.get(HTTP_ROUTE))); - assertEquals("/catch-all/{param1}", String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); - } - /** {@code http.route} falls back to the regex of the route; a regex has no normalized route. */ @Test void noNormalizedRouteForRegexRoute() throws Exception { - assertEquals(200, get("/regex/123")); - Map tags = serverSpanTags(); - - assertEquals("/regex/(\\d+)", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + assertNoNormalizedRoute("/regex/123", "/regex/(\\d+)"); } /** @@ -63,11 +48,7 @@ void noNormalizedRouteForRegexRoute() throws Exception { */ @Test void staleNormalizedRouteIsClearedByLaterRegexRoute() throws Exception { - assertEquals(200, get("/stale/1")); - Map tags = serverSpanTags(); - - assertEquals("/stale/(\\d+)", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + assertNoNormalizedRoute("/stale/1", "/stale/(\\d+)"); } /** @@ -77,22 +58,14 @@ void staleNormalizedRouteIsClearedByLaterRegexRoute() throws Exception { */ @Test void noNormalizedRouteUnderAParameterMount() throws Exception { - assertEquals(200, get("/acme/api/items/1")); - Map tags = serverSpanTags(); - - assertEquals("/acme/api/items/:id", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + assertNoNormalizedRoute("/acme/api/items/1", "/acme/api/items/:id"); } @Test void noNormalizedRouteWhenAppSecIsInactive() throws Exception { ActiveSubsystems.APPSEC_ACTIVE = false; - assertEquals(200, get("/multi/1.json")); - Map tags = serverSpanTags(); - - assertEquals("/multi/:id.:format", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + assertNoNormalizedRoute("/multi/1.json", "/multi/:id.:format"); } /** diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java index cccd95728da..e437a02957c 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java @@ -1,6 +1,11 @@ package server.normalizedroute; +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; import datadog.trace.agent.test.AbstractInstrumentationTest; @@ -12,11 +17,10 @@ import io.vertx.core.http.HttpServer; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; -import java.net.ServerSocket; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import okhttp3.OkHttpClient; import okhttp3.Request; @@ -35,6 +39,11 @@ @TestInstance(PER_CLASS) abstract class AbstractVertxNormalizedRouteTest extends AbstractInstrumentationTest { + private static final long TIMEOUT_SECONDS = 10; + + /** Operation name of the server span, which carries both route tags. */ + private static final String SERVER_SPAN = "netty.request"; + private final OkHttpClient client = OkHttpUtils.client(); private Vertx vertx; private HttpServer server; @@ -43,9 +52,6 @@ abstract class AbstractVertxNormalizedRouteTest extends AbstractInstrumentationT @BeforeAll void startServer() throws Exception { - try (ServerSocket socket = new ServerSocket(0)) { - port = socket.getLocalPort(); - } vertx = Vertx.vertx(); Router router = Router.router(vertx); router.route("/").handler(AbstractVertxNormalizedRouteTest::ok); @@ -70,7 +76,8 @@ void startServer() throws Exception { tenant.route("/items/:id").handler(AbstractVertxNormalizedRouteTest::ok); router.route("/:tenant/api/*").subRouter(tenant); - server = await(vertx.createHttpServer().requestHandler(router).listen(port)); + server = await(vertx.createHttpServer().requestHandler(router).listen(0)); + port = server.actualPort(); } @AfterAll @@ -110,7 +117,7 @@ private static T await(Future future) throws Exception { } done.countDown(); }); - if (!done.await(10, TimeUnit.SECONDS)) { + if (!done.await(TIMEOUT_SECONDS, SECONDS)) { throw new IllegalStateException("Vert.x operation did not complete in time"); } if (failure.get() != null) { @@ -127,18 +134,30 @@ int get(String path) throws Exception { } } - /** Tags of the {@code netty.request} span of the single trace written. */ + /** Tags of the {@link #SERVER_SPAN} span of the single trace written. */ Map serverSpanTags() throws Exception { writer.waitForTraces(1); DDSpan serverSpan = null; for (List trace : writer) { for (DDSpan span : trace) { - if ("netty.request".equals(span.getOperationName().toString())) { + if (SERVER_SPAN.equals(span.getOperationName().toString())) { serverSpan = span; } } } - assertNotNull(serverSpan, "netty.request span"); + assertNotNull(serverSpan, SERVER_SPAN + " span"); return serverSpan.getTags(); } + + /** + * Sends {@code GET request}, expects a 200 with {@code expectedHttpRoute} (null for none) as + * {@code http.route} and no normalized route. + */ + void assertNoNormalizedRoute(String request, String expectedHttpRoute) throws Exception { + assertEquals(200, get(request)); + Map tags = serverSpanTags(); + + assertEquals(expectedHttpRoute, Objects.toString(tags.get(HTTP_ROUTE), null)); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } } diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java index a8825bac467..0cdebbd2602 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteApiSecurityDisabledForkedTest.java @@ -1,13 +1,7 @@ package server.normalizedroute; -import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; -import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - import datadog.trace.api.config.AppSecConfig; import datadog.trace.test.junit.utils.config.WithConfig; -import java.util.Map; import org.junit.jupiter.api.Test; /** With API Security disabled the normalized route is not set; {@code http.route} still is. */ @@ -16,10 +10,6 @@ class VertxNormalizedRouteApiSecurityDisabledForkedTest extends AbstractVertxNor @Test void noNormalizedRouteWhenApiSecurityIsDisabled() throws Exception { - assertEquals(200, get("/multi/1.json")); - Map tags = serverSpanTags(); - - assertEquals("/multi/:id.:format", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + assertNoNormalizedRoute("/multi/1.json", "/multi/:id.:format"); } } diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java index 9d4f84fb2c6..3d09551bfb3 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java @@ -14,11 +14,13 @@ class VertxNormalizedRouteTest extends AbstractVertxNormalizedRouteTest { @TableTest({ - "Scenario | Request | Route | Normalized ", + "Scenario | Request | HttpRoute | Normalized ", "root | '/' | '/' | '/' ", "two params in a segment | '/multi/1.json' | '/multi/:id.:format' | '/multi/{id}.{format}' ", "three params in a segment | '/three/1-2-3' | '/three/:a-:b-:c' | '/three/{a}-{b}-{c}' ", "static text before a param | '/static-text/user-1' | '/static-text/user-:id' | '/static-text/user-{id}'", + // getPath() drops the trailing '*' (http.route '/catch-all/'), so '{param1}' proves the + // declared '/catch-all/*' was captured from setPath "catch-all present | '/catch-all/a/b/c.txt' | '/catch-all/' | '/catch-all/{param1}' ", "catch-all matched a slash | '/catch-all/' | '/catch-all/' | '/catch-all/' ", "catch-all after a collapsed slash | '/catch-all//' | '/catch-all/' | '/catch-all/' ", @@ -26,35 +28,18 @@ class VertxNormalizedRouteTest extends AbstractVertxNormalizedRouteTest { "sub-router param | '/sub/users/1' | '/sub/users/:id' | '/sub/users/{id}' ", "sub-router catch-all | '/sub/files/a' | '/sub/files/' | '/sub/files/{param1}' " }) - void normalizedRoute(String request, String route, String normalized) throws Exception { + void normalizedRoute(String request, String httpRoute, String normalized) throws Exception { assertEquals(200, get(request)); Map tags = serverSpanTags(); - assertEquals(route, String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals(httpRoute, String.valueOf(tags.get(HTTP_ROUTE))); assertEquals(normalized, String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); } - /** - * The store holds the declared {@code /catch-all/*}: {@code getPath()} drops the trailing {@code - * *} (http.route {@code /catch-all/}), so only the declared path gives {@code {param1}}. - */ - @Test - void storeKeepsTheTrailingStarOfTheDeclaredPath() throws Exception { - assertEquals(200, get("/catch-all/x")); - Map tags = serverSpanTags(); - - assertEquals("/catch-all/", String.valueOf(tags.get(HTTP_ROUTE))); - assertEquals("/catch-all/{param1}", String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); - } - /** {@code http.route} falls back to the regex of the route; a regex has no normalized route. */ @Test void noNormalizedRouteForRegexRoute() throws Exception { - assertEquals(200, get("/regex/123")); - Map tags = serverSpanTags(); - - assertEquals("/regex/(\\d+)", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + assertNoNormalizedRoute("/regex/123", "/regex/(\\d+)"); } /** @@ -63,11 +48,7 @@ void noNormalizedRouteForRegexRoute() throws Exception { */ @Test void staleNormalizedRouteIsClearedByLaterRegexRoute() throws Exception { - assertEquals(200, get("/stale/1")); - Map tags = serverSpanTags(); - - assertEquals("/stale/(\\d+)", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + assertNoNormalizedRoute("/stale/1", "/stale/(\\d+)"); } /** @@ -77,22 +58,14 @@ void staleNormalizedRouteIsClearedByLaterRegexRoute() throws Exception { */ @Test void noNormalizedRouteUnderAParameterMount() throws Exception { - assertEquals(200, get("/acme/api/items/1")); - Map tags = serverSpanTags(); - - assertEquals("/acme/api/items/:id", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + assertNoNormalizedRoute("/acme/api/items/1", "/acme/api/items/:id"); } @Test void noNormalizedRouteWhenAppSecIsInactive() throws Exception { ActiveSubsystems.APPSEC_ACTIVE = false; - assertEquals(200, get("/multi/1.json")); - Map tags = serverSpanTags(); - - assertEquals("/multi/:id.:format", String.valueOf(tags.get(HTTP_ROUTE))); - assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + assertNoNormalizedRoute("/multi/1.json", "/multi/:id.:format"); } /** diff --git a/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxNormalizedRoute.java b/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxNormalizedRoute.java index 1b665086b9f..a20691aa3f9 100644 --- a/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxNormalizedRoute.java +++ b/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxNormalizedRoute.java @@ -19,11 +19,22 @@ public final class VertxNormalizedRoute { private static final Logger log = LoggerFactory.getLogger(VertxNormalizedRoute.class); /** System property that selects the {@link Grammar#EXTENDED} name grammar on Vert.x 4.0.3+. */ - static final String EXTENDED_PATTERN_PROPERTY = "io.vertx.web.route.param.extended-pattern"; + private static final String EXTENDED_PATTERN_PROPERTY = + "io.vertx.web.route.param.extended-pattern"; /** Path param Vert.x binds to the catch-all match; never used for presence. */ private static final String REST_PARAM = "*"; + /** {@link #remainderStart} result: the request path does not match the static base. */ + private static final int UNKNOWN_REMAINDER = -1; + + /** + * {@link #remainderStart} result: the full base ends inside a request segment while the {@code *} + * is a whole segment. Vert.x matched something the template cannot describe (a mount {@code /sub} + * without trailing {@code /} matches {@code /subway/x} for the sub-route {@code /*}). + */ + private static final int NOT_A_SEGMENT_BOUNDARY = -2; + /** Catch-all resolvers by {@link RoutePresence#ordinal()}, so rendering allocates none. */ private static final PresenceResolver[] CATCH_ALL_RESOLVERS; @@ -65,12 +76,14 @@ public static void tag( // a later route that cannot be expressed must not keep the tag of an earlier one span.setTag(NormalizedRouteHelper.NORMALIZED_ROUTE_TAG, (String) null); RouteTemplate template = template(declaredPath, grammar, mountPoint, pathParams); - if (template != null) { + if (template == null) { + return; + } + PresenceResolver resolver = + resolver(template, declaredPath, grammar, mountPoint, normalizedPath); + if (resolver != null) { NormalizedRouteHelper.tag( - span, - template, - NormalizedRouteHelper.decodePath(mountPoint), - resolver(template, declaredPath, grammar, mountPoint, normalizedPath)); + span, template, NormalizedRouteHelper.decodePath(mountPoint), resolver); } } catch (Throwable t) { log.debug("Failed to set the Vert.x normalized route tag", t); @@ -89,9 +102,11 @@ static String render( if (template == null) { return null; } - return template.render( - NormalizedRouteHelper.decodePath(mountPoint), - resolver(template, declaredPath, grammar, mountPoint, normalizedPath)); + PresenceResolver resolver = + resolver(template, declaredPath, grammar, mountPoint, normalizedPath); + return resolver == null + ? null + : template.render(NormalizedRouteHelper.decodePath(mountPoint), resolver); } /** @@ -112,7 +127,8 @@ static Grammar vertx4Grammar(boolean extendedPattern) { * Template to render, or null when there is no tag: the route cannot be expressed, or the mount * point holds request values. A mount with parameters returns the concrete matched prefix and * shares its {@code pathParams()} with the sub-router, so a bound parameter that the route does - * not declare means a parameter mount (conservative: a middleware route may also have left it). + * not declare means a parameter mount (conservative: a middleware route may also have left it). A + * root mount ({@code /}) never holds request values, so it skips that check. */ private static RouteTemplate template( String declaredPath, Grammar grammar, String mountPoint, Map pathParams) { @@ -120,7 +136,7 @@ private static RouteTemplate template( if (!template.isExpressible()) { return null; } - if (mountPoint != null && !mountPoint.isEmpty() && pathParams != null) { + if (pathParams != null && !isRootMount(mountPoint)) { for (String name : pathParams.keySet()) { if (!REST_PARAM.equals(name) && !VertxRouteParser.declaresParam(declaredPath, name, grammar)) { @@ -131,8 +147,16 @@ private static RouteTemplate template( return template; } + /** Whether there is no mount, or the mount is {@code /} (empty once its trailing '/' is gone). */ + private static boolean isRootMount(String mountPoint) { + return mountPoint == null + || mountPoint.isEmpty() + || (mountPoint.length() == 1 && mountPoint.charAt(0) == '/'); + } + /** - * Presence of the trailing catch-all, or null for templates that do not depend on the request. + * Presence of the trailing catch-all ({@link PresenceResolver#UNKNOWN} for templates that do not + * depend on the request), or null when there is no tag. */ private static PresenceResolver resolver( RouteTemplate template, @@ -142,14 +166,31 @@ private static PresenceResolver resolver( String normalizedPath) { // the trailing '*' is the only optional part of a Vert.x template if (template.staticRoute() != null) { - return null; + return PresenceResolver.UNKNOWN; } int start = remainderStart(declaredPath, grammar, mountPoint, normalizedPath); - RoutePresence presence = - start < 0 - ? RoutePresence.UNKNOWN - : RoutePresence.ofCatchAllValue(normalizedPath.substring(start)); - return catchAllResolver(presence); + if (start == NOT_A_SEGMENT_BOUNDARY) { + return null; + } + return catchAllResolver( + start == UNKNOWN_REMAINDER ? RoutePresence.UNKNOWN : presenceFrom(normalizedPath, start)); + } + + /** + * Same as {@link RoutePresence#ofCatchAllValue} for {@code path.substring(start)}, without the + * copy. + */ + private static RoutePresence presenceFrom(String path, int start) { + int length = path.length(); + if (start == length) { + return RoutePresence.ABSENT; + } + for (int i = start; i < length; i++) { + if (path.charAt(i) != '/') { + return RoutePresence.PRESENT; + } + } + return RoutePresence.ABSENT_TRAILING_SLASH; } /** Shared resolver that answers {@code presence} for the unnamed catch-all. */ @@ -159,7 +200,8 @@ static PresenceResolver catchAllResolver(RoutePresence presence) { } /** - * Index of {@code normalizedPath} where the trailing {@code *} match starts, or -1 when unknown. + * Index of {@code normalizedPath} where the trailing {@code *} match starts, {@link + * #UNKNOWN_REMAINDER} when the path does not match the base, or {@link #NOT_A_SEGMENT_BOUNDARY}. * The static base is the declared path without the {@code *} and the {@code /} right before it; * the full base is the mount (without its trailing {@code /}) followed by the base, which is * Vert.x' join: {@code mount + path.substring(1)} for a mount ending with {@code /}, the mount @@ -168,7 +210,7 @@ static PresenceResolver catchAllResolver(RoutePresence presence) { private static int remainderStart( String declaredPath, Grammar grammar, String mountPoint, String normalizedPath) { if (normalizedPath == null) { - return -1; + return UNKNOWN_REMAINDER; } int baseEnd = declaredPath.length() - 1; boolean wholeSegment = baseEnd > 0 && declaredPath.charAt(baseEnd - 1) == '/'; @@ -180,25 +222,25 @@ private static int remainderStart( mountLength--; } if (mountLength > 0 && !normalizedPath.regionMatches(0, mountPoint, 0, mountLength)) { - return -1; + return UNKNOWN_REMAINDER; } int start; if (declaredPath.indexOf(':') < 0) { // no parameter: Vert.x matches the joined path with startsWith if (!normalizedPath.regionMatches(mountLength, declaredPath, 0, baseEnd)) { - return -1; + return UNKNOWN_REMAINDER; } start = mountLength + baseEnd; } else { start = skipSegments(declaredPath, baseEnd, wholeSegment, grammar, normalizedPath, mountLength); if (start < 0) { - return -1; + return UNKNOWN_REMAINDER; } } if (wholeSegment && start < normalizedPath.length() && normalizedPath.charAt(start) != '/') { - // "/a/*" never matches "/ab" - return -1; + // "/a/*" never matches "/ab" by itself; a mount without trailing '/' can make it match + return NOT_A_SEGMENT_BOUNDARY; } return start; } @@ -219,7 +261,7 @@ private static int skipSegments( int pathLength = path.length(); int segmentStart = 0; while (segmentStart < baseEnd) { - // declaredPath.charAt(segmentStart) == '/': the parser only accepts absolute paths + // invariant: every declared segment starts with '/' (parse rejects relative paths) if (position >= pathLength || path.charAt(position) != '/') { return -1; } diff --git a/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxRouteParser.java b/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxRouteParser.java index 2f88b841de2..af358fdf04c 100644 --- a/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxRouteParser.java +++ b/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxRouteParser.java @@ -53,11 +53,21 @@ public enum Grammar { */ EXTENDED; - private final DDCache cache = DDCaches.newFixedSizeCache(CACHE_CAPACITY); - private final Function safeParse = safely(path -> VertxRouteParser.parse(path, this)); + /** Cache of this grammar; created on first use, so a process only pays for the one it uses. */ + DDCache cache() { + switch (this) { + case LEGACY: + return LegacyCache.CACHE; + case EXTENDED: + return ExtendedCache.CACHE; + default: + return DefaultCache.CACHE; + } + } + boolean isNameStart(char c) { if (isAsciiLetter(c)) { return true; @@ -87,6 +97,21 @@ private static boolean isDigit(char c) { private VertxRouteParser() {} + /** Lazy holder of the {@link Grammar#LEGACY} cache. */ + private static final class LegacyCache { + static final DDCache CACHE = DDCaches.newFixedSizeCache(CACHE_CAPACITY); + } + + /** Lazy holder of the {@link Grammar#DEFAULT} cache. */ + private static final class DefaultCache { + static final DDCache CACHE = DDCaches.newFixedSizeCache(CACHE_CAPACITY); + } + + /** Lazy holder of the {@link Grammar#EXTENDED} cache. */ + private static final class ExtendedCache { + static final DDCache CACHE = DDCaches.newFixedSizeCache(CACHE_CAPACITY); + } + /** * Same as {@link #parse(String, Grammar)} but backed by a bounded cache per grammar, for the * request hot path. Never returns null or throws. @@ -95,7 +120,7 @@ public static RouteTemplate cached(String declaredPath, Grammar grammar) { if (grammar == null) { return RouteTemplate.NOT_EXPRESSIBLE; } - return cached(grammar.cache, declaredPath, grammar.safeParse); + return cached(grammar.cache(), declaredPath, grammar.safeParse); } @VisibleForTesting @@ -158,7 +183,7 @@ public static RouteTemplate parse(String declaredPath, Grammar grammar) { boolean trailingStar = declaredPath.charAt(len - 1) == '*'; int end = trailingStar ? len - 1 : len; // Vert.x compiles the path to a regex as soon as it holds a ':', valid name or not - boolean regex = declaredPath.indexOf(':') >= 0; + boolean compiledToRegex = declaredPath.indexOf(':') >= 0; RouteTemplate.Builder builder = RouteTemplate.builder(); List parts = new ArrayList<>(); List names = null; @@ -170,41 +195,36 @@ public static RouteTemplate parse(String declaredPath, Grammar grammar) { literalStart = flushLiteral(declaredPath, literalStart, i, parts); endSegment(builder, parts); i++; - } else if (regex && isRegexOperator(c)) { + } else if (compiledToRegex && isRegexOperator(c)) { return RouteTemplate.NOT_EXPRESSIBLE; - } else if (c == ':' && i + 1 < end && grammar.isNameStart(declaredPath.charAt(i + 1))) { - literalStart = flushLiteral(declaredPath, literalStart, i, parts); - int nameEnd = i + 2; - while (nameEnd < end && grammar.isNamePart(declaredPath.charAt(nameEnd))) { - nameEnd++; - } - String name = declaredPath.substring(i + 1, nameEnd); - if (names == null) { - names = new ArrayList<>(); - } else if (names.contains(name)) { - // Vert.x rejects a name used twice - return RouteTemplate.NOT_EXPRESSIBLE; - } - names.add(name); - parts.add(param(name)); - i = nameEnd; } else { - if (literalStart < 0) { - literalStart = i; + int nameEnd = c == ':' ? nameEnd(declaredPath, i, end, grammar) : -1; + if (nameEnd > 0) { + literalStart = flushLiteral(declaredPath, literalStart, i, parts); + String name = declaredPath.substring(i + 1, nameEnd); + if (names == null) { + names = new ArrayList<>(); + } else if (names.contains(name)) { + // Vert.x rejects a name used twice + return RouteTemplate.NOT_EXPRESSIBLE; + } + names.add(name); + parts.add(param(name)); + i = nameEnd; + } else { + if (literalStart < 0) { + literalStart = i; + } + i++; } - i++; } } flushLiteral(declaredPath, literalStart, end, parts); - if (trailingStar && declaredPath.charAt(end - 1) == '/') { - // "/a/*": the '/' before it already closed the previous segment - builder.segment(catchAll(null)); - } else { - if (trailingStar) { - parts.add(catchAll(null)); - } - endSegment(builder, parts); + // for "/a/*", the '/' before the '*' already closed the previous segment: the '*' is alone + if (trailingStar) { + parts.add(catchAll(null)); } + endSegment(builder, parts); return builder .trailingSlash(!trailingStar && len > 1 && declaredPath.charAt(len - 1) == '/') .build(); @@ -221,7 +241,7 @@ static boolean declaresParam(String declaredPath, String name, Grammar grammar) int len = declaredPath.length(); for (int i = declaredPath.indexOf(':'); i >= 0; i = declaredPath.indexOf(':', i + 1)) { int nameEnd = nameEnd(declaredPath, i, len, grammar); - if (nameEnd - i - 1 == name.length() && declaredPath.startsWith(name, i + 1)) { + if (nameEnd > 0 && nameEnd - i - 1 == name.length() && declaredPath.startsWith(name, i + 1)) { return true; } } diff --git a/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteForkedTest.java b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteForkedTest.java index 00fb6113496..01e9b6aa41b 100644 --- a/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteForkedTest.java +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteForkedTest.java @@ -2,6 +2,7 @@ import static datadog.trace.api.KnownTags.DD_APPSEC_NORMALIZED_ROUTE; import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static java.util.Collections.singletonMap; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.inOrder; @@ -14,19 +15,16 @@ import datadog.trace.bootstrap.ActiveSubsystems; import datadog.trace.bootstrap.instrumentation.api.AgentSpan; import datadog.trace.bootstrap.instrumentation.api.Tags; -import java.util.Collections; -import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InOrder; +import org.tabletest.junit.TableTest; /** Mutates the global {@link ActiveSubsystems#APPSEC_ACTIVE}, so it runs in its own JVM. */ class VertxNormalizedRouteForkedTest { - private static final Map NO_PARAMS = Collections.emptyMap(); - private boolean previousAppSecActive; @BeforeEach @@ -45,47 +43,25 @@ void clearsThePreviousTagThenSetsTheNewOne() { AgentSpan span = spanWithRoute("/sub/catch-all/"); VertxNormalizedRoute.tag( - span, - "/catch-all/*", - Grammar.DEFAULT, - "/sub/", - "/sub/catch-all/a", - Collections.singletonMap("*", "a")); + span, "/catch-all/*", Grammar.DEFAULT, "/sub/", "/sub/catch-all/a", singletonMap("*", "a")); InOrder order = inOrder(span); order.verify(span).setTag(NORMALIZED_ROUTE_TAG, (String) null); order.verify(span).setTag(DD_APPSEC_NORMALIZED_ROUTE, "/sub/catch-all/{param1}"); } - @Test - void onlyClearsForANullDeclaredPath() { - AgentSpan span = spanWithRoute("/a"); - - VertxNormalizedRoute.tag(span, null, Grammar.DEFAULT, null, "/a", NO_PARAMS); - - verify(span).setTag(NORMALIZED_ROUTE_TAG, (String) null); - verify(span, never()).setTag(anyLong(), anyString()); - } - - @Test - void onlyClearsForARegexLikeRoute() { - AgentSpan span = spanWithRoute("/a/:id?"); - - VertxNormalizedRoute.tag(span, "/a/:id?", Grammar.DEFAULT, null, "/a/1", NO_PARAMS); - - verify(span).setTag(NORMALIZED_ROUTE_TAG, (String) null); - verify(span, never()).setTag(anyLong(), anyString()); - } - - @Test - void onlyClearsUnderAParamMount() { - AgentSpan span = spanWithRoute("/acme/api/users/:id"); - Map params = new HashMap<>(); - params.put("tenant", "acme"); - params.put("id", "1"); - - VertxNormalizedRoute.tag( - span, "/users/:id", Grammar.DEFAULT, "/acme/api/", "/acme/api/users/1", params); + @TableTest({ + "Scenario | Declared | Mount | Path | Params ", + "null declared path | | | '/a' | [:] ", + "regex-like route | '/a/:id?' | | '/a/1' | [:] ", + "param mount | '/users/:id' | '/acme/api/' | '/acme/api/users/1' | [tenant: acme, id: '1']", + "mount inside a segment | '/*' | '/sub' | '/subway/x' | [:] " + }) + void onlyClearsWhenThereIsNoTag( + String declared, String mount, String path, Map params) { + AgentSpan span = spanWithRoute("/route"); + + VertxNormalizedRoute.tag(span, declared, Grammar.DEFAULT, mount, path, params); verify(span).setTag(NORMALIZED_ROUTE_TAG, (String) null); verify(span, never()).setTag(anyLong(), anyString()); diff --git a/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteTest.java b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteTest.java index 94cb0c6f033..c3749e21105 100644 --- a/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteTest.java +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteTest.java @@ -1,6 +1,7 @@ package datadog.trace.api.appsec.route; import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static java.util.Collections.emptyMap; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.anyString; @@ -11,7 +12,6 @@ import datadog.trace.api.appsec.route.VertxRouteParser.Grammar; import datadog.trace.bootstrap.instrumentation.api.AgentSpan; -import java.util.Collections; import java.util.Map; import org.junit.jupiter.api.Test; import org.tabletest.junit.TableTest; @@ -29,11 +29,11 @@ class VertxNormalizedRouteTest { "dashed params, extended grammar | '/t/:a-b' | EXTENDED | | '/t/1' | [a-b: '1'] | '/t/{a_b}' ", "encoded literal | '/caf%C3%A9' | DEFAULT | | '/caf%C3%A9' | [:] | '/caf%C3%A9' ", "encoded mount | '/x' | DEFAULT | '/caf%C3%A9/' | '/caf%C3%A9/x' | [:] | '/caf%C3%A9/x' ", - "catch-all, base only | '/catch-all/*' | DEFAULT | | '/catch-all' | ['*': '/'] | '/catch-all' ", - "catch-all, trailing slash | '/catch-all/*' | DEFAULT | | '/catch-all/' | ['*': ''] | '/catch-all/' ", - "catch-all, present | '/catch-all/*' | DEFAULT | | '/catch-all/a/b' | ['*': 'a/b'] | '/catch-all/{param1}' ", - "catch-all, double slash normalized | '/api_security/catch-all/*' | DEFAULT | | '/api_security/catch-all/' | [:] | '/api_security/catch-all/'", - "catch-all, other segment | '/catch-all/*' | DEFAULT | | '/catch-allx' | [:] | '/catch-all' ", + "catch-all, base only | '/catch-all/*' | DEFAULT | | '/catch-all' | [:] | '/catch-all' ", + "catch-all, trailing slash | '/catch-all/*' | DEFAULT | | '/catch-all/' | [:] | '/catch-all/' ", + "catch-all, present | '/catch-all/*' | DEFAULT | | '/catch-all/a/b' | [:] | '/catch-all/{param1}' ", + "catch-all, nested base, trailing slash | '/api_security/catch-all/*' | DEFAULT | | '/api_security/catch-all/' | [:] | '/api_security/catch-all/'", + "catch-all, other segment | '/catch-all/*' | DEFAULT | | '/catch-allx' | [:] | ", "catch-all, path outside the base | '/catch-all/*' | DEFAULT | | '/other/a' | [:] | '/catch-all' ", "catch-all, no normalized path | '/catch-all/*' | DEFAULT | | | [:] | '/catch-all' ", "catch-all under mount with slash | '/catch-all/*' | DEFAULT | '/sub/' | '/sub/catch-all/a' | ['*': 'a'] | '/sub/catch-all/{param1}' ", @@ -45,10 +45,16 @@ class VertxNormalizedRouteTest { "root catch-all under mount, present | '/*' | DEFAULT | '/sub/' | '/sub/x' | [:] | '/sub/{param1}' ", "root catch-all under mount, slash | '/*' | DEFAULT | '/sub/' | '/sub/' | [:] | '/sub/' ", "root catch-all under mount, base only | '/*' | LEGACY | '/sub' | '/sub' | [:] | '/sub' ", + "root catch-all, bare mount, slash | '/*' | LEGACY | '/sub' | '/sub/' | [:] | '/sub/' ", + "root catch-all, bare mount, present | '/*' | LEGACY | '/sub' | '/sub/x' | [:] | '/sub/{param1}' ", + "root catch-all, bare mount, base only 4.x | '/*' | DEFAULT | '/sub' | '/sub' | [:] | '/sub' ", + "root catch-all, bare mount, other segment | '/*' | LEGACY | '/sub' | '/subway/x' | [:] | ", + "root catch-all, bare mount, other seg 4.x | '/*' | DEFAULT | '/sub' | '/subway' | [:] | ", + "catch-all under mount, other segment | '/x/*' | DEFAULT | '/sub' | '/sub/xy' | [:] | ", "in-segment catch-all, present | '/img*' | DEFAULT | | '/img42' | [:] | '/img{param1}' ", "in-segment catch-all, absent | '/img*' | DEFAULT | | '/img' | [:] | '/img' ", "param prefix route, slash | '/users/:id/*' | DEFAULT | | '/users/5/' | [id: '5'] | '/users/{id}/' ", - "param prefix route, present | '/users/:id/*' | DEFAULT | | '/users/5/a/b' | [id: '5', '*': 'a/b'] | '/users/{id}/{param1}' ", + "param prefix route, present | '/users/:id/*' | DEFAULT | | '/users/5/a/b' | [id: '5'] | '/users/{id}/{param1}' ", "param prefix route, absent | '/users/:id/*' | DEFAULT | | '/users/5' | [id: '5'] | '/users/{id}' ", "param prefix route, too few segments | '/users/:id/*' | DEFAULT | | '/users' | [:] | '/users/{id}' ", "param prefix route, no leading slash | '/users/:id/*' | DEFAULT | | 'users/5/a' | [:] | '/users/{id}' ", @@ -69,6 +75,7 @@ class VertxNormalizedRouteTest { "param mount: undeclared bound param | '/users/:id' | DEFAULT | '/acme/api/' | '/acme/api/users/1' | [tenant: acme, id: '1'] | ", "same params without mount | '/users/:id' | DEFAULT | | '/users/1' | [tenant: acme, id: '1'] | '/users/{id}' ", "same params with empty mount | '/users/:id' | DEFAULT | '' | '/users/1' | [tenant: acme, id: '1'] | '/users/{id}' ", + "same params with root mount | '/users/:id' | DEFAULT | '/' | '/users/1' | [tenant: acme, id: '1'] | '/users/{id}' ", "mount: rest param ignored | '/users/:id' | DEFAULT | '/sub/' | '/sub/users/1' | [id: '1', '*': x] | '/sub/users/{id}' ", "mount: no params | '/users/:id' | DEFAULT | '/sub/' | '/sub/users/1' | | '/sub/users/{id}' " }) @@ -83,11 +90,10 @@ void rendersTheNormalizedRoute( } @Test - void clearsThePreviousTagBeforeTagging() { + void clearsTheTagEvenWhenDisabled() { AgentSpan span = mock(AgentSpan.class); - VertxNormalizedRoute.tag( - span, "/users/:id", Grammar.DEFAULT, null, "/users/1", Collections.emptyMap()); + VertxNormalizedRoute.tag(span, "/users/:id", Grammar.DEFAULT, null, "/users/1", emptyMap()); // the tag is only set when NormalizedRouteHelper is enabled (see the forked test) verify(span).setTag(NORMALIZED_ROUTE_TAG, (String) null); @@ -100,10 +106,10 @@ void neverThrows() { assertDoesNotThrow(() -> VertxNormalizedRoute.tag( - span, "/users/:id", Grammar.DEFAULT, null, "/users/1", Collections.emptyMap())); + span, "/users/:id", Grammar.DEFAULT, null, "/users/1", emptyMap())); assertDoesNotThrow(() -> VertxNormalizedRoute.tag( - null, "/users/:id", Grammar.DEFAULT, null, "/users/1", Collections.emptyMap())); + null, "/users/:id", Grammar.DEFAULT, null, "/users/1", emptyMap())); } @Test diff --git a/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserCacheTest.java b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserCacheTest.java index a2e7b54912a..5f88166dbd4 100644 --- a/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserCacheTest.java +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserCacheTest.java @@ -40,6 +40,11 @@ void grammarsUseSeparateCaches() { assertNotSame(legacy, extended); assertSame(legacy, VertxRouteParser.cached("/t/:1abc", Grammar.LEGACY)); assertSame(current, VertxRouteParser.cached("/t/:1abc", Grammar.DEFAULT)); + assertSame(extended, VertxRouteParser.cached("/t/:1abc", Grammar.EXTENDED)); + assertNotSame(Grammar.LEGACY.cache(), Grammar.DEFAULT.cache()); + assertNotSame(Grammar.DEFAULT.cache(), Grammar.EXTENDED.cache()); + assertNotSame(Grammar.LEGACY.cache(), Grammar.EXTENDED.cache()); + assertSame(Grammar.LEGACY.cache(), Grammar.LEGACY.cache()); } @Test From cdfdce2ca6eb79f973a9e76fd9908a96d2e5023f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20Gonz=C3=A1lez=20Garc=C3=ADa?= Date: Fri, 27 Nov 2026 10:09:28 +0100 Subject: [PATCH 7/9] review: pre-PR checks - Test that path() followed by pathRegex() drops the declared path on Vert.x 4/5 - Skip the catch-all remainder for declared paths without a trailing '*' (root route) - Static-import NormalizedRouteHelper helpers and Grammar.LEGACY --- .../vertx_3_4/server/RouteHandlerWrapper.java | 4 ++-- .../AbstractVertxNormalizedRouteTest.java | 6 ++++++ .../VertxNormalizedRouteTest.java | 5 +++++ .../AbstractVertxNormalizedRouteTest.java | 6 ++++++ .../VertxNormalizedRouteTest.java | 5 +++++ .../api/appsec/route/VertxNormalizedRoute.java | 17 +++++++++-------- 6 files changed, 33 insertions(+), 10 deletions(-) diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerWrapper.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerWrapper.java index 657d98e7cc0..3ef2473c926 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerWrapper.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/main/java/datadog/trace/instrumentation/vertx_3_4/server/RouteHandlerWrapper.java @@ -1,5 +1,6 @@ package datadog.trace.instrumentation.vertx_3_4.server; +import static datadog.trace.api.appsec.route.VertxRouteParser.Grammar.LEGACY; import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activateSpan; import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activeSpan; import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.startSpan; @@ -10,7 +11,6 @@ import datadog.context.ContextScope; import datadog.trace.api.appsec.route.NormalizedRouteHelper; import datadog.trace.api.appsec.route.VertxNormalizedRoute; -import datadog.trace.api.appsec.route.VertxRouteParser; import datadog.trace.bootstrap.ContextStore; import datadog.trace.bootstrap.instrumentation.api.AgentSpan; import datadog.trace.bootstrap.instrumentation.api.Tags; @@ -132,7 +132,7 @@ private void tagNormalizedRoute(final RoutingContext routingContext, final Agent VertxNormalizedRoute.tag( span, declared, - VertxRouteParser.Grammar.LEGACY, + LEGACY, routingContext.mountPoint(), routingContext.normalisedPath(), routingContext.pathParams()); diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java index e437a02957c..2aeb7fcb14d 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java @@ -64,6 +64,12 @@ void startServer() throws Exception { // middleware with a declared path, then a regex route: the regex route must not keep its tag router.route("/stale/*").handler(RoutingContext::next); router.routeWithRegex("/stale/(\\d+)").handler(AbstractVertxNormalizedRouteTest::ok); + // path() then pathRegex() on the same route: the setRegex advice drops the declared path + router.route("/stale-path/*").handler(RoutingContext::next); + router + .route("/stale-path/x") + .pathRegex("/stale-path/(\\d+)") + .handler(AbstractVertxNormalizedRouteTest::ok); // what mountSubRouter("/sub/", sub) does on 4.x (mountSubRouter is gone in 5.x) Router sub = Router.router(vertx); diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/VertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/VertxNormalizedRouteTest.java index 3d09551bfb3..d62896b624a 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/VertxNormalizedRouteTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/VertxNormalizedRouteTest.java @@ -56,6 +56,11 @@ void staleNormalizedRouteIsClearedByLaterRegexRoute() throws Exception { * ({@code /acme/api/}), which holds a request value: no normalized route, {@code http.route} * unchanged. */ + @Test + void declaredPathIsDroppedByALaterPathRegex() throws Exception { + assertNoNormalizedRoute("/stale-path/1", "/stale-path/x"); + } + @Test void noNormalizedRouteUnderAParameterMount() throws Exception { assertNoNormalizedRoute("/acme/api/items/1", "/acme/api/items/:id"); diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java index e437a02957c..2aeb7fcb14d 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java @@ -64,6 +64,12 @@ void startServer() throws Exception { // middleware with a declared path, then a regex route: the regex route must not keep its tag router.route("/stale/*").handler(RoutingContext::next); router.routeWithRegex("/stale/(\\d+)").handler(AbstractVertxNormalizedRouteTest::ok); + // path() then pathRegex() on the same route: the setRegex advice drops the declared path + router.route("/stale-path/*").handler(RoutingContext::next); + router + .route("/stale-path/x") + .pathRegex("/stale-path/(\\d+)") + .handler(AbstractVertxNormalizedRouteTest::ok); // what mountSubRouter("/sub/", sub) does on 4.x (mountSubRouter is gone in 5.x) Router sub = Router.router(vertx); diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java index 3d09551bfb3..d62896b624a 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java @@ -56,6 +56,11 @@ void staleNormalizedRouteIsClearedByLaterRegexRoute() throws Exception { * ({@code /acme/api/}), which holds a request value: no normalized route, {@code http.route} * unchanged. */ + @Test + void declaredPathIsDroppedByALaterPathRegex() throws Exception { + assertNoNormalizedRoute("/stale-path/1", "/stale-path/x"); + } + @Test void noNormalizedRouteUnderAParameterMount() throws Exception { assertNoNormalizedRoute("/acme/api/items/1", "/acme/api/items/:id"); diff --git a/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxNormalizedRoute.java b/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxNormalizedRoute.java index a20691aa3f9..e4911dabadc 100644 --- a/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxNormalizedRoute.java +++ b/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxNormalizedRoute.java @@ -1,5 +1,8 @@ package datadog.trace.api.appsec.route; +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.decodePath; + import datadog.trace.api.appsec.route.VertxRouteParser.Grammar; import datadog.trace.api.internal.VisibleForTesting; import datadog.trace.bootstrap.instrumentation.api.AgentSpan; @@ -74,7 +77,7 @@ public static void tag( } try { // a later route that cannot be expressed must not keep the tag of an earlier one - span.setTag(NormalizedRouteHelper.NORMALIZED_ROUTE_TAG, (String) null); + span.setTag(NORMALIZED_ROUTE_TAG, (String) null); RouteTemplate template = template(declaredPath, grammar, mountPoint, pathParams); if (template == null) { return; @@ -82,8 +85,7 @@ public static void tag( PresenceResolver resolver = resolver(template, declaredPath, grammar, mountPoint, normalizedPath); if (resolver != null) { - NormalizedRouteHelper.tag( - span, template, NormalizedRouteHelper.decodePath(mountPoint), resolver); + NormalizedRouteHelper.tag(span, template, decodePath(mountPoint), resolver); } } catch (Throwable t) { log.debug("Failed to set the Vert.x normalized route tag", t); @@ -104,9 +106,7 @@ static String render( } PresenceResolver resolver = resolver(template, declaredPath, grammar, mountPoint, normalizedPath); - return resolver == null - ? null - : template.render(NormalizedRouteHelper.decodePath(mountPoint), resolver); + return resolver == null ? null : template.render(decodePath(mountPoint), resolver); } /** @@ -164,8 +164,9 @@ private static PresenceResolver resolver( Grammar grammar, String mountPoint, String normalizedPath) { - // the trailing '*' is the only optional part of a Vert.x template - if (template.staticRoute() != null) { + // the trailing '*' is the only optional part of a Vert.x template; the root route also has + // no static route (empty body) but no catch-all either + if (template.staticRoute() != null || !declaredPath.endsWith("*")) { return PresenceResolver.UNKNOWN; } int start = remainderStart(declaredPath, grammar, mountPoint, normalizedPath); From f99f86a69a0a3ed47d7167b04b8dba8d486cb4d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20Gonz=C3=A1lez=20Garc=C3=ADa?= Date: Fri, 27 Nov 2026 21:52:16 +0100 Subject: [PATCH 8/9] Test that Vert.x rejects parameter mounts reusing a child param name --- .../AbstractVertxNormalizedRouteTest.java | 2 +- .../VertxNormalizedRouteTest.java | 15 +++++++++++++ .../AbstractVertxNormalizedRouteTest.java | 2 +- .../VertxNormalizedRouteTest.java | 21 +++++++++++++++++++ .../AbstractVertxNormalizedRouteTest.java | 2 +- .../VertxNormalizedRouteTest.java | 21 +++++++++++++++++++ 6 files changed, 60 insertions(+), 3 deletions(-) diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java index d3e5d6f6813..889ea3ad13b 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java @@ -46,7 +46,7 @@ abstract class AbstractVertxNormalizedRouteTest extends AbstractInstrumentationT private static final String SERVER_SPAN = "netty.request"; private final OkHttpClient client = OkHttpUtils.client(); - private Vertx vertx; + Vertx vertx; private HttpServer server; private int port; private boolean appSecActiveBefore; diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java index 48381708d30..3686a4d6468 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java @@ -4,9 +4,11 @@ import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assumptions.assumeTrue; import datadog.trace.bootstrap.ActiveSubsystems; +import io.vertx.ext.web.Router; import java.util.Map; import org.junit.jupiter.api.Test; import org.tabletest.junit.TableTest; @@ -60,6 +62,19 @@ void noNormalizedRouteWhenAppSecIsInactive() throws Exception { * prefix ({@code /acme/api}), which holds a request value: no normalized route, {@code * http.route} unchanged. */ + /** + * A parameter mount can never reuse a child param name: Vert.x 3.4 rejects patterns in mounts and + * 3.8.2+ rejects the repeated identifier, so the mount-param check always sees a foreign key. + */ + @Test + void vertxRejectsAParameterMountReusingAChildParamName() { + Router child = Router.router(vertx); + child.route("/items/:id").handler(ctx -> ctx.response().end()); + + assertThrows( + RuntimeException.class, () -> Router.router(vertx).mountSubRouter("/:id/api", child)); + } + @Test void noNormalizedRouteUnderAParameterMount() throws Exception { assumeTrue(paramMountSupported(), "this Vert.x version rejects patterns in sub-router mounts"); diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java index 2aeb7fcb14d..97d7fc5e35d 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java @@ -45,7 +45,7 @@ abstract class AbstractVertxNormalizedRouteTest extends AbstractInstrumentationT private static final String SERVER_SPAN = "netty.request"; private final OkHttpClient client = OkHttpUtils.client(); - private Vertx vertx; + Vertx vertx; private HttpServer server; private int port; private boolean appSecActiveBefore; diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/VertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/VertxNormalizedRouteTest.java index d62896b624a..f03083e6fd0 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/VertxNormalizedRouteTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/VertxNormalizedRouteTest.java @@ -4,8 +4,10 @@ import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import datadog.trace.bootstrap.ActiveSubsystems; +import io.vertx.ext.web.Router; import java.util.Map; import org.junit.jupiter.api.Test; import org.tabletest.junit.TableTest; @@ -61,6 +63,25 @@ void declaredPathIsDroppedByALaterPathRegex() throws Exception { assertNoNormalizedRoute("/stale-path/1", "/stale-path/x"); } + /** + * A parameter mount can never reuse a child param name: Vert.x rejects the repeated identifier + * when mounting and when a route is added later, so the mount-param check always sees a foreign + * key. + */ + @Test + void vertxRejectsAParameterMountReusingAChildParamName() { + Router child = Router.router(vertx); + child.route("/items/:id").handler(ctx -> ctx.response().end()); + assertThrows( + RuntimeException.class, () -> Router.router(vertx).route("/:id/api/*").subRouter(child)); + + Router laterChild = Router.router(vertx); + Router.router(vertx).route("/:id/api/*").subRouter(laterChild); + assertThrows( + RuntimeException.class, + () -> laterChild.route("/items/:id").handler(ctx -> ctx.response().end())); + } + @Test void noNormalizedRouteUnderAParameterMount() throws Exception { assertNoNormalizedRoute("/acme/api/items/1", "/acme/api/items/:id"); diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java index 2aeb7fcb14d..97d7fc5e35d 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java @@ -45,7 +45,7 @@ abstract class AbstractVertxNormalizedRouteTest extends AbstractInstrumentationT private static final String SERVER_SPAN = "netty.request"; private final OkHttpClient client = OkHttpUtils.client(); - private Vertx vertx; + Vertx vertx; private HttpServer server; private int port; private boolean appSecActiveBefore; diff --git a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java index d62896b624a..f03083e6fd0 100644 --- a/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java @@ -4,8 +4,10 @@ import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import datadog.trace.bootstrap.ActiveSubsystems; +import io.vertx.ext.web.Router; import java.util.Map; import org.junit.jupiter.api.Test; import org.tabletest.junit.TableTest; @@ -61,6 +63,25 @@ void declaredPathIsDroppedByALaterPathRegex() throws Exception { assertNoNormalizedRoute("/stale-path/1", "/stale-path/x"); } + /** + * A parameter mount can never reuse a child param name: Vert.x rejects the repeated identifier + * when mounting and when a route is added later, so the mount-param check always sees a foreign + * key. + */ + @Test + void vertxRejectsAParameterMountReusingAChildParamName() { + Router child = Router.router(vertx); + child.route("/items/:id").handler(ctx -> ctx.response().end()); + assertThrows( + RuntimeException.class, () -> Router.router(vertx).route("/:id/api/*").subRouter(child)); + + Router laterChild = Router.router(vertx); + Router.router(vertx).route("/:id/api/*").subRouter(laterChild); + assertThrows( + RuntimeException.class, + () -> laterChild.route("/items/:id").handler(ctx -> ctx.response().end())); + } + @Test void noNormalizedRouteUnderAParameterMount() throws Exception { assertNoNormalizedRoute("/acme/api/items/1", "/acme/api/items/:id"); From 7964e1e3f4c68af96c04372357d5bf4f8333b8c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20Gonz=C3=A1lez=20Garc=C3=ADa?= Date: Fri, 27 Nov 2026 22:20:12 +0100 Subject: [PATCH 9/9] Skip the normalized route under a Vert.x mount with an encoded slash --- .../appsec/route/VertxNormalizedRoute.java | 22 +++++++++++++++++-- .../route/VertxNormalizedRouteTest.java | 7 +++++- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxNormalizedRoute.java b/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxNormalizedRoute.java index e4911dabadc..dfa98f7e04d 100644 --- a/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxNormalizedRoute.java +++ b/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxNormalizedRoute.java @@ -128,12 +128,14 @@ static Grammar vertx4Grammar(boolean extendedPattern) { * point holds request values. A mount with parameters returns the concrete matched prefix and * shares its {@code pathParams()} with the sub-router, so a bound parameter that the route does * not declare means a parameter mount (conservative: a middleware route may also have left it). A - * root mount ({@code /}) never holds request values, so it skips that check. + * root mount ({@code /}) never holds request values, so it skips that check. A mount point with + * an encoded {@code /} gives no tag either: the prefix is rendered decoded, which would turn it + * into a separator. */ private static RouteTemplate template( String declaredPath, Grammar grammar, String mountPoint, Map pathParams) { RouteTemplate template = VertxRouteParser.cached(declaredPath, grammar); - if (!template.isExpressible()) { + if (!template.isExpressible() || hasEncodedSlash(mountPoint)) { return null; } if (pathParams != null && !isRootMount(mountPoint)) { @@ -147,6 +149,22 @@ private static RouteTemplate template( return template; } + /** Whether the mount point holds {@code %2F} (any case), which Vert.x matches as a literal. */ + private static boolean hasEncodedSlash(String mountPoint) { + if (mountPoint == null) { + return false; + } + for (int i = mountPoint.indexOf('%'); + i >= 0 && i + 2 < mountPoint.length(); + i = mountPoint.indexOf('%', i + 1)) { + char c = mountPoint.charAt(i + 2); + if (mountPoint.charAt(i + 1) == '2' && (c == 'F' || c == 'f')) { + return true; + } + } + return false; + } + /** Whether there is no mount, or the mount is {@code /} (empty once its trailing '/' is gone). */ private static boolean isRootMount(String mountPoint) { return mountPoint == null diff --git a/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteTest.java b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteTest.java index c3749e21105..86dd0772199 100644 --- a/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteTest.java +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteTest.java @@ -77,7 +77,12 @@ class VertxNormalizedRouteTest { "same params with empty mount | '/users/:id' | DEFAULT | '' | '/users/1' | [tenant: acme, id: '1'] | '/users/{id}' ", "same params with root mount | '/users/:id' | DEFAULT | '/' | '/users/1' | [tenant: acme, id: '1'] | '/users/{id}' ", "mount: rest param ignored | '/users/:id' | DEFAULT | '/sub/' | '/sub/users/1' | [id: '1', '*': x] | '/sub/users/{id}' ", - "mount: no params | '/users/:id' | DEFAULT | '/sub/' | '/sub/users/1' | | '/sub/users/{id}' " + "mount: no params | '/users/:id' | DEFAULT | '/sub/' | '/sub/users/1' | | '/sub/users/{id}' ", + "mount: encoded slash | '/users/:id' | DEFAULT | '/a%2Fb/' | '/a%2Fb/users/1' | | ", + "mount: encoded slash, lower case | '/users/:id' | DEFAULT | '/a%2fb/' | '/a%2fb/users/1' | | ", + "mount: other escape kept | '/users/:id' | DEFAULT | '/a%20b/' | '/a%20b/users/1' | | '/a%20b/users/{id}' ", + "mount: unreserved escape | '/users/:id' | DEFAULT | '/a%41b/' | '/aAb/users/1' | | '/aAb/users/{id}' ", + "mount: trailing percent | '/users/:id' | DEFAULT | '/a%2' | '/a%2/users/1' | | '/a%252/users/{id}' " }) void rendersTheNormalizedRoute( String declared,