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..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 @@ -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,11 @@ 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(String.class)), + packageName + ".RouteSetPathAdvice"); + transformer.applyAdvice( + 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 7af44b78e9d..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; @@ -8,14 +9,22 @@ 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.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. */ + 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,24 @@ 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.get(routingContext.currentRoute()); + VertxNormalizedRoute.tag( + span, + declared, + 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/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-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..889ea3ad13b --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java @@ -0,0 +1,187 @@ +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.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +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 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(); + Vertx vertx; + private HttpServer server; + private int port; + private boolean appSecActiveBefore; + private boolean paramMountSupported; + + @BeforeAll + void startServer() throws Exception { + 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); + + // 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) { + AbstractVertxNormalizedRouteTest.await(server::close); + } + if (vertx != null) { + AbstractVertxNormalizedRouteTest.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"); + } + + /** + * 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(); + try (Response response = client.newCall(request).execute()) { + return response.code(); + } + } + + /** 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 (SERVER_SPAN.equals(span.getOperationName().toString())) { + serverSpan = 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 new file mode 100644 index 00000000000..0cdebbd2602 --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/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-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..3686a4d6468 --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-3.4/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java @@ -0,0 +1,117 @@ +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 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; + +/** Normalized route of Vert.x 3.x routes, top level and under {@code mountSubRouter("/sub")}. */ +class VertxNormalizedRouteTest extends AbstractVertxNormalizedRouteTest { + + @TableTest({ + "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/' ", + "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 httpRoute, String normalized) throws Exception { + assertEquals(200, get(request)); + Map tags = serverSpanTags(); + + assertEquals(httpRoute, String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals(normalized, String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } + + @Test + void noNormalizedRouteForRegexRoute() throws Exception { + 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 { + assertNoNormalizedRoute("/stale-path/1", "/stale-path/x"); + } + + @Test + void noNormalizedRouteWhenAppSecIsInactive() throws Exception { + ActiveSubsystems.APPSEC_ACTIVE = false; + + 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. + */ + /** + * 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"); + + assertNoNormalizedRoute("/acme/api/items/1", "/acme/api/items/:id"); + } + + /** + * {@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))); + } +} 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/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/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..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 @@ -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,11 @@ 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(String.class)), + packageName + ".RouteSetPathAdvice"); + transformer.applyAdvice( + 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 28e79e35a27..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 @@ -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. */ + 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,24 @@ 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.get(routingContext.currentRoute()); + 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/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-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 new file mode 100644 index 00000000000..97d7fc5e35d --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java @@ -0,0 +1,169 @@ +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.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.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CountDownLatch; +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 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(); + Vertx vertx; + private HttpServer server; + private int port; + private boolean appSecActiveBefore; + + @BeforeAll + void startServer() throws Exception { + 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); + // 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); + 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(0)); + port = server.actualPort(); + } + + @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(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(); + } + + /** 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 {@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 (SERVER_SPAN.equals(span.getOperationName().toString())) { + serverSpan = 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/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 new file mode 100644 index 00000000000..f03083e6fd0 --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-4.0/src/testNormalizedRoute/java/server/normalizedroute/VertxNormalizedRouteTest.java @@ -0,0 +1,115 @@ +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 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; + +/** 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 | 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/' ", + "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 httpRoute, String normalized) throws Exception { + assertEquals(200, get(request)); + Map tags = serverSpanTags(); + + assertEquals(httpRoute, String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals(normalized, 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 { + assertNoNormalizedRoute("/regex/123", "/regex/(\\d+)"); + } + + /** + * 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 { + assertNoNormalizedRoute("/stale/1", "/stale/(\\d+)"); + } + + /** + * 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 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"); + } + + @Test + void noNormalizedRouteWhenAppSecIsInactive() throws Exception { + ActiveSubsystems.APPSEC_ACTIVE = false; + + assertNoNormalizedRoute("/multi/1.json", "/multi/:id.:format"); + } + + /** + * {@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/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) { 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..97d7fc5e35d --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/AbstractVertxNormalizedRouteTest.java @@ -0,0 +1,169 @@ +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.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.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CountDownLatch; +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 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(); + Vertx vertx; + private HttpServer server; + private int port; + private boolean appSecActiveBefore; + + @BeforeAll + void startServer() throws Exception { + 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); + // 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); + 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(0)); + port = server.actualPort(); + } + + @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(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(); + } + + /** 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 {@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 (SERVER_SPAN.equals(span.getOperationName().toString())) { + serverSpan = 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 new file mode 100644 index 00000000000..0cdebbd2602 --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/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-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..f03083e6fd0 --- /dev/null +++ b/dd-java-agent/instrumentation/vertx/vertx-web/vertx-web-5.0/src/test/java/server/normalizedroute/VertxNormalizedRouteTest.java @@ -0,0 +1,115 @@ +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 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; + +/** 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 | 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/' ", + "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 httpRoute, String normalized) throws Exception { + assertEquals(200, get(request)); + Map tags = serverSpanTags(); + + assertEquals(httpRoute, String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals(normalized, 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 { + assertNoNormalizedRoute("/regex/123", "/regex/(\\d+)"); + } + + /** + * 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 { + assertNoNormalizedRoute("/stale/1", "/stale/(\\d+)"); + } + + /** + * 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 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"); + } + + @Test + void noNormalizedRouteWhenAppSecIsInactive() throws Exception { + ActiveSubsystems.APPSEC_ACTIVE = false; + + assertNoNormalizedRoute("/multi/1.json", "/multi/:id.:format"); + } + + /** + * {@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/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..dfa98f7e04d --- /dev/null +++ b/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxNormalizedRoute.java @@ -0,0 +1,370 @@ +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; +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+. */ + 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; + + 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(NORMALIZED_ROUTE_TAG, (String) null); + RouteTemplate template = template(declaredPath, grammar, mountPoint, pathParams); + if (template == null) { + return; + } + PresenceResolver resolver = + resolver(template, declaredPath, grammar, mountPoint, normalizedPath); + if (resolver != null) { + NormalizedRouteHelper.tag(span, template, decodePath(mountPoint), resolver); + } + } 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; + } + PresenceResolver resolver = + resolver(template, declaredPath, grammar, mountPoint, normalizedPath); + return resolver == null ? null : template.render(decodePath(mountPoint), resolver); + } + + /** + * 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). A + * 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() || hasEncodedSlash(mountPoint)) { + return null; + } + if (pathParams != null && !isRootMount(mountPoint)) { + for (String name : pathParams.keySet()) { + if (!REST_PARAM.equals(name) + && !VertxRouteParser.declaresParam(declaredPath, name, grammar)) { + return null; + } + } + } + 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 + || mountPoint.isEmpty() + || (mountPoint.length() == 1 && mountPoint.charAt(0) == '/'); + } + + /** + * 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, + String declaredPath, + Grammar grammar, + String mountPoint, + String normalizedPath) { + // 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); + 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. */ + @VisibleForTesting + static PresenceResolver catchAllResolver(RoutePresence presence) { + return CATCH_ALL_RESOLVERS[presence.ordinal()]; + } + + /** + * 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 + * 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 UNKNOWN_REMAINDER; + } + 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 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 UNKNOWN_REMAINDER; + } + start = mountLength + baseEnd; + } else { + start = + skipSegments(declaredPath, baseEnd, wholeSegment, grammar, normalizedPath, mountLength); + if (start < 0) { + return UNKNOWN_REMAINDER; + } + } + if (wholeSegment && start < normalizedPath.length() && normalizedPath.charAt(start) != '/') { + // "/a/*" never matches "/ab" by itself; a mount without trailing '/' can make it match + return NOT_A_SEGMENT_BOUNDARY; + } + 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) { + // invariant: every declared segment starts with '/' (parse rejects relative 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 new file mode 100644 index 00000000000..af358fdf04c --- /dev/null +++ b/internal-api/src/main/java/datadog/trace/api/appsec/route/VertxRouteParser.java @@ -0,0 +1,297 @@ +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: + * + *
    + *
  • {@code :name}: parameter; the name ends at the first char outside the {@link Grammar} name + * class, so a segment may hold several ({@code /:id.:format}, {@code /:a-:b}). A {@code :} + * not followed by a valid first char is static text; + *
  • a trailing {@code *}: unnamed catch-all, a whole segment after {@code /} ({@code /a/*}) or + * the end of the last segment ({@code /img*}); + *
  • everything else: static text, percent-decoded (Vert.x matches the encoded request path). + *
+ * + * 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 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; + } + 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() {} + + /** 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. + */ + 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 compiledToRegex = 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 (compiledToRegex && isRegexOperator(c)) { + return RouteTemplate.NOT_EXPRESSIBLE; + } else { + 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++; + } + } + } + flushLiteral(declaredPath, literalStart, end, 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(); + } + + /** + * 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 > 0 && 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) { + 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/VertxNormalizedRouteForkedTest.java b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteForkedTest.java new file mode 100644 index 00000000000..01e9b6aa41b --- /dev/null +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteForkedTest.java @@ -0,0 +1,75 @@ +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 java.util.Collections.singletonMap; +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.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 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", 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}"); + } + + @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()); + } + + 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..86dd0772199 --- /dev/null +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxNormalizedRouteTest.java @@ -0,0 +1,137 @@ +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; +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.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' | [:] | '/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}' ", + "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' ", + "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'] | '/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}' ", + "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: 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, + Grammar grammar, + String mount, + String path, + Map params, + String normalized) { + assertEquals(normalized, VertxNormalizedRoute.render(declared, grammar, mount, path, params)); + } + + @Test + void clearsTheTagEvenWhenDisabled() { + AgentSpan span = mock(AgentSpan.class); + + 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); + } + + @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", emptyMap())); + assertDoesNotThrow(() -> + VertxNormalizedRoute.tag( + null, "/users/:id", Grammar.DEFAULT, null, "/users/1", 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/VertxRouteParserCacheTest.java b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserCacheTest.java new file mode 100644 index 00000000000..5f88166dbd4 --- /dev/null +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserCacheTest.java @@ -0,0 +1,128 @@ +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)); + 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 + 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..5114ea79369 --- /dev/null +++ b/internal-api/src/test/java/datadog/trace/api/appsec/route/VertxRouteParserTest.java @@ -0,0 +1,192 @@ +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()); + } + + @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( + "/sub/users/{id}", + VertxRouteParser.parse("/users/:id", Grammar.DEFAULT).render("/sub/", null)); + } +}