From 6a3ef45cd817d65ab8edff382d2f7e72a0a2b5b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20Gonz=C3=A1lez=20Garc=C3=ADa?= Date: Thu, 26 Nov 2026 16:30:07 +0100 Subject: [PATCH 1/2] Tag JAX-RS server spans with the normalized route Capture the mount prefix and bound path values in Jersey (UriRoutingContext.setMatchedResourceMethod) and RESTEasy (ResourceMethodInvoker.invoke), and set _dd.appsec.normalized_route next to http.route in the jax-rs 2 and jakarta-rs 3 decorators. Dropwizard and new Jetty servlet tests for Jersey and RESTEasy cover the tag end to end. --- .../dropwizard/dropwizard-0.8/build.gradle | 2 + .../src/test/groovy/DropwizardTest.groovy | 6 + .../jersey-appsec-2.0/build.gradle | 14 + .../jersey2/JaxRsRequestMatchCapture.java | 52 ++++ ...UriRoutingContextMatchInstrumentation.java | 59 +++++ .../AbstractJerseyNormalizedRouteTest.java | 94 +++++++ ...zedRouteApiSecurityDisabledForkedTest.java | 24 ++ ...ormalizedRouteNoRouteNamingForkedTest.java | 34 +++ .../JerseyNormalizedRouteTest.java | 60 +++++ .../NormalizedRouteResource.java | 69 +++++ .../resteasy/resteasy-appsec-3.0/build.gradle | 8 +- .../resteasy/JaxRsRequestMatchCapture.java | 52 ++++ .../ResourceMethodInvokerInstrumentation.java | 62 +++++ .../AbstractResteasyNormalizedRouteTest.java | 98 +++++++ .../NormalizedRouteResource.java | 69 +++++ ...zedRouteApiSecurityDisabledForkedTest.java | 25 ++ ...ormalizedRouteNoRouteNamingForkedTest.java | 34 +++ .../ResteasyNormalizedRouteTest.java | 73 +++++ .../JakartaRsAnnotationsDecorator.java | 67 +++++ .../JakartaRsNormalizedRouteTest.java | 249 ++++++++++++++++++ .../jaxrs2/JaxRsAnnotationsDecorator.java | 70 ++++- .../jaxrs2/JaxRsAnnotationsDecoratorTest.java | 230 ++++++++++++++++ 22 files changed, 1447 insertions(+), 4 deletions(-) create mode 100644 dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/main/java/datadog/trace/instrumentation/jersey2/JaxRsRequestMatchCapture.java create mode 100644 dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/main/java/datadog/trace/instrumentation/jersey2/UriRoutingContextMatchInstrumentation.java create mode 100644 dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/AbstractJerseyNormalizedRouteTest.java create mode 100644 dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/JerseyNormalizedRouteApiSecurityDisabledForkedTest.java create mode 100644 dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/JerseyNormalizedRouteNoRouteNamingForkedTest.java create mode 100644 dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/JerseyNormalizedRouteTest.java create mode 100644 dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/NormalizedRouteResource.java create mode 100644 dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/main/java/datadog/trace/instrumentation/resteasy/JaxRsRequestMatchCapture.java create mode 100644 dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/main/java/datadog/trace/instrumentation/resteasy/ResourceMethodInvokerInstrumentation.java create mode 100644 dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/AbstractResteasyNormalizedRouteTest.java create mode 100644 dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/NormalizedRouteResource.java create mode 100644 dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/ResteasyNormalizedRouteApiSecurityDisabledForkedTest.java create mode 100644 dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/ResteasyNormalizedRouteNoRouteNamingForkedTest.java create mode 100644 dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/ResteasyNormalizedRouteTest.java create mode 100644 dd-java-agent/instrumentation/rs/jakarta-rs-annotations-3.0/src/test/java/datadog/trace/instrumentation/jakarta3/JakartaRsNormalizedRouteTest.java diff --git a/dd-java-agent/instrumentation/dropwizard/dropwizard-0.8/build.gradle b/dd-java-agent/instrumentation/dropwizard/dropwizard-0.8/build.gradle index 5f45383db8d..89ecd2ca3d5 100644 --- a/dd-java-agent/instrumentation/dropwizard/dropwizard-0.8/build.gradle +++ b/dd-java-agent/instrumentation/dropwizard/dropwizard-0.8/build.gradle @@ -7,6 +7,8 @@ plugins { dependencies { testImplementation project(':dd-java-agent:instrumentation:rs:jax-rs:jax-rs-annotations:jax-rs-annotations-2.0') testImplementation project(':dd-java-agent:instrumentation:servlet:javax-servlet:javax-servlet-3.0') + // Captures the Jersey request match for _dd.appsec.normalized_route + testImplementation project(':dd-java-agent:instrumentation:jersey:jersey-appsec:jersey-appsec-2.0') // Dropwizard 0.8 transitively depends on Jetty 9.2.9, so load the jetty-server // instrumentation modules whose muzzle ranges cover that version, matching the // production classpath: diff --git a/dd-java-agent/instrumentation/dropwizard/dropwizard-0.8/src/test/groovy/DropwizardTest.groovy b/dd-java-agent/instrumentation/dropwizard/dropwizard-0.8/src/test/groovy/DropwizardTest.groovy index 5361c91abfd..d2ecb9221f7 100644 --- a/dd-java-agent/instrumentation/dropwizard/dropwizard-0.8/src/test/groovy/DropwizardTest.groovy +++ b/dd-java-agent/instrumentation/dropwizard/dropwizard-0.8/src/test/groovy/DropwizardTest.groovy @@ -93,6 +93,12 @@ class DropwizardTest extends HttpServerTest { return "/${endpoint.relativeRawPath()}" } + @Override + Serializable expectedNormalizedRoute(ServerEndpoint endpoint) { + // Jersey servlet mounted at the root: no prefix; the %20 escape of the @Path literal is kept + return normalizedRouteOf('', expectedServerSpanRoute(endpoint)) + } + @Override String expectedIntegrationName() { // In production, Jetty's server instrumentation creates the request span before Servlet3 diff --git a/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/build.gradle b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/build.gradle index 41fba61a7b9..0f7a315c2ef 100644 --- a/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/build.gradle +++ b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/build.gradle @@ -17,6 +17,13 @@ muzzle { versions = '[2,3)' assertInverse = true } + pass { + name = 'jersey_server_2+3' + group = 'org.glassfish.jersey.core' + module = 'jersey-server' + versions = '[2,)' + assertInverse = true + } pass { name = 'jersey_2+3' group = 'org.glassfish.jersey.core' @@ -43,6 +50,13 @@ dependencies { compileOnly group: 'org.glassfish.jersey.media', name: 'jersey-media-multipart', version: '2.0' testImplementation group: 'org.glassfish.jersey.media', name: 'jersey-media-multipart', version: '2.18' + + // Normalized route tests: Jersey servlet on Jetty, server span from jetty-server-7.6 + testImplementation group: 'org.glassfish.jersey.containers', name: 'jersey-container-servlet-core', version: '2.18' + testImplementation group: 'org.eclipse.jetty', name: 'jetty-server', version: '8.2.0.v20160908' + testImplementation group: 'org.eclipse.jetty', name: 'jetty-servlet', version: '8.2.0.v20160908' + testImplementation project(':dd-java-agent:instrumentation:jetty:jetty-server:jetty-server-7.6') + testImplementation project(':dd-java-agent:instrumentation:rs:jax-rs:jax-rs-annotations:jax-rs-annotations-2.0') } // tested in grizzly-http-2.3.20 diff --git a/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/main/java/datadog/trace/instrumentation/jersey2/JaxRsRequestMatchCapture.java b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/main/java/datadog/trace/instrumentation/jersey2/JaxRsRequestMatchCapture.java new file mode 100644 index 00000000000..9e92f5a1cc0 --- /dev/null +++ b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/main/java/datadog/trace/instrumentation/jersey2/JaxRsRequestMatchCapture.java @@ -0,0 +1,52 @@ +package datadog.trace.instrumentation.jersey2; + +import static datadog.trace.api.telemetry.LogCollector.EXCLUDE_TELEMETRY; +import static datadog.trace.bootstrap.ContextStores.getContextStore; +import static datadog.trace.bootstrap.ContextStores.getContextStoreId; +import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activeSpan; + +import datadog.trace.api.appsec.route.JaxRsRequestMatch; +import datadog.trace.bootstrap.ContextStore; +import datadog.trace.bootstrap.instrumentation.api.AgentSpan; +import java.net.URI; +import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Stores what Jersey matched for the current request under the local root span, where the JAX-RS + * annotations decorators read it to tag {@code _dd.appsec.normalized_route}. The store id must + * match the one the decorators use. + */ +public final class JaxRsRequestMatchCapture { + + private static final Logger log = LoggerFactory.getLogger(JaxRsRequestMatchCapture.class); + + private static final ContextStore REQUEST_MATCHES = + getContextStore( + getContextStoreId(AgentSpan.class.getName(), JaxRsRequestMatch.class.getName())); + + private JaxRsRequestMatchCapture() {} + + /** + * Stores nothing when the base URI or its raw path is unknown (no prefix, so no tag; an empty + * path is the root prefix), or when a sub-resource locator already marked the request with {@link + * JaxRsRequestMatch#SUBRESOURCE}. + * + * @param baseUri the request's base URI (what Jersey served before the matched path), or null + * @param boundValues the path parameters Jersey bound, by name + */ + public static void capture(URI baseUri, Map boundValues) { + try { + String rawBasePath = baseUri == null ? null : baseUri.getRawPath(); + AgentSpan span = rawBasePath == null ? null : activeSpan(); + AgentSpan localRoot = span == null ? null : span.getLocalRootSpan(); + if (localRoot == null || REQUEST_MATCHES.get(localRoot) == JaxRsRequestMatch.SUBRESOURCE) { + return; + } + REQUEST_MATCHES.put(localRoot, JaxRsRequestMatch.of(rawBasePath, boundValues)); + } catch (Throwable t) { + log.debug(EXCLUDE_TELEMETRY, "Failed to capture the JAX-RS request match", t); + } + } +} diff --git a/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/main/java/datadog/trace/instrumentation/jersey2/UriRoutingContextMatchInstrumentation.java b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/main/java/datadog/trace/instrumentation/jersey2/UriRoutingContextMatchInstrumentation.java new file mode 100644 index 00000000000..9dd8cd79619 --- /dev/null +++ b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/main/java/datadog/trace/instrumentation/jersey2/UriRoutingContextMatchInstrumentation.java @@ -0,0 +1,59 @@ +package datadog.trace.instrumentation.jersey2; + +import static datadog.trace.agent.tooling.bytebuddy.matcher.NameMatchers.named; +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.api.appsec.route.NormalizedRouteHelper; +import java.util.Map; +import net.bytebuddy.asm.Advice; +import org.glassfish.jersey.server.internal.routing.UriRoutingContext; + +/** + * Captures the base URI and the bound path parameters once Jersey (2 and 3) has matched the + * resource method, for {@code _dd.appsec.normalized_route}. Reads the {@code encodedTemplateValues} + * field rather than calling {@code getPathParameters}, which {@link + * UriRoutingContextInstrumentation} hooks to run the WAF. + */ +@AutoService(InstrumenterModule.class) +public class UriRoutingContextMatchInstrumentation extends InstrumenterModule.AppSec + implements Instrumenter.ForSingleType, Instrumenter.HasMethodAdvice { + public UriRoutingContextMatchInstrumentation() { + super("jersey"); + } + + @Override + public String muzzleDirective() { + return "jersey_server_2+3"; + } + + @Override + public String instrumentedType() { + return "org.glassfish.jersey.server.internal.routing.UriRoutingContext"; + } + + @Override + public void methodAdvice(MethodTransformer transformer) { + transformer.applyAdvice( + named("setMatchedResourceMethod").and(takesArguments(1)), + getClass().getName() + "$SetMatchedResourceMethodAdvice"); + } + + public static class SetMatchedResourceMethodAdvice { + @Advice.OnMethodExit(suppress = Throwable.class) + static void after( + @Advice.This final UriRoutingContext thiz, + @Advice.FieldValue("encodedTemplateValues") final Map encodedTemplateValues) { + if (!NormalizedRouteHelper.isEnabled()) { + return; + } + // The private field encodedTemplateValues is read because getPathParameters runs the WAF. + // It is stable from Jersey 2.0 to 4.0 (checked with javap), but muzzle does not validate + // field names: recheck it when a new Jersey major is supported. + // It is a javax (2.x) or jakarta (3.x+) MultivaluedHashMap: read it as a Map. + JaxRsRequestMatchCapture.capture(thiz.getBaseUri(), encodedTemplateValues); + } + } +} diff --git a/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/AbstractJerseyNormalizedRouteTest.java b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/AbstractJerseyNormalizedRouteTest.java new file mode 100644 index 00000000000..6edbf9aede7 --- /dev/null +++ b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/AbstractJerseyNormalizedRouteTest.java @@ -0,0 +1,94 @@ +package normalizedroute; + +import static org.junit.jupiter.api.Assertions.assertEquals; +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 java.util.List; +import java.util.Map; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.nio.SelectChannelConnector; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.glassfish.jersey.server.ServerProperties; +import org.glassfish.jersey.servlet.ServletContainer; +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; + +/** + * Serves {@link NormalizedRouteResource} with Jersey 2 in a Jetty servlet container ({@code /ctx} + * context path, {@code /api/*} servlet mapping), with AppSec forced active like the Spock {@code + * InstrumentationSpecification}, and returns the tags of the server span of a request. + */ +@TestInstance(PER_CLASS) +abstract class AbstractJerseyNormalizedRouteTest extends AbstractInstrumentationTest { + + static final String PREFIX = "/ctx/api"; + + private final OkHttpClient client = OkHttpUtils.client(); + private Server server; + private int port; + private boolean appSecActiveBefore; + + @BeforeAll + void startServer() throws Exception { + server = new Server(); + SelectChannelConnector connector = new SelectChannelConnector(); + connector.setPort(0); + server.addConnector(connector); + ServletContextHandler context = new ServletContextHandler(); + context.setContextPath("/ctx"); + ServletHolder holder = new ServletHolder(new ServletContainer()); + holder.setInitParameter( + ServerProperties.PROVIDER_CLASSNAMES, NormalizedRouteResource.class.getName()); + context.addServlet(holder, "/api/*"); + server.setHandler(context); + server.start(); + port = connector.getLocalPort(); + } + + @AfterAll + void stopServer() throws Exception { + if (server != null) { + server.stop(); + } + } + + @BeforeEach + void forceAppSecActive() { + appSecActiveBefore = ActiveSubsystems.APPSEC_ACTIVE; + ActiveSubsystems.APPSEC_ACTIVE = true; + } + + @AfterEach + void restoreAppSecActive() { + ActiveSubsystems.APPSEC_ACTIVE = appSecActiveBefore; + } + + /** Sends {@code GET PREFIX + path}, expects a 200 and returns the tags of the server span. */ + Map serverSpanTags(String path) throws Exception { + Request request = + new Request.Builder().url("http://localhost:" + port + PREFIX + path).get().build(); + try (Response response = client.newCall(request).execute()) { + assertEquals(200, response.code()); + } + writer.waitForTraces(1); + for (List trace : writer) { + for (DDSpan span : trace) { + if (span.isLocalRootSpan()) { + return span.getTags(); + } + } + } + throw new AssertionError("no server span"); + } +} diff --git a/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/JerseyNormalizedRouteApiSecurityDisabledForkedTest.java b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/JerseyNormalizedRouteApiSecurityDisabledForkedTest.java new file mode 100644 index 00000000000..33607b4922e --- /dev/null +++ b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/JerseyNormalizedRouteApiSecurityDisabledForkedTest.java @@ -0,0 +1,24 @@ +package normalizedroute; + +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import datadog.trace.api.config.AppSecConfig; +import datadog.trace.test.junit.utils.config.WithConfig; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** With API Security disabled the normalized route is not set; {@code http.route} still is. */ +@WithConfig(key = AppSecConfig.API_SECURITY_ENABLED, value = "false") +class JerseyNormalizedRouteApiSecurityDisabledForkedTest extends AbstractJerseyNormalizedRouteTest { + + @Test + void noNormalizedRouteWhenApiSecurityIsDisabled() throws Exception { + Map tags = serverSpanTags("/regex/123"); + + assertEquals("/regex/{id: [0-9]+}", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } +} diff --git a/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/JerseyNormalizedRouteNoRouteNamingForkedTest.java b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/JerseyNormalizedRouteNoRouteNamingForkedTest.java new file mode 100644 index 00000000000..2596002e47a --- /dev/null +++ b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/JerseyNormalizedRouteNoRouteNamingForkedTest.java @@ -0,0 +1,34 @@ +package normalizedroute; + +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import datadog.trace.api.config.TraceInstrumentationConfig; +import datadog.trace.test.junit.utils.config.WithConfig; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** + * With route-based naming off the sub-resource method sets {@code http.route} again after its + * locator, once Jersey stored the request match; the locator's mark still prevents the tag. + */ +@WithConfig(key = TraceInstrumentationConfig.HTTP_SERVER_ROUTE_BASED_NAMING, value = "false") +class JerseyNormalizedRouteNoRouteNamingForkedTest extends AbstractJerseyNormalizedRouteTest { + + @Test + void noNormalizedRouteForASubResourceLocator() throws Exception { + Map tags = serverSpanTags("/locator/1/x"); + + assertEquals("/{name}", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + @Test + void normalizedRouteForAResourceMethod() throws Exception { + Map tags = serverSpanTags("/regex/123"); + + assertEquals(PREFIX + "/regex/{id}", String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } +} diff --git a/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/JerseyNormalizedRouteTest.java b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/JerseyNormalizedRouteTest.java new file mode 100644 index 00000000000..6320ca57e14 --- /dev/null +++ b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/JerseyNormalizedRouteTest.java @@ -0,0 +1,60 @@ +package normalizedroute; + +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import datadog.trace.bootstrap.ActiveSubsystems; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.tabletest.junit.TableTest; + +/** + * End-to-end normalized route for Jersey 2 served by a Jetty servlet container: the Jersey capture + * advice provides the mount prefix ({@code /ctx} context path plus the {@code /api/*} servlet + * mapping) and the bound values, the JAX-RS annotations decorator sets the tag on the server span. + */ +class JerseyNormalizedRouteTest extends AbstractJerseyNormalizedRouteTest { + + @TableTest({ + "Scenario | Path | Route | Normalized ", + "param and static text in segment | '/files/report.json' | '/files/{name}.json' | '/files/{name}.json' ", + "several params in one segment | '/three/1-2-3' | '/three/{a}-{b}-{c}' | '/three/{a}-{b}-{c}' ", + "static prefix in segment | '/users/user-42' | '/users/user-{id}' | '/users/user-{id}' ", + "regex constraint removed | '/regex/123' | '/regex/{id: [0-9]+}' | '/regex/{id}' ", + "catch-all with slashes | '/catch-all/a/b/c.txt' | '/catch-all/{path: .*}' | '/catch-all/{path}' ", + "catch-all bound empty: removed | '/catch-all/' | '/catch-all/{path: .*}' | '/catch-all' ", + "catch-all bound a slash | '/catch-all//' | '/catch-all/{path: .*}' | '/catch-all/' ", + "param names sanitized and unique | '/param-names/a/b' | '/param-names/{user-id}/{user_id}' | '/param-names/{user_id_2}/{user_id}'", + "non-ASCII literal encoded | '/encoded/caf%C3%A9' | '/encoded/café' | '/encoded/caf%C3%A9' " + }) + void normalizedRoute(String path, String route, String normalized) throws Exception { + Map tags = serverSpanTags(path); + + assertEquals(route, String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals(PREFIX + normalized, String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } + + @Test + void noNormalizedRouteWhenAppSecIsInactive() throws Exception { + ActiveSubsystems.APPSEC_ACTIVE = false; + + Map tags = serverSpanTags("/regex/123"); + + assertEquals("/regex/{id: [0-9]+}", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + /** + * A sub-resource locator runs during routing, before Jersey stores the match: its truncated route + * keeps http.route as before and sets no normalized route. + */ + @Test + void noNormalizedRouteForASubResourceLocator() throws Exception { + Map tags = serverSpanTags("/locator/1/x"); + + assertEquals("/locator/{id}", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } +} diff --git a/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/NormalizedRouteResource.java b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/NormalizedRouteResource.java new file mode 100644 index 00000000000..acb720844da --- /dev/null +++ b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/normalizedroute/NormalizedRouteResource.java @@ -0,0 +1,69 @@ +package normalizedroute; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; + +/** + * JAX-RS routes for the normalized route tests, outside the agent-ignored datadog.trace package. + */ +@Path("/") +public class NormalizedRouteResource { + + @GET + @Path("files/{name}.json") + public String file(@PathParam("name") String name) { + return name; + } + + @GET + @Path("three/{a}-{b}-{c}") + public String three(@PathParam("a") String a) { + return a; + } + + @GET + @Path("users/user-{id}") + public String user(@PathParam("id") String id) { + return id; + } + + @GET + @Path("regex/{id: [0-9]+}") + public String regex(@PathParam("id") String id) { + return id; + } + + @GET + @Path("catch-all/{path: .*}") + public String catchAll(@PathParam("path") String path) { + return "[" + path + "]"; + } + + @GET + @Path("param-names/{user-id}/{user_id}") + public String paramNames(@PathParam("user-id") String first) { + return first; + } + + @GET + @Path("encoded/caf\u00e9") + public String encoded() { + return "encoded"; + } + + /** Sub-resource locator: a route but no http method. */ + @Path("locator/{id}") + public SubResource locator() { + return new SubResource(); + } + + /** The sub-resource {@link #locator()} returns. */ + public static class SubResource { + @GET + @Path("{name}") + public String get(@PathParam("name") String name) { + return name; + } + } +} diff --git a/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/build.gradle b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/build.gradle index c48d668049d..ae7b6d94ef4 100644 --- a/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/build.gradle +++ b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/build.gradle @@ -48,11 +48,17 @@ dependencies { exclude group: 'org.eclipse.jetty', module: 'jetty-server' } + // Normalized route tests: HttpServletDispatcher on Jetty, server span from jetty-server-7.6 + def jettyVersion = '8.2.0.v20160908' + testImplementation group: 'org.eclipse.jetty', name: 'jetty-server', version: jettyVersion + testImplementation group: 'org.eclipse.jetty', name: 'jetty-servlet', version: jettyVersion + testImplementation project(':dd-java-agent:instrumentation:jetty:jetty-server:jetty-server-7.6') + testImplementation project(':dd-java-agent:instrumentation:rs:jax-rs:jax-rs-annotations:jax-rs-annotations-2.0') + nettyTestImplementation group: 'io.netty', name: 'netty', version: '3.8.0.Final' // upgrade netty to a version we support nettyTestImplementation group: 'org.jboss.resteasy', name: 'resteasy-netty', version :'3.0.0.Final' nettyTestImplementation project(':dd-java-agent:instrumentation:netty:netty-3.8') - def jettyVersion = '8.2.0.v20160908' jettyAsyncTestImplementation group: 'org.jboss.resteasy', name: 'async-http-servlet-3.0', version :'3.0.0.Final' jettyAsyncTestImplementation group: 'org.eclipse.jetty', name: 'jetty-server', version: jettyVersion jettyAsyncTestImplementation group: 'org.eclipse.jetty', name: 'jetty-servlet', version: jettyVersion diff --git a/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/main/java/datadog/trace/instrumentation/resteasy/JaxRsRequestMatchCapture.java b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/main/java/datadog/trace/instrumentation/resteasy/JaxRsRequestMatchCapture.java new file mode 100644 index 00000000000..ea65b800179 --- /dev/null +++ b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/main/java/datadog/trace/instrumentation/resteasy/JaxRsRequestMatchCapture.java @@ -0,0 +1,52 @@ +package datadog.trace.instrumentation.resteasy; + +import static datadog.trace.api.telemetry.LogCollector.EXCLUDE_TELEMETRY; +import static datadog.trace.bootstrap.ContextStores.getContextStore; +import static datadog.trace.bootstrap.ContextStores.getContextStoreId; +import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activeSpan; + +import datadog.trace.api.appsec.route.JaxRsRequestMatch; +import datadog.trace.bootstrap.ContextStore; +import datadog.trace.bootstrap.instrumentation.api.AgentSpan; +import java.net.URI; +import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Stores what RESTEasy matched for the current request under the local root span, where the JAX-RS + * annotations decorators read it to tag {@code _dd.appsec.normalized_route}. The store id must + * match the one the decorators use. + */ +public final class JaxRsRequestMatchCapture { + + private static final Logger log = LoggerFactory.getLogger(JaxRsRequestMatchCapture.class); + + private static final ContextStore REQUEST_MATCHES = + getContextStore( + getContextStoreId(AgentSpan.class.getName(), JaxRsRequestMatch.class.getName())); + + private JaxRsRequestMatchCapture() {} + + /** + * Stores nothing when the base URI or its raw path is unknown (no prefix, so no tag; an empty + * path is the root prefix), or when a sub-resource locator already marked the request with {@link + * JaxRsRequestMatch#SUBRESOURCE}. + * + * @param baseUri the request's base URI (what RESTEasy served before the matched path), or null + * @param boundValues the path parameters RESTEasy bound, by name + */ + public static void capture(URI baseUri, Map boundValues) { + try { + String rawBasePath = baseUri == null ? null : baseUri.getRawPath(); + AgentSpan span = rawBasePath == null ? null : activeSpan(); + AgentSpan localRoot = span == null ? null : span.getLocalRootSpan(); + if (localRoot == null || REQUEST_MATCHES.get(localRoot) == JaxRsRequestMatch.SUBRESOURCE) { + return; + } + REQUEST_MATCHES.put(localRoot, JaxRsRequestMatch.of(rawBasePath, boundValues)); + } catch (Throwable t) { + log.debug(EXCLUDE_TELEMETRY, "Failed to capture the JAX-RS request match", t); + } + } +} diff --git a/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/main/java/datadog/trace/instrumentation/resteasy/ResourceMethodInvokerInstrumentation.java b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/main/java/datadog/trace/instrumentation/resteasy/ResourceMethodInvokerInstrumentation.java new file mode 100644 index 00000000000..0c29f022b94 --- /dev/null +++ b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/main/java/datadog/trace/instrumentation/resteasy/ResourceMethodInvokerInstrumentation.java @@ -0,0 +1,62 @@ +package datadog.trace.instrumentation.resteasy; + +import static datadog.trace.agent.tooling.bytebuddy.matcher.NameMatchers.named; +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.api.appsec.route.NormalizedRouteHelper; +import net.bytebuddy.asm.Advice; +import org.jboss.resteasy.spi.HttpRequest; +import org.jboss.resteasy.spi.ResteasyUriInfo; + +/** + * Captures the base URI and the bound path parameters before RESTEasy invokes the matched resource + * method, for {@code _dd.appsec.normalized_route}. {@code ResteasyUriInfo.getPathParameters} is not + * hooked by AppSec (its hook is {@link MethodExpressionInstrumentation}). + */ +@AutoService(InstrumenterModule.class) +public class ResourceMethodInvokerInstrumentation extends InstrumenterModule.AppSec + implements Instrumenter.ForSingleType, Instrumenter.HasMethodAdvice { + + public ResourceMethodInvokerInstrumentation() { + super("resteasy"); + } + + @Override + public String muzzleDirective() { + return "jaxrs"; + } + + @Override + public String instrumentedType() { + return "org.jboss.resteasy.core.ResourceMethodInvoker"; + } + + @Override + public void methodAdvice(MethodTransformer transformer) { + transformer.applyAdvice( + named("invoke") + .and(takesArguments(3)) + .and(takesArgument(0, named("org.jboss.resteasy.spi.HttpRequest"))) + .and(takesArgument(1, named("org.jboss.resteasy.spi.HttpResponse"))) + .and(takesArgument(2, Object.class)), + ResourceMethodInvokerInstrumentation.class.getName() + "$InvokeAdvice"); + } + + public static class InvokeAdvice { + @Advice.OnMethodEnter(suppress = Throwable.class) + static void before(@Advice.Argument(0) final HttpRequest request) { + if (!NormalizedRouteHelper.isEnabled()) { + return; + } + ResteasyUriInfo uriInfo = request.getUri(); + if (uriInfo != null) { + // encoded values, like Jersey's encodedTemplateValues + JaxRsRequestMatchCapture.capture(uriInfo.getBaseUri(), uriInfo.getPathParameters(false)); + } + } + } +} diff --git a/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/AbstractResteasyNormalizedRouteTest.java b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/AbstractResteasyNormalizedRouteTest.java new file mode 100644 index 00000000000..fe2d496cc33 --- /dev/null +++ b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/AbstractResteasyNormalizedRouteTest.java @@ -0,0 +1,98 @@ +package normalizedroute; + +import static org.junit.jupiter.api.Assertions.assertEquals; +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 java.util.List; +import java.util.Map; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.nio.SelectChannelConnector; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher; +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; + +/** + * Serves {@link NormalizedRouteResource} with RESTEasy 3 in a Jetty servlet container ({@code /ctx} + * context path, {@code /api} mapping prefix), with AppSec forced active like the Spock {@code + * InstrumentationSpecification}, and returns the tags of the server span of a request. + */ +@TestInstance(PER_CLASS) +abstract class AbstractResteasyNormalizedRouteTest extends AbstractInstrumentationTest { + + static final String PREFIX = "/ctx/api"; + + private final OkHttpClient client = OkHttpUtils.client(); + private Server server; + private int port; + private boolean appSecActiveBefore; + + @BeforeAll + void startServer() throws Exception { + server = new Server(); + SelectChannelConnector connector = new SelectChannelConnector(); + connector.setPort(0); + server.addConnector(connector); + ServletContextHandler context = new ServletContextHandler(); + context.setContextPath("/ctx"); + ServletHolder holder = new ServletHolder(new HttpServletDispatcher()); + holder.setInitParameter("resteasy.servlet.mapping.prefix", "/api"); + holder.setInitParameter("resteasy.resources", NormalizedRouteResource.class.getName()); + context.addServlet(holder, "/api/*"); + server.setHandler(context); + server.start(); + port = connector.getLocalPort(); + } + + @AfterAll + void stopServer() throws Exception { + if (server != null) { + server.stop(); + } + } + + @BeforeEach + void forceAppSecActive() { + appSecActiveBefore = ActiveSubsystems.APPSEC_ACTIVE; + ActiveSubsystems.APPSEC_ACTIVE = true; + } + + @AfterEach + void restoreAppSecActive() { + ActiveSubsystems.APPSEC_ACTIVE = appSecActiveBefore; + } + + /** Sends {@code GET PREFIX + path}, expects a 200 and returns the tags of the server span. */ + Map serverSpanTags(String path) throws Exception { + return serverSpanTags(path, 200); + } + + /** Sends {@code GET PREFIX + path}, expects {@code status} and returns the server span tags. */ + Map serverSpanTags(String path, int status) throws Exception { + Request request = + new Request.Builder().url("http://localhost:" + port + PREFIX + path).get().build(); + try (Response response = client.newCall(request).execute()) { + assertEquals(status, response.code()); + } + writer.waitForTraces(1); + for (List trace : writer) { + for (DDSpan span : trace) { + if (span.isLocalRootSpan()) { + return span.getTags(); + } + } + } + throw new AssertionError("no server span"); + } +} diff --git a/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/NormalizedRouteResource.java b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/NormalizedRouteResource.java new file mode 100644 index 00000000000..acb720844da --- /dev/null +++ b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/NormalizedRouteResource.java @@ -0,0 +1,69 @@ +package normalizedroute; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; + +/** + * JAX-RS routes for the normalized route tests, outside the agent-ignored datadog.trace package. + */ +@Path("/") +public class NormalizedRouteResource { + + @GET + @Path("files/{name}.json") + public String file(@PathParam("name") String name) { + return name; + } + + @GET + @Path("three/{a}-{b}-{c}") + public String three(@PathParam("a") String a) { + return a; + } + + @GET + @Path("users/user-{id}") + public String user(@PathParam("id") String id) { + return id; + } + + @GET + @Path("regex/{id: [0-9]+}") + public String regex(@PathParam("id") String id) { + return id; + } + + @GET + @Path("catch-all/{path: .*}") + public String catchAll(@PathParam("path") String path) { + return "[" + path + "]"; + } + + @GET + @Path("param-names/{user-id}/{user_id}") + public String paramNames(@PathParam("user-id") String first) { + return first; + } + + @GET + @Path("encoded/caf\u00e9") + public String encoded() { + return "encoded"; + } + + /** Sub-resource locator: a route but no http method. */ + @Path("locator/{id}") + public SubResource locator() { + return new SubResource(); + } + + /** The sub-resource {@link #locator()} returns. */ + public static class SubResource { + @GET + @Path("{name}") + public String get(@PathParam("name") String name) { + return name; + } + } +} diff --git a/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/ResteasyNormalizedRouteApiSecurityDisabledForkedTest.java b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/ResteasyNormalizedRouteApiSecurityDisabledForkedTest.java new file mode 100644 index 00000000000..ebcd18b1164 --- /dev/null +++ b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/ResteasyNormalizedRouteApiSecurityDisabledForkedTest.java @@ -0,0 +1,25 @@ +package normalizedroute; + +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import datadog.trace.api.config.AppSecConfig; +import datadog.trace.test.junit.utils.config.WithConfig; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** With API Security disabled the normalized route is not set; {@code http.route} still is. */ +@WithConfig(key = AppSecConfig.API_SECURITY_ENABLED, value = "false") +class ResteasyNormalizedRouteApiSecurityDisabledForkedTest + extends AbstractResteasyNormalizedRouteTest { + + @Test + void noNormalizedRouteWhenApiSecurityIsDisabled() throws Exception { + Map tags = serverSpanTags("/regex/123"); + + assertEquals("/regex/{id: [0-9]+}", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } +} diff --git a/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/ResteasyNormalizedRouteNoRouteNamingForkedTest.java b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/ResteasyNormalizedRouteNoRouteNamingForkedTest.java new file mode 100644 index 00000000000..99997c1bdeb --- /dev/null +++ b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/ResteasyNormalizedRouteNoRouteNamingForkedTest.java @@ -0,0 +1,34 @@ +package normalizedroute; + +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import datadog.trace.api.config.TraceInstrumentationConfig; +import datadog.trace.test.junit.utils.config.WithConfig; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** + * With route-based naming off the sub-resource method sets {@code http.route} again after its + * locator, once RESTEasy stored the request match; the locator's mark still prevents the tag. + */ +@WithConfig(key = TraceInstrumentationConfig.HTTP_SERVER_ROUTE_BASED_NAMING, value = "false") +class ResteasyNormalizedRouteNoRouteNamingForkedTest extends AbstractResteasyNormalizedRouteTest { + + @Test + void noNormalizedRouteForASubResourceLocator() throws Exception { + Map tags = serverSpanTags("/locator/1/x"); + + assertEquals("/{name}", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + @Test + void normalizedRouteForAResourceMethod() throws Exception { + Map tags = serverSpanTags("/regex/123"); + + assertEquals(PREFIX + "/regex/{id}", String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } +} diff --git a/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/ResteasyNormalizedRouteTest.java b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/ResteasyNormalizedRouteTest.java new file mode 100644 index 00000000000..b098eb36a54 --- /dev/null +++ b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/normalizedroute/ResteasyNormalizedRouteTest.java @@ -0,0 +1,73 @@ +package normalizedroute; + +import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import datadog.trace.bootstrap.ActiveSubsystems; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.tabletest.junit.TableTest; + +/** + * End-to-end normalized route for RESTEasy 3 served by a Jetty servlet container: the RESTEasy + * capture advice provides the mount prefix ({@code /ctx} context path plus the {@code /api} mapping + * prefix) and the bound values, the JAX-RS annotations decorator sets the tag on the server span. + */ +class ResteasyNormalizedRouteTest extends AbstractResteasyNormalizedRouteTest { + + @TableTest({ + "Scenario | Path | Route | Normalized ", + "param and static text in segment | '/files/report.json' | '/files/{name}.json' | '/files/{name}.json' ", + "several params in one segment | '/three/1-2-3' | '/three/{a}-{b}-{c}' | '/three/{a}-{b}-{c}' ", + "static prefix in segment | '/users/user-42' | '/users/user-{id}' | '/users/user-{id}' ", + "regex constraint removed | '/regex/123' | '/regex/{id: [0-9]+}' | '/regex/{id}' ", + "catch-all with slashes | '/catch-all/a/b/c.txt' | '/catch-all/{path: .*}' | '/catch-all/{path}' ", + "param names sanitized and unique | '/param-names/a/b' | '/param-names/{user-id}/{user_id}' | '/param-names/{user_id_2}/{user_id}'", + "non-ASCII literal encoded | '/encoded/caf%C3%A9' | '/encoded/café' | '/encoded/caf%C3%A9' " + }) + void normalizedRoute(String path, String route, String normalized) throws Exception { + Map tags = serverSpanTags(path); + + assertEquals(route, String.valueOf(tags.get(HTTP_ROUTE))); + assertEquals(PREFIX + normalized, String.valueOf(tags.get(NORMALIZED_ROUTE_TAG))); + } + + /** + * RESTEasy 3 does not match {@code {path: .*}} with an empty or only-{@code /} value (404), so + * there is no route and no normalized route. + */ + @ParameterizedTest + @ValueSource(strings = {"/catch-all/", "/catch-all//"}) + void catchAllWithEmptyValueIsNotMatched(String path) throws Exception { + Map tags = serverSpanTags(path, 404); + + assertNull(tags.get(HTTP_ROUTE)); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + @Test + void noNormalizedRouteWhenAppSecIsInactive() throws Exception { + ActiveSubsystems.APPSEC_ACTIVE = false; + + Map tags = serverSpanTags("/regex/123"); + + assertEquals("/regex/{id: [0-9]+}", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } + + /** + * RESTEasy invokes a sub-resource locator before the sub-resource method it returns: the + * locator's truncated route keeps http.route as before and sets no normalized route. + */ + @Test + void noNormalizedRouteForASubResourceLocator() throws Exception { + Map tags = serverSpanTags("/locator/1/x"); + + assertEquals("/locator/{id}", String.valueOf(tags.get(HTTP_ROUTE))); + assertNull(tags.get(NORMALIZED_ROUTE_TAG)); + } +} diff --git a/dd-java-agent/instrumentation/rs/jakarta-rs-annotations-3.0/src/main/java/datadog/trace/instrumentation/jakarta3/JakartaRsAnnotationsDecorator.java b/dd-java-agent/instrumentation/rs/jakarta-rs-annotations-3.0/src/main/java/datadog/trace/instrumentation/jakarta3/JakartaRsAnnotationsDecorator.java index 41bc2021fd7..a47f01b0b46 100644 --- a/dd-java-agent/instrumentation/rs/jakarta-rs-annotations-3.0/src/main/java/datadog/trace/instrumentation/jakarta3/JakartaRsAnnotationsDecorator.java +++ b/dd-java-agent/instrumentation/rs/jakarta-rs-annotations-3.0/src/main/java/datadog/trace/instrumentation/jakarta3/JakartaRsAnnotationsDecorator.java @@ -1,11 +1,17 @@ package datadog.trace.instrumentation.jakarta3; +import static datadog.trace.api.telemetry.LogCollector.EXCLUDE_TELEMETRY; import static datadog.trace.bootstrap.ContextStores.getContextStore; import static datadog.trace.bootstrap.ContextStores.getContextStoreId; import static datadog.trace.bootstrap.instrumentation.decorator.http.HttpResourceDecorator.HTTP_RESOURCE_DECORATOR; import datadog.trace.api.GenericClassValue; import datadog.trace.api.Pair; +import datadog.trace.api.appsec.route.JaxRsRequestMatch; +import datadog.trace.api.appsec.route.JaxRsRouteParser; +import datadog.trace.api.appsec.route.NormalizedRouteHelper; +import datadog.trace.api.appsec.route.RouteTemplate; +import datadog.trace.api.internal.VisibleForTesting; import datadog.trace.bootstrap.ClassHierarchyIterable; import datadog.trace.bootstrap.ContextStore; import datadog.trace.bootstrap.instrumentation.api.AgentSpan; @@ -19,8 +25,11 @@ import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class JakartaRsAnnotationsDecorator extends BaseDecorator { + private static final Logger log = LoggerFactory.getLogger(JakartaRsAnnotationsDecorator.class); public static final CharSequence JAKARTA_RS_REQUEST_ABORT = UTF8BytesString.create("jakarta-rs.request.abort"); @@ -48,6 +57,11 @@ private enum RouteState { private static final ContextStore ROUTE_STATES = getContextStore(getContextStoreId(AgentSpan.class.getName(), RouteState.class.getName())); + /** Filled by the Jersey AppSec capture advice, keyed by the local root span. */ + private static final ContextStore REQUEST_MATCHES = + getContextStore( + getContextStoreId(AgentSpan.class.getName(), JaxRsRequestMatch.class.getName())); + @Override protected String[] instrumentationNames() { return new String[0]; @@ -73,16 +87,20 @@ public void onJakartaRsSpan( // When jakarta-rs is the root, we want to name using the path, otherwise use the class/method. final boolean isRootScope = parent == null; if (isRootScope) { + markSubResourceLocator(span, httpMethodAndRoute); HTTP_RESOURCE_DECORATOR.withRoute( span, httpMethodAndRoute.getLeft(), httpMethodAndRoute.getRight()); + tagNormalizedRoute(span, httpMethodAndRoute.getRight()); } else { span.setResourceName(DECORATE.spanNameForMethod(target, method)); final AgentSpan localRoot = parent.getLocalRootSpan(); + markSubResourceLocator(localRoot, httpMethodAndRoute); if (parent == localRoot) { parent.setTag(Tags.COMPONENT, "jakarta-rs"); HTTP_RESOURCE_DECORATOR.withRoute( parent, httpMethodAndRoute.getLeft(), httpMethodAndRoute.getRight()); + tagNormalizedRoute(parent, httpMethodAndRoute.getRight()); } else if (localRoot != null && Tags.SPAN_KIND_SERVER.equals(parent.getTag(Tags.SPAN_KIND)) && "/".equals(localRoot.getTag(Tags.HTTP_ROUTE)) @@ -95,11 +113,60 @@ public void onJakartaRsSpan( // Refine a server handler's catch-all route, but not from a nested resource call. HTTP_RESOURCE_DECORATOR.withRoute( localRoot, httpMethodAndRoute.getLeft(), httpMethodAndRoute.getRight()); + tagNormalizedRoute(localRoot, httpMethodAndRoute.getRight()); } } } } + /** + * Marks the request of {@code localRoot} as handled by a sub-resource locator (an annotated + * method with a route but no http method): the route of its sub-resource methods is truncated, so + * they set no normalized route. Runs before the capture advice, which keeps the mark. Never + * throws. + */ + private static void markSubResourceLocator( + final AgentSpan localRoot, final Pair httpMethodAndRoute) { + if (localRoot == null + || httpMethodAndRoute.hasLeft() + || !httpMethodAndRoute.hasRight() + || httpMethodAndRoute.getRight().length() == 0 + || !NormalizedRouteHelper.isEnabled()) { + return; + } + try { + REQUEST_MATCHES.put(localRoot, JaxRsRequestMatch.SUBRESOURCE); + } catch (Throwable t) { + log.debug(EXCLUDE_TELEMETRY, "Failed to mark a Jakarta RS sub-resource locator", t); + } + } + + /** + * Sets {@code _dd.appsec.normalized_route} on {@code span}, the span that just received {@code + * route} as {@code http.route} (the local root), from the request match a capture advice stored + * for it. No match (prefix unknown) or a sub-resource locator means no tag. Never throws. + */ + private static void tagNormalizedRoute(final AgentSpan span, final CharSequence route) { + if (!NormalizedRouteHelper.isEnabled()) { + return; + } + try { + tagNormalizedRoute(span, route, (JaxRsRequestMatch) REQUEST_MATCHES.get(span)); + } catch (Throwable t) { + log.debug(EXCLUDE_TELEMETRY, "Failed to set the Jakarta RS normalized route", t); + } + } + + @VisibleForTesting + static void tagNormalizedRoute( + final AgentSpan span, final CharSequence route, final JaxRsRequestMatch match) { + if (match == null || match == JaxRsRequestMatch.SUBRESOURCE || route == null) { + return; + } + final RouteTemplate template = JaxRsRouteParser.cached(route.toString()); + NormalizedRouteHelper.tag(span, template, match.prefix(), match.presenceFor(template)); + } + /** * Returns the resource name parts given a JakartaRS annotated method. Results are cached so this * method can be called multiple times without significantly impacting performance. diff --git a/dd-java-agent/instrumentation/rs/jakarta-rs-annotations-3.0/src/test/java/datadog/trace/instrumentation/jakarta3/JakartaRsNormalizedRouteTest.java b/dd-java-agent/instrumentation/rs/jakarta-rs-annotations-3.0/src/test/java/datadog/trace/instrumentation/jakarta3/JakartaRsNormalizedRouteTest.java new file mode 100644 index 00000000000..384364440c5 --- /dev/null +++ b/dd-java-agent/instrumentation/rs/jakarta-rs-annotations-3.0/src/test/java/datadog/trace/instrumentation/jakarta3/JakartaRsNormalizedRouteTest.java @@ -0,0 +1,249 @@ +package datadog.trace.instrumentation.jakarta3; + +import static datadog.trace.api.KnownTags.DD_APPSEC_NORMALIZED_ROUTE; +import static datadog.trace.bootstrap.ContextStores.getContextStore; +import static datadog.trace.bootstrap.ContextStores.getContextStoreId; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; +import static datadog.trace.bootstrap.instrumentation.api.Tags.SPAN_KIND; +import static datadog.trace.bootstrap.instrumentation.api.Tags.SPAN_KIND_SERVER; +import static datadog.trace.instrumentation.jakarta3.JakartaRsAnnotationsDecorator.DECORATE; +import static java.util.Collections.singletonMap; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +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.KnownTags; +import datadog.trace.api.appsec.route.JaxRsRequestMatch; +import datadog.trace.bootstrap.ActiveSubsystems; +import datadog.trace.bootstrap.ContextStore; +import datadog.trace.bootstrap.instrumentation.api.AgentSpan; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.tabletest.junit.TableTest; + +/** + * {@code _dd.appsec.normalized_route} set next to each {@code http.route} of {@link + * JakartaRsAnnotationsDecorator}, from the request match a capture advice stored for the local root + * span. + */ +class JakartaRsNormalizedRouteTest { + + private static final ContextStore REQUEST_MATCHES = + getContextStore( + getContextStoreId(AgentSpan.class.getName(), JaxRsRequestMatch.class.getName())); + + private final List storeKeys = new ArrayList<>(); + private boolean appSecActive; + + @BeforeEach + void activateAppSec() { + appSecActive = ActiveSubsystems.APPSEC_ACTIVE; + ActiveSubsystems.APPSEC_ACTIVE = true; + } + + @AfterEach + void restoreAppSec() { + ActiveSubsystems.APPSEC_ACTIVE = appSecActive; + } + + @AfterEach + void clearStore() { + for (AgentSpan key : storeKeys) { + REQUEST_MATCHES.remove(key); + } + } + + /** A resource with a catch-all path parameter. */ + @Path("/files") + public static class Files { + @GET + @Path("{path: .*}") + public String get() { + return "file"; + } + } + + /** A sub-resource locator: a route but no http method. */ + @Path("/locator") + public static class Locator { + @Path("{id}") + public SubResource sub() { + return new SubResource(); + } + } + + /** The sub-resource {@link Locator} returns; its route alone is truncated. */ + public static class SubResource { + @GET + @Path("{name}") + public String get() { + return "sub"; + } + } + + /** The route is rendered under the captured prefix, with presence from the bound values. */ + @TableTest({ + "Scenario | Route | Prefix | Name | Value | Tag ", + "static route | '/users' | '/ctx/' | | | '/ctx/users' ", + "regex removed | '/users/{id: [0-9]+}' | '/ctx/api/' | id | '42' | '/ctx/api/users/{id}'", + "catch-all value | '/files/{path: .*}' | '/ctx/' | path | 'a/b' | '/ctx/files/{path}' ", + "catch-all empty | '/files/{path: .*}' | '/ctx/' | path | '' | '/ctx/files' ", + "catch-all slash | '/files/{path: .*}' | | path | '/' | '/files/' " + }) + void tagsTheRouteUnderTheCapturedPrefix( + String route, String prefix, String name, String value, String tag) { + AgentSpan span = routedSpan(); + + JakartaRsAnnotationsDecorator.tagNormalizedRoute( + span, route, JaxRsRequestMatch.of(prefix, name == null ? null : singletonMap(name, value))); + + verify(span).setTag(DD_APPSEC_NORMALIZED_ROUTE, tag); + } + + @Test + void noTagWithoutACapturedMatch() { + AgentSpan span = routedSpan(); + + JakartaRsAnnotationsDecorator.tagNormalizedRoute(span, "/users/{id}", null); + + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + } + + @Test + void tagsTheRootSpan() throws Exception { + AgentSpan span = routedSpan(); + store(span, "/"); + + DECORATE.onJakartaRsSpan(span, null, Files.class, get()); + + verify(span).setTag(DD_APPSEC_NORMALIZED_ROUTE, "/ctx/files/"); + } + + @Test + void tagsTheParentWhenItIsTheLocalRoot() throws Exception { + AgentSpan parent = routedSpan(); + when(parent.getLocalRootSpan()).thenReturn(parent); + AgentSpan span = mock(AgentSpan.class); + store(parent, "a/b"); + + DECORATE.onJakartaRsSpan(span, parent, Files.class, get()); + + verify(parent).setTag(DD_APPSEC_NORMALIZED_ROUTE, "/ctx/files/{path}"); + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + } + + @Test + void tagsTheLocalRootWhenItRefinesACatchAllRoute() throws Exception { + AgentSpan localRoot = routedSpan(); + when(localRoot.getTag(HTTP_ROUTE)).thenReturn("/"); + AgentSpan parent = mock(AgentSpan.class); + when(parent.getLocalRootSpan()).thenReturn(localRoot); + when(parent.getTag(SPAN_KIND)).thenReturn(SPAN_KIND_SERVER); + AgentSpan span = mock(AgentSpan.class); + store(localRoot, ""); + + DECORATE.onJakartaRsSpan(span, parent, Files.class, get()); + + verify(localRoot).setTag(DD_APPSEC_NORMALIZED_ROUTE, "/ctx/files"); + verify(parent, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + } + + @Test + void noTagWithoutAStoredMatch() throws Exception { + AgentSpan span = routedSpan(); + + DECORATE.onJakartaRsSpan(span, null, Files.class, get()); + + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + } + + @Test + void noTagWhenAppSecIsInactive() throws Exception { + ActiveSubsystems.APPSEC_ACTIVE = false; + AgentSpan span = routedSpan(); + store(span, "/"); + + DECORATE.onJakartaRsSpan(span, null, Files.class, get()); + + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + } + + @Test + void noTagForASubResourceLocatorMatch() { + AgentSpan span = routedSpan(); + + JakartaRsAnnotationsDecorator.tagNormalizedRoute( + span, "/users/{id}", JaxRsRequestMatch.SUBRESOURCE); + + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + } + + /** + * The sub-resource method overwrites the locator's http.route on a parent that is the local root; + * the locator's mark keeps it from setting the tag. + */ + @Test + void aSubResourceLocatorMarksTheLocalRootAndPreventsTheTag() throws Exception { + AgentSpan parent = routedSpan(); + when(parent.getLocalRootSpan()).thenReturn(parent); + storeKeys.add(parent); + + DECORATE.onJakartaRsSpan(mock(AgentSpan.class), parent, Locator.class, locatorMethod()); + assertSame(JaxRsRequestMatch.SUBRESOURCE, REQUEST_MATCHES.get(parent)); + DECORATE.onJakartaRsSpan(mock(AgentSpan.class), parent, SubResource.class, subMethod()); + + verify(parent).setTag(eq(KnownTags.HTTP_ROUTE), route("/locator/{id}")); + verify(parent).setTag(eq(KnownTags.HTTP_ROUTE), route("/{name}")); + verify(parent, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + } + + @Test + void aRootSubResourceLocatorMarksItsSpan() throws Exception { + AgentSpan span = routedSpan(); + storeKeys.add(span); + + DECORATE.onJakartaRsSpan(span, null, Locator.class, locatorMethod()); + + assertSame(JaxRsRequestMatch.SUBRESOURCE, REQUEST_MATCHES.get(span)); + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + } + + private static CharSequence route(String expected) { + return argThat(route -> route != null && expected.equals(route.toString())); + } + + private void store(AgentSpan localRoot, String path) { + storeKeys.add(localRoot); + REQUEST_MATCHES.put(localRoot, JaxRsRequestMatch.of("/ctx/", singletonMap("path", path))); + } + + private static Method locatorMethod() throws NoSuchMethodException { + return Locator.class.getMethod("sub"); + } + + private static Method subMethod() throws NoSuchMethodException { + return SubResource.class.getMethod("get"); + } + + private static Method get() throws NoSuchMethodException { + return Files.class.getMethod("get"); + } + + /** A span that already carries {@code http.route}, as after {@code withRoute}. */ + private static AgentSpan routedSpan() { + AgentSpan span = mock(AgentSpan.class); + when(span.getTag(HTTP_ROUTE)).thenReturn("route"); + return span; + } +} diff --git a/dd-java-agent/instrumentation/rs/jax-rs/jax-rs-annotations/jax-rs-annotations-2.0/src/main/java/datadog/trace/instrumentation/jaxrs2/JaxRsAnnotationsDecorator.java b/dd-java-agent/instrumentation/rs/jax-rs/jax-rs-annotations/jax-rs-annotations-2.0/src/main/java/datadog/trace/instrumentation/jaxrs2/JaxRsAnnotationsDecorator.java index 359dfe2d554..a2e28af3f26 100644 --- a/dd-java-agent/instrumentation/rs/jax-rs/jax-rs-annotations/jax-rs-annotations-2.0/src/main/java/datadog/trace/instrumentation/jaxrs2/JaxRsAnnotationsDecorator.java +++ b/dd-java-agent/instrumentation/rs/jax-rs/jax-rs-annotations/jax-rs-annotations-2.0/src/main/java/datadog/trace/instrumentation/jaxrs2/JaxRsAnnotationsDecorator.java @@ -1,12 +1,19 @@ package datadog.trace.instrumentation.jaxrs2; import static datadog.trace.api.telemetry.LogCollector.EXCLUDE_TELEMETRY; +import static datadog.trace.bootstrap.ContextStores.getContextStore; +import static datadog.trace.bootstrap.ContextStores.getContextStoreId; import static datadog.trace.bootstrap.instrumentation.decorator.http.HttpResourceDecorator.HTTP_RESOURCE_DECORATOR; import datadog.trace.api.GenericClassValue; import datadog.trace.api.Pair; +import datadog.trace.api.appsec.route.JaxRsRequestMatch; +import datadog.trace.api.appsec.route.JaxRsRouteParser; +import datadog.trace.api.appsec.route.NormalizedRouteHelper; +import datadog.trace.api.appsec.route.RouteTemplate; import datadog.trace.api.internal.VisibleForTesting; import datadog.trace.bootstrap.ClassHierarchyIterable; +import datadog.trace.bootstrap.ContextStore; import datadog.trace.bootstrap.instrumentation.api.AgentSpan; import datadog.trace.bootstrap.instrumentation.api.InternalSpanTypes; import datadog.trace.bootstrap.instrumentation.api.ResourceNamePriorities; @@ -43,6 +50,11 @@ public class JaxRsAnnotationsDecorator extends BaseDecorator { private static final ClassValue>> RESOURCE_NAMES = GenericClassValue.constructing(ConcurrentHashMap.class); + /** Filled by the Jersey and RESTEasy AppSec capture advices, keyed by the local root span. */ + private static final ContextStore REQUEST_MATCHES = + getContextStore( + getContextStoreId(AgentSpan.class.getName(), JaxRsRequestMatch.class.getName())); + @Override protected String[] instrumentationNames() { return new String[0]; @@ -69,14 +81,17 @@ public void onJaxRsSpan( final boolean isRootScope = parent == null; if (isRootScope) { if (httpMethodAndRoute.hasRight()) { // no route when no path was readable: keep the name + markSubResourceLocator(span, httpMethodAndRoute); HTTP_RESOURCE_DECORATOR.withRoute( span, httpMethodAndRoute.getLeft(), httpMethodAndRoute.getRight()); + tagNormalizedRoute(span, httpMethodAndRoute.getRight()); } } else { span.setResourceName(DECORATE.spanNameForMethod(target, method)); - if (parent.getLocalRootSpan().getResourceNamePriority() - < ResourceNamePriorities.HTTP_FRAMEWORK_ROUTE) { + final AgentSpan localRoot = parent.getLocalRootSpan(); + markSubResourceLocator(localRoot, httpMethodAndRoute); + if (localRoot.getResourceNamePriority() < ResourceNamePriorities.HTTP_FRAMEWORK_ROUTE) { parent.setTag(Tags.COMPONENT, "jax-rs"); // current handler is a filter @@ -90,11 +105,60 @@ public void onJaxRsSpan( } HTTP_RESOURCE_DECORATOR.withRoute( - parent.getLocalRootSpan(), httpMethodAndRoute.getLeft(), httpMethodAndRoute.getRight()); + localRoot, httpMethodAndRoute.getLeft(), httpMethodAndRoute.getRight()); + tagNormalizedRoute(localRoot, httpMethodAndRoute.getRight()); } } } + /** + * Marks the request of {@code localRoot} as handled by a sub-resource locator (an annotated + * method with a route but no http method): the route of its sub-resource methods is truncated, so + * they set no normalized route. Runs before the capture advice, which keeps the mark. Never + * throws. + */ + private static void markSubResourceLocator( + final AgentSpan localRoot, final Pair httpMethodAndRoute) { + if (localRoot == null + || httpMethodAndRoute.hasLeft() + || !httpMethodAndRoute.hasRight() + || httpMethodAndRoute.getRight().length() == 0 + || !NormalizedRouteHelper.isEnabled()) { + return; + } + try { + REQUEST_MATCHES.put(localRoot, JaxRsRequestMatch.SUBRESOURCE); + } catch (Throwable t) { + log.debug(EXCLUDE_TELEMETRY, "Failed to mark a JAX-RS sub-resource locator", t); + } + } + + /** + * Sets {@code _dd.appsec.normalized_route} on {@code span}, the span that just received {@code + * route} as {@code http.route} (the local root), from the request match a capture advice stored + * for it. No match (prefix unknown) or a sub-resource locator means no tag. Never throws. + */ + private static void tagNormalizedRoute(final AgentSpan span, final CharSequence route) { + if (!NormalizedRouteHelper.isEnabled()) { + return; + } + try { + tagNormalizedRoute(span, route, (JaxRsRequestMatch) REQUEST_MATCHES.get(span)); + } catch (Throwable t) { + log.debug(EXCLUDE_TELEMETRY, "Failed to set the JAX-RS normalized route", t); + } + } + + @VisibleForTesting + static void tagNormalizedRoute( + final AgentSpan span, final CharSequence route, final JaxRsRequestMatch match) { + if (match == null || match == JaxRsRequestMatch.SUBRESOURCE || route == null) { + return; + } + final RouteTemplate template = JaxRsRouteParser.cached(route.toString()); + NormalizedRouteHelper.tag(span, template, match.prefix(), match.presenceFor(template)); + } + /** * Returns the resource name parts given a JaxRS annotated method. Results are cached so this * method can be called multiple times without significantly impacting performance. diff --git a/dd-java-agent/instrumentation/rs/jax-rs/jax-rs-annotations/jax-rs-annotations-2.0/src/test/java/datadog/trace/instrumentation/jaxrs2/JaxRsAnnotationsDecoratorTest.java b/dd-java-agent/instrumentation/rs/jax-rs/jax-rs-annotations/jax-rs-annotations-2.0/src/test/java/datadog/trace/instrumentation/jaxrs2/JaxRsAnnotationsDecoratorTest.java index d70f87da9e4..c7c3ac8bae5 100644 --- a/dd-java-agent/instrumentation/rs/jax-rs/jax-rs-annotations/jax-rs-annotations-2.0/src/test/java/datadog/trace/instrumentation/jaxrs2/JaxRsAnnotationsDecoratorTest.java +++ b/dd-java-agent/instrumentation/rs/jax-rs/jax-rs-annotations/jax-rs-annotations-2.0/src/test/java/datadog/trace/instrumentation/jaxrs2/JaxRsAnnotationsDecoratorTest.java @@ -1,23 +1,38 @@ package datadog.trace.instrumentation.jaxrs2; +import static datadog.trace.api.KnownTags.DD_APPSEC_NORMALIZED_ROUTE; +import static datadog.trace.bootstrap.ContextStores.getContextStore; +import static datadog.trace.bootstrap.ContextStores.getContextStoreId; +import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE; import static datadog.trace.instrumentation.jaxrs2.JaxRsAnnotationsDecorator.DECORATE; +import static java.util.Collections.singletonMap; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyByte; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.nullable; 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.KnownTags; import datadog.trace.api.Pair; +import datadog.trace.api.appsec.route.JaxRsRequestMatch; +import datadog.trace.bootstrap.ActiveSubsystems; +import datadog.trace.bootstrap.ContextStore; import datadog.trace.bootstrap.instrumentation.api.AgentSpan; import java.lang.annotation.AnnotationFormatError; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import javax.ws.rs.GET; import javax.ws.rs.HttpMethod; import javax.ws.rs.Path; @@ -28,7 +43,10 @@ import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; import net.bytebuddy.dynamic.scaffold.TypeValidation; import net.bytebuddy.implementation.FixedValue; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.tabletest.junit.TableTest; /** * A resource whose annotations are malformed: {@code @Path} is not repeatable, so a method that @@ -36,6 +54,59 @@ */ class JaxRsAnnotationsDecoratorTest { + private static final ContextStore REQUEST_MATCHES = + getContextStore( + getContextStoreId(AgentSpan.class.getName(), JaxRsRequestMatch.class.getName())); + + private final List storeKeys = new ArrayList<>(); + private boolean appSecActive; + + @BeforeEach + void activateAppSec() { + appSecActive = ActiveSubsystems.APPSEC_ACTIVE; + ActiveSubsystems.APPSEC_ACTIVE = true; + } + + @AfterEach + void restoreAppSec() { + ActiveSubsystems.APPSEC_ACTIVE = appSecActive; + } + + @AfterEach + void clearStore() { + for (AgentSpan key : storeKeys) { + REQUEST_MATCHES.remove(key); + } + } + + /** A resource with a catch-all path parameter. */ + @Path("/files") + public static class Files { + @GET + @Path("{path: .*}") + public String get() { + return "file"; + } + } + + /** A sub-resource locator: a route but no http method. */ + @Path("/locator") + public static class Locator { + @Path("{id}") + public SubResource sub() { + return new SubResource(); + } + } + + /** The sub-resource {@link Locator} returns; its route alone is truncated. */ + public static class SubResource { + @GET + @Path("{name}") + public String get() { + return "sub"; + } + } + /** Declares the http method and path the malformed implementation can still be routed by. */ public interface Orders { @GET @@ -204,6 +275,165 @@ void routesByTheClassPathWhenNothingElseIsReadable() throws Exception { assertEquals("/orders", String.valueOf(httpMethodAndRoute.getRight())); } + /** The route is rendered under the captured prefix, with presence from the bound values. */ + @TableTest({ + "Scenario | Route | Prefix | Name | Value | Tag ", + "static route | '/users' | '/ctx/' | | | '/ctx/users' ", + "no prefix | '/users/{id}' | | id | '42' | '/users/{id}' ", + "regex removed | '/users/{id: [0-9]+}' | '/ctx/api/' | id | '42' | '/ctx/api/users/{id}'", + "encoded prefix | '/users/{id}' | '/c%20x/' | id | '42' | '/c%20x/users/{id}' ", + "catch-all value | '/files/{path: .*}' | '/ctx/' | path | 'a/b' | '/ctx/files/{path}' ", + "catch-all empty | '/files/{path: .*}' | '/ctx/' | path | '' | '/ctx/files' ", + "catch-all slash | '/files/{path: .*}' | '/ctx/' | path | '/' | '/ctx/files/' " + }) + void tagsTheRouteUnderTheCapturedPrefix( + String route, String prefix, String name, String value, String tag) { + AgentSpan span = routedSpan(); + Map boundValues = name == null ? null : singletonMap(name, value); + + JaxRsAnnotationsDecorator.tagNormalizedRoute( + span, route, JaxRsRequestMatch.of(prefix, boundValues)); + + verify(span).setTag(DD_APPSEC_NORMALIZED_ROUTE, tag); + } + + @Test + void noTagWithoutACapturedMatch() { + AgentSpan span = routedSpan(); + + JaxRsAnnotationsDecorator.tagNormalizedRoute(span, "/users/{id}", null); + + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + } + + @Test + void noTagForAMalformedRoute() { + AgentSpan span = routedSpan(); + + JaxRsAnnotationsDecorator.tagNormalizedRoute( + span, "/users/{id", JaxRsRequestMatch.of("/ctx/", null)); + + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + } + + @Test + void tagsTheRootSpanFromTheStoredMatch() throws Exception { + AgentSpan span = routedSpan(); + store(span, JaxRsRequestMatch.of("/ctx/", singletonMap("path", "/"))); + + DECORATE.onJaxRsSpan(span, null, Files.class, Files.class.getMethod("get")); + + verify(span).setTag(DD_APPSEC_NORMALIZED_ROUTE, "/ctx/files/"); + } + + @Test + void tagsTheLocalRootSpanFromTheStoredMatch() throws Exception { + AgentSpan localRoot = routedSpan(); + when(localRoot.getLocalRootSpan()).thenReturn(localRoot); + AgentSpan span = mock(AgentSpan.class); + store(localRoot, JaxRsRequestMatch.of("/ctx/", singletonMap("path", "a/b"))); + + DECORATE.onJaxRsSpan(span, localRoot, Files.class, Files.class.getMethod("get")); + + verify(localRoot).setTag(DD_APPSEC_NORMALIZED_ROUTE, "/ctx/files/{path}"); + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + } + + @Test + void noTagWithoutAStoredMatch() throws Exception { + AgentSpan span = routedSpan(); + + DECORATE.onJaxRsSpan(span, null, Files.class, Files.class.getMethod("get")); + + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + } + + @Test + void noTagWhenAppSecIsInactive() throws Exception { + ActiveSubsystems.APPSEC_ACTIVE = false; + AgentSpan span = routedSpan(); + store(span, JaxRsRequestMatch.of("/ctx/", null)); + + DECORATE.onJaxRsSpan(span, null, Files.class, Files.class.getMethod("get")); + + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + } + + @Test + void noTagForASubResourceLocatorMatch() { + AgentSpan span = routedSpan(); + + JaxRsAnnotationsDecorator.tagNormalizedRoute( + span, "/users/{id}", JaxRsRequestMatch.SUBRESOURCE); + + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + } + + /** + * Route-based naming off keeps the resource name priority low, so the sub-resource method sets + * http.route again after the locator; the locator's mark keeps it from setting the tag. + */ + @Test + void aSubResourceLocatorMarksTheLocalRootAndPreventsTheTag() throws Exception { + AgentSpan localRoot = routedSpan(); + when(localRoot.getLocalRootSpan()).thenReturn(localRoot); + storeKeys.add(localRoot); + + DECORATE.onJaxRsSpan(mock(AgentSpan.class), localRoot, Locator.class, locatorMethod()); + assertSame(JaxRsRequestMatch.SUBRESOURCE, REQUEST_MATCHES.get(localRoot)); + DECORATE.onJaxRsSpan(mock(AgentSpan.class), localRoot, SubResource.class, subMethod()); + + verify(localRoot).setTag(eq(KnownTags.HTTP_ROUTE), route("/locator/{id}")); + verify(localRoot).setTag(eq(KnownTags.HTTP_ROUTE), route("/{name}")); + verify(localRoot, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + } + + @Test + void aRootSubResourceLocatorMarksItsSpan() throws Exception { + AgentSpan span = routedSpan(); + storeKeys.add(span); + + DECORATE.onJaxRsSpan(span, null, Locator.class, locatorMethod()); + + assertSame(JaxRsRequestMatch.SUBRESOURCE, REQUEST_MATCHES.get(span)); + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + } + + @Test + void noMarkWhenAppSecIsInactive() throws Exception { + ActiveSubsystems.APPSEC_ACTIVE = false; + AgentSpan span = routedSpan(); + storeKeys.add(span); + + DECORATE.onJaxRsSpan(span, null, Locator.class, locatorMethod()); + + assertNull(REQUEST_MATCHES.get(span)); + } + + private static CharSequence route(String expected) { + return argThat(route -> route != null && expected.equals(route.toString())); + } + + private void store(AgentSpan localRoot, JaxRsRequestMatch match) { + storeKeys.add(localRoot); + REQUEST_MATCHES.put(localRoot, match); + } + + private static Method locatorMethod() throws NoSuchMethodException { + return Locator.class.getMethod("sub"); + } + + private static Method subMethod() throws NoSuchMethodException { + return SubResource.class.getMethod("get"); + } + + /** A span that already carries {@code http.route}, as after {@code withRoute}. */ + private static AgentSpan routedSpan() { + AgentSpan span = mock(AgentSpan.class); + when(span.getTag(HTTP_ROUTE)).thenReturn("route"); + return span; + } + /** A {@code @Path("/orders")} class whose {@code get()} carries {@code @GET} and two paths. */ private static Class malformedResource(Class parent) { AnnotationDescription ordersPath = path("/orders"); From d14b6124b765b4cdd8908de3f90a058d2feda43e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20Gonz=C3=A1lez=20Garc=C3=ADa?= Date: Fri, 27 Nov 2026 09:51:32 +0100 Subject: [PATCH 2/2] review: pre-PR checks - Clear _dd.appsec.normalized_route before recomputing it on every withRoute, so the last writer of http.route owns the tag (no stale value on re-dispatch or Quarkus on Vert.x) - Mark sub-resource locators only where the locator sets the route - Drop dead root-scope tagging (no server span, no capture) - Unit tests for JaxRsRequestMatchCapture (null base URI, no span, SUBRESOURCE kept) - jakarta-rs negative tests (AppSec inactive, malformed route) and stale-tag tests --- .../jersey-appsec-2.0/build.gradle | 1 + .../jersey2/JaxRsRequestMatchCapture.java | 18 ++- .../jersey2/JaxRsRequestMatchCaptureTest.java | 152 ++++++++++++++++++ .../resteasy/resteasy-appsec-3.0/build.gradle | 1 + .../resteasy/JaxRsRequestMatchCapture.java | 18 ++- .../JaxRsRequestMatchCaptureTest.java | 152 ++++++++++++++++++ .../JakartaRsAnnotationsDecorator.java | 16 +- .../JakartaRsNormalizedRouteTest.java | 124 ++++++++++++-- .../jaxrs2/JaxRsAnnotationsDecorator.java | 14 +- .../jaxrs2/JaxRsAnnotationsDecoratorTest.java | 94 +++++++++-- 10 files changed, 546 insertions(+), 44 deletions(-) create mode 100644 dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/datadog/trace/instrumentation/jersey2/JaxRsRequestMatchCaptureTest.java create mode 100644 dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/datadog/trace/instrumentation/resteasy/JaxRsRequestMatchCaptureTest.java diff --git a/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/build.gradle b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/build.gradle index 0f7a315c2ef..3cb0182e827 100644 --- a/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/build.gradle +++ b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/build.gradle @@ -57,6 +57,7 @@ dependencies { testImplementation group: 'org.eclipse.jetty', name: 'jetty-servlet', version: '8.2.0.v20160908' testImplementation project(':dd-java-agent:instrumentation:jetty:jetty-server:jetty-server-7.6') testImplementation project(':dd-java-agent:instrumentation:rs:jax-rs:jax-rs-annotations:jax-rs-annotations-2.0') + testImplementation libs.bundles.mockito } // tested in grizzly-http-2.3.20 diff --git a/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/main/java/datadog/trace/instrumentation/jersey2/JaxRsRequestMatchCapture.java b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/main/java/datadog/trace/instrumentation/jersey2/JaxRsRequestMatchCapture.java index 9e92f5a1cc0..b5e690992a9 100644 --- a/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/main/java/datadog/trace/instrumentation/jersey2/JaxRsRequestMatchCapture.java +++ b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/main/java/datadog/trace/instrumentation/jersey2/JaxRsRequestMatchCapture.java @@ -6,6 +6,8 @@ import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activeSpan; import datadog.trace.api.appsec.route.JaxRsRequestMatch; +import datadog.trace.api.appsec.route.NormalizedRouteHelper; +import datadog.trace.api.internal.VisibleForTesting; import datadog.trace.bootstrap.ContextStore; import datadog.trace.bootstrap.instrumentation.api.AgentSpan; import java.net.URI; @@ -37,10 +39,22 @@ private JaxRsRequestMatchCapture() {} * @param boundValues the path parameters Jersey bound, by name */ public static void capture(URI baseUri, Map boundValues) { + capture(baseUri == null ? null : activeSpan(), baseUri, boundValues); + } + + /** + * Same as {@link #capture(URI, Map)} with {@code span} as the active span. Also stores nothing + * without an active span or local root, or when {@link NormalizedRouteHelper#isEnabled()} is + * false. + */ + @VisibleForTesting + static void capture(AgentSpan span, URI baseUri, Map boundValues) { try { String rawBasePath = baseUri == null ? null : baseUri.getRawPath(); - AgentSpan span = rawBasePath == null ? null : activeSpan(); - AgentSpan localRoot = span == null ? null : span.getLocalRootSpan(); + AgentSpan localRoot = + rawBasePath == null || span == null || !NormalizedRouteHelper.isEnabled() + ? null + : span.getLocalRootSpan(); if (localRoot == null || REQUEST_MATCHES.get(localRoot) == JaxRsRequestMatch.SUBRESOURCE) { return; } diff --git a/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/datadog/trace/instrumentation/jersey2/JaxRsRequestMatchCaptureTest.java b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/datadog/trace/instrumentation/jersey2/JaxRsRequestMatchCaptureTest.java new file mode 100644 index 00000000000..b23638991e7 --- /dev/null +++ b/dd-java-agent/instrumentation/jersey/jersey-appsec/jersey-appsec-2.0/src/test/java/datadog/trace/instrumentation/jersey2/JaxRsRequestMatchCaptureTest.java @@ -0,0 +1,152 @@ +package datadog.trace.instrumentation.jersey2; + +import static datadog.trace.bootstrap.ContextStores.getContextStore; +import static datadog.trace.bootstrap.ContextStores.getContextStoreId; +import static java.util.Collections.singletonList; +import static java.util.Collections.singletonMap; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import datadog.trace.api.appsec.route.JaxRsRequestMatch; +import datadog.trace.api.appsec.route.JaxRsRouteParser; +import datadog.trace.api.appsec.route.RouteTemplate; +import datadog.trace.bootstrap.ActiveSubsystems; +import datadog.trace.bootstrap.ContextStore; +import datadog.trace.bootstrap.instrumentation.api.AgentSpan; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class JaxRsRequestMatchCaptureTest { + + private static final ContextStore REQUEST_MATCHES = + getContextStore( + getContextStoreId(AgentSpan.class.getName(), JaxRsRequestMatch.class.getName())); + + private static final URI BASE_URI = URI.create("http://localhost:8080/c%20x/api/"); + private static final Map BOUND_VALUES = singletonMap("path", singletonList("a/b")); + + private final List storeKeys = new ArrayList<>(); + private boolean appSecActive; + + @BeforeEach + void activateAppSec() { + appSecActive = ActiveSubsystems.APPSEC_ACTIVE; + ActiveSubsystems.APPSEC_ACTIVE = true; + } + + @AfterEach + void restoreAppSec() { + ActiveSubsystems.APPSEC_ACTIVE = appSecActive; + } + + @AfterEach + void clearStore() { + for (AgentSpan key : storeKeys) { + REQUEST_MATCHES.remove(key); + } + } + + @Test + void storesTheDecodedPrefixAndTheBoundValues() { + AgentSpan localRoot = localRoot(); + + JaxRsRequestMatchCapture.capture(spanUnder(localRoot), BASE_URI, BOUND_VALUES); + + JaxRsRequestMatch match = (JaxRsRequestMatch) REQUEST_MATCHES.get(localRoot); + assertEquals("/c x/api/", match.prefix()); + assertEquals("/c%20x/api/files/{path}", render("/files/{path: .*}", match)); + } + + @Test + void anEmptyRawPathStoresARootMatch() { + AgentSpan localRoot = localRoot(); + + JaxRsRequestMatchCapture.capture( + spanUnder(localRoot), URI.create("http://localhost:8080"), singletonMap("path", "")); + + JaxRsRequestMatch match = (JaxRsRequestMatch) REQUEST_MATCHES.get(localRoot); + assertEquals("", match.prefix()); + assertEquals("/files", render("/files/{path: .*}", match)); + } + + @Test + void aNullBaseUriStoresNothing() { + AgentSpan localRoot = localRoot(); + + JaxRsRequestMatchCapture.capture(spanUnder(localRoot), null, BOUND_VALUES); + + assertNull(REQUEST_MATCHES.get(localRoot)); + } + + @Test + void aNullRawPathStoresNothing() { + AgentSpan localRoot = localRoot(); + + // an opaque URI has no path + JaxRsRequestMatchCapture.capture( + spanUnder(localRoot), URI.create("mailto:a@example.com"), BOUND_VALUES); + + assertNull(REQUEST_MATCHES.get(localRoot)); + } + + @Test + void noActiveSpanStoresNothing() { + assertDoesNotThrow(() -> JaxRsRequestMatchCapture.capture(null, BASE_URI, BOUND_VALUES)); + } + + @Test + void noLocalRootStoresNothing() { + AgentSpan span = mock(AgentSpan.class); + storeKeys.add(span); + + JaxRsRequestMatchCapture.capture(span, BASE_URI, BOUND_VALUES); + + assertNull(REQUEST_MATCHES.get(span)); + } + + @Test + void keepsASubResourceMark() { + AgentSpan localRoot = localRoot(); + REQUEST_MATCHES.put(localRoot, JaxRsRequestMatch.SUBRESOURCE); + + JaxRsRequestMatchCapture.capture(spanUnder(localRoot), BASE_URI, BOUND_VALUES); + + assertSame(JaxRsRequestMatch.SUBRESOURCE, REQUEST_MATCHES.get(localRoot)); + } + + @Test + void storesNothingWhenAppSecIsInactive() { + ActiveSubsystems.APPSEC_ACTIVE = false; + AgentSpan localRoot = localRoot(); + + JaxRsRequestMatchCapture.capture(spanUnder(localRoot), BASE_URI, BOUND_VALUES); + + assertNull(REQUEST_MATCHES.get(localRoot)); + } + + private AgentSpan localRoot() { + AgentSpan localRoot = mock(AgentSpan.class); + storeKeys.add(localRoot); + return localRoot; + } + + private static AgentSpan spanUnder(AgentSpan localRoot) { + AgentSpan span = mock(AgentSpan.class); + when(span.getLocalRootSpan()).thenReturn(localRoot); + return span; + } + + private static String render(String route, JaxRsRequestMatch match) { + RouteTemplate template = JaxRsRouteParser.cached(route); + return template.render(match.prefix(), match.presenceFor(template)); + } +} diff --git a/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/build.gradle b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/build.gradle index ae7b6d94ef4..7b7cbd9c857 100644 --- a/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/build.gradle +++ b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/build.gradle @@ -54,6 +54,7 @@ dependencies { testImplementation group: 'org.eclipse.jetty', name: 'jetty-servlet', version: jettyVersion testImplementation project(':dd-java-agent:instrumentation:jetty:jetty-server:jetty-server-7.6') testImplementation project(':dd-java-agent:instrumentation:rs:jax-rs:jax-rs-annotations:jax-rs-annotations-2.0') + testImplementation libs.bundles.mockito nettyTestImplementation group: 'io.netty', name: 'netty', version: '3.8.0.Final' // upgrade netty to a version we support nettyTestImplementation group: 'org.jboss.resteasy', name: 'resteasy-netty', version :'3.0.0.Final' diff --git a/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/main/java/datadog/trace/instrumentation/resteasy/JaxRsRequestMatchCapture.java b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/main/java/datadog/trace/instrumentation/resteasy/JaxRsRequestMatchCapture.java index ea65b800179..fad44963ace 100644 --- a/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/main/java/datadog/trace/instrumentation/resteasy/JaxRsRequestMatchCapture.java +++ b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/main/java/datadog/trace/instrumentation/resteasy/JaxRsRequestMatchCapture.java @@ -6,6 +6,8 @@ import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activeSpan; import datadog.trace.api.appsec.route.JaxRsRequestMatch; +import datadog.trace.api.appsec.route.NormalizedRouteHelper; +import datadog.trace.api.internal.VisibleForTesting; import datadog.trace.bootstrap.ContextStore; import datadog.trace.bootstrap.instrumentation.api.AgentSpan; import java.net.URI; @@ -37,10 +39,22 @@ private JaxRsRequestMatchCapture() {} * @param boundValues the path parameters RESTEasy bound, by name */ public static void capture(URI baseUri, Map boundValues) { + capture(baseUri == null ? null : activeSpan(), baseUri, boundValues); + } + + /** + * Same as {@link #capture(URI, Map)} with {@code span} as the active span. Also stores nothing + * without an active span or local root, or when {@link NormalizedRouteHelper#isEnabled()} is + * false. + */ + @VisibleForTesting + static void capture(AgentSpan span, URI baseUri, Map boundValues) { try { String rawBasePath = baseUri == null ? null : baseUri.getRawPath(); - AgentSpan span = rawBasePath == null ? null : activeSpan(); - AgentSpan localRoot = span == null ? null : span.getLocalRootSpan(); + AgentSpan localRoot = + rawBasePath == null || span == null || !NormalizedRouteHelper.isEnabled() + ? null + : span.getLocalRootSpan(); if (localRoot == null || REQUEST_MATCHES.get(localRoot) == JaxRsRequestMatch.SUBRESOURCE) { return; } diff --git a/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/datadog/trace/instrumentation/resteasy/JaxRsRequestMatchCaptureTest.java b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/datadog/trace/instrumentation/resteasy/JaxRsRequestMatchCaptureTest.java new file mode 100644 index 00000000000..dfc5ed0d6bf --- /dev/null +++ b/dd-java-agent/instrumentation/resteasy/resteasy-appsec-3.0/src/test/java/datadog/trace/instrumentation/resteasy/JaxRsRequestMatchCaptureTest.java @@ -0,0 +1,152 @@ +package datadog.trace.instrumentation.resteasy; + +import static datadog.trace.bootstrap.ContextStores.getContextStore; +import static datadog.trace.bootstrap.ContextStores.getContextStoreId; +import static java.util.Collections.singletonList; +import static java.util.Collections.singletonMap; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import datadog.trace.api.appsec.route.JaxRsRequestMatch; +import datadog.trace.api.appsec.route.JaxRsRouteParser; +import datadog.trace.api.appsec.route.RouteTemplate; +import datadog.trace.bootstrap.ActiveSubsystems; +import datadog.trace.bootstrap.ContextStore; +import datadog.trace.bootstrap.instrumentation.api.AgentSpan; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class JaxRsRequestMatchCaptureTest { + + private static final ContextStore REQUEST_MATCHES = + getContextStore( + getContextStoreId(AgentSpan.class.getName(), JaxRsRequestMatch.class.getName())); + + private static final URI BASE_URI = URI.create("http://localhost:8080/c%20x/api/"); + private static final Map BOUND_VALUES = singletonMap("path", singletonList("a/b")); + + private final List storeKeys = new ArrayList<>(); + private boolean appSecActive; + + @BeforeEach + void activateAppSec() { + appSecActive = ActiveSubsystems.APPSEC_ACTIVE; + ActiveSubsystems.APPSEC_ACTIVE = true; + } + + @AfterEach + void restoreAppSec() { + ActiveSubsystems.APPSEC_ACTIVE = appSecActive; + } + + @AfterEach + void clearStore() { + for (AgentSpan key : storeKeys) { + REQUEST_MATCHES.remove(key); + } + } + + @Test + void storesTheDecodedPrefixAndTheBoundValues() { + AgentSpan localRoot = localRoot(); + + JaxRsRequestMatchCapture.capture(spanUnder(localRoot), BASE_URI, BOUND_VALUES); + + JaxRsRequestMatch match = (JaxRsRequestMatch) REQUEST_MATCHES.get(localRoot); + assertEquals("/c x/api/", match.prefix()); + assertEquals("/c%20x/api/files/{path}", render("/files/{path: .*}", match)); + } + + @Test + void anEmptyRawPathStoresARootMatch() { + AgentSpan localRoot = localRoot(); + + JaxRsRequestMatchCapture.capture( + spanUnder(localRoot), URI.create("http://localhost:8080"), singletonMap("path", "")); + + JaxRsRequestMatch match = (JaxRsRequestMatch) REQUEST_MATCHES.get(localRoot); + assertEquals("", match.prefix()); + assertEquals("/files", render("/files/{path: .*}", match)); + } + + @Test + void aNullBaseUriStoresNothing() { + AgentSpan localRoot = localRoot(); + + JaxRsRequestMatchCapture.capture(spanUnder(localRoot), null, BOUND_VALUES); + + assertNull(REQUEST_MATCHES.get(localRoot)); + } + + @Test + void aNullRawPathStoresNothing() { + AgentSpan localRoot = localRoot(); + + // an opaque URI has no path + JaxRsRequestMatchCapture.capture( + spanUnder(localRoot), URI.create("mailto:a@example.com"), BOUND_VALUES); + + assertNull(REQUEST_MATCHES.get(localRoot)); + } + + @Test + void noActiveSpanStoresNothing() { + assertDoesNotThrow(() -> JaxRsRequestMatchCapture.capture(null, BASE_URI, BOUND_VALUES)); + } + + @Test + void noLocalRootStoresNothing() { + AgentSpan span = mock(AgentSpan.class); + storeKeys.add(span); + + JaxRsRequestMatchCapture.capture(span, BASE_URI, BOUND_VALUES); + + assertNull(REQUEST_MATCHES.get(span)); + } + + @Test + void keepsASubResourceMark() { + AgentSpan localRoot = localRoot(); + REQUEST_MATCHES.put(localRoot, JaxRsRequestMatch.SUBRESOURCE); + + JaxRsRequestMatchCapture.capture(spanUnder(localRoot), BASE_URI, BOUND_VALUES); + + assertSame(JaxRsRequestMatch.SUBRESOURCE, REQUEST_MATCHES.get(localRoot)); + } + + @Test + void storesNothingWhenAppSecIsInactive() { + ActiveSubsystems.APPSEC_ACTIVE = false; + AgentSpan localRoot = localRoot(); + + JaxRsRequestMatchCapture.capture(spanUnder(localRoot), BASE_URI, BOUND_VALUES); + + assertNull(REQUEST_MATCHES.get(localRoot)); + } + + private AgentSpan localRoot() { + AgentSpan localRoot = mock(AgentSpan.class); + storeKeys.add(localRoot); + return localRoot; + } + + private static AgentSpan spanUnder(AgentSpan localRoot) { + AgentSpan span = mock(AgentSpan.class); + when(span.getLocalRootSpan()).thenReturn(localRoot); + return span; + } + + private static String render(String route, JaxRsRequestMatch match) { + RouteTemplate template = JaxRsRouteParser.cached(route); + return template.render(match.prefix(), match.presenceFor(template)); + } +} diff --git a/dd-java-agent/instrumentation/rs/jakarta-rs-annotations-3.0/src/main/java/datadog/trace/instrumentation/jakarta3/JakartaRsAnnotationsDecorator.java b/dd-java-agent/instrumentation/rs/jakarta-rs-annotations-3.0/src/main/java/datadog/trace/instrumentation/jakarta3/JakartaRsAnnotationsDecorator.java index a47f01b0b46..5974bf06b9b 100644 --- a/dd-java-agent/instrumentation/rs/jakarta-rs-annotations-3.0/src/main/java/datadog/trace/instrumentation/jakarta3/JakartaRsAnnotationsDecorator.java +++ b/dd-java-agent/instrumentation/rs/jakarta-rs-annotations-3.0/src/main/java/datadog/trace/instrumentation/jakarta3/JakartaRsAnnotationsDecorator.java @@ -6,6 +6,7 @@ import static datadog.trace.bootstrap.instrumentation.decorator.http.HttpResourceDecorator.HTTP_RESOURCE_DECORATOR; import datadog.trace.api.GenericClassValue; +import datadog.trace.api.KnownTags; import datadog.trace.api.Pair; import datadog.trace.api.appsec.route.JaxRsRequestMatch; import datadog.trace.api.appsec.route.JaxRsRouteParser; @@ -87,17 +88,16 @@ public void onJakartaRsSpan( // When jakarta-rs is the root, we want to name using the path, otherwise use the class/method. final boolean isRootScope = parent == null; if (isRootScope) { - markSubResourceLocator(span, httpMethodAndRoute); HTTP_RESOURCE_DECORATOR.withRoute( span, httpMethodAndRoute.getLeft(), httpMethodAndRoute.getRight()); - tagNormalizedRoute(span, httpMethodAndRoute.getRight()); + // No normalized route: without a server span, no capture advice stored a match for it. } else { span.setResourceName(DECORATE.spanNameForMethod(target, method)); final AgentSpan localRoot = parent.getLocalRootSpan(); - markSubResourceLocator(localRoot, httpMethodAndRoute); if (parent == localRoot) { parent.setTag(Tags.COMPONENT, "jakarta-rs"); + markSubResourceLocator(parent, httpMethodAndRoute); HTTP_RESOURCE_DECORATOR.withRoute( parent, httpMethodAndRoute.getLeft(), httpMethodAndRoute.getRight()); tagNormalizedRoute(parent, httpMethodAndRoute.getRight()); @@ -109,6 +109,7 @@ public void onJakartaRsSpan( // A locator returns before its subresource is dispatched. Its prefix is unavailable // when decorating that subresource, so keep the fallback route for this request. ROUTE_STATES.put(localRoot, RouteState.SUBRESOURCE); + markSubResourceLocator(localRoot, httpMethodAndRoute); } else if (ROUTE_STATES.get(localRoot) == null) { // Refine a server handler's catch-all route, but not from a nested resource call. HTTP_RESOURCE_DECORATOR.withRoute( @@ -122,8 +123,8 @@ public void onJakartaRsSpan( /** * Marks the request of {@code localRoot} as handled by a sub-resource locator (an annotated * method with a route but no http method): the route of its sub-resource methods is truncated, so - * they set no normalized route. Runs before the capture advice, which keeps the mark. Never - * throws. + * they set no normalized route. Only called where the locator decides {@code http.route}; runs + * before the capture advice, which keeps the mark. Never throws. */ private static void markSubResourceLocator( final AgentSpan localRoot, final Pair httpMethodAndRoute) { @@ -144,7 +145,9 @@ private static void markSubResourceLocator( /** * Sets {@code _dd.appsec.normalized_route} on {@code span}, the span that just received {@code * route} as {@code http.route} (the local root), from the request match a capture advice stored - * for it. No match (prefix unknown) or a sub-resource locator means no tag. Never throws. + * for it. A previous value is cleared first, so the last writer of {@code http.route} owns the + * tag (e.g. over Vert.x on Quarkus). No match (prefix unknown) or a sub-resource locator means no + * tag. Never throws. */ private static void tagNormalizedRoute(final AgentSpan span, final CharSequence route) { if (!NormalizedRouteHelper.isEnabled()) { @@ -160,6 +163,7 @@ private static void tagNormalizedRoute(final AgentSpan span, final CharSequence @VisibleForTesting static void tagNormalizedRoute( final AgentSpan span, final CharSequence route, final JaxRsRequestMatch match) { + span.setTag(KnownTags.DD_APPSEC_NORMALIZED_ROUTE, (String) null); if (match == null || match == JaxRsRequestMatch.SUBRESOURCE || route == null) { return; } diff --git a/dd-java-agent/instrumentation/rs/jakarta-rs-annotations-3.0/src/test/java/datadog/trace/instrumentation/jakarta3/JakartaRsNormalizedRouteTest.java b/dd-java-agent/instrumentation/rs/jakarta-rs-annotations-3.0/src/test/java/datadog/trace/instrumentation/jakarta3/JakartaRsNormalizedRouteTest.java index 384364440c5..0e4d31efc0b 100644 --- a/dd-java-agent/instrumentation/rs/jakarta-rs-annotations-3.0/src/test/java/datadog/trace/instrumentation/jakarta3/JakartaRsNormalizedRouteTest.java +++ b/dd-java-agent/instrumentation/rs/jakarta-rs-annotations-3.0/src/test/java/datadog/trace/instrumentation/jakarta3/JakartaRsNormalizedRouteTest.java @@ -8,10 +8,13 @@ import static datadog.trace.bootstrap.instrumentation.api.Tags.SPAN_KIND_SERVER; import static datadog.trace.instrumentation.jakarta3.JakartaRsAnnotationsDecorator.DECORATE; import static java.util.Collections.singletonMap; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -30,6 +33,7 @@ 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; /** @@ -120,14 +124,65 @@ void noTagWithoutACapturedMatch() { verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); } + /** A root jakarta-rs span has no server span, so no capture advice stores a match for it. */ @Test - void tagsTheRootSpan() throws Exception { + void noTagOnARootSpan() throws Exception { AgentSpan span = routedSpan(); store(span, "/"); DECORATE.onJakartaRsSpan(span, null, Files.class, get()); - verify(span).setTag(DD_APPSEC_NORMALIZED_ROUTE, "/ctx/files/"); + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), nullable(String.class)); + } + + @Test + void noTagForAMalformedRoute() { + AgentSpan span = routedSpan(); + + JakartaRsAnnotationsDecorator.tagNormalizedRoute( + span, "/users/{id", JaxRsRequestMatch.of("/ctx/", null)); + + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + } + + /** + * The last writer of http.route owns the tag: a previous value (e.g. from Vert.x on Quarkus) + * never survives a new route. + */ + @Test + void aNewRouteWithoutAMatchClearsAPreviousTag() { + assertClearedWithoutTag("/users/{id}", null); + } + + @Test + void aSubResourceLocatorMatchClearsAPreviousTag() { + assertClearedWithoutTag("/users/{id}", JaxRsRequestMatch.SUBRESOURCE); + } + + @Test + void aMalformedRouteClearsAPreviousTag() { + assertClearedWithoutTag("/users/{id", JaxRsRequestMatch.of("/ctx/", null)); + } + + @Test + void aNewRouteWithAMatchReplacesAPreviousTag() { + AgentSpan span = routedSpan(); + + JakartaRsAnnotationsDecorator.tagNormalizedRoute( + span, "/users/{id}", JaxRsRequestMatch.of("/ctx/", singletonMap("id", "42"))); + + InOrder inOrder = inOrder(span); + inOrder.verify(span).setTag(DD_APPSEC_NORMALIZED_ROUTE, (String) null); + inOrder.verify(span).setTag(DD_APPSEC_NORMALIZED_ROUTE, "/ctx/users/{id}"); + } + + private static void assertClearedWithoutTag(String route, JaxRsRequestMatch match) { + AgentSpan span = routedSpan(); + + JakartaRsAnnotationsDecorator.tagNormalizedRoute(span, route, match); + + verify(span).setTag(DD_APPSEC_NORMALIZED_ROUTE, (String) null); + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); } @Test @@ -161,22 +216,22 @@ void tagsTheLocalRootWhenItRefinesACatchAllRoute() throws Exception { @Test void noTagWithoutAStoredMatch() throws Exception { - AgentSpan span = routedSpan(); + AgentSpan parent = localRoot(); - DECORATE.onJakartaRsSpan(span, null, Files.class, get()); + DECORATE.onJakartaRsSpan(mock(AgentSpan.class), parent, Files.class, get()); - verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + verify(parent, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); } @Test void noTagWhenAppSecIsInactive() throws Exception { ActiveSubsystems.APPSEC_ACTIVE = false; - AgentSpan span = routedSpan(); - store(span, "/"); + AgentSpan parent = localRoot(); + store(parent, "/"); - DECORATE.onJakartaRsSpan(span, null, Files.class, get()); + DECORATE.onJakartaRsSpan(mock(AgentSpan.class), parent, Files.class, get()); - verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + verify(parent, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), nullable(String.class)); } @Test @@ -209,14 +264,52 @@ void aSubResourceLocatorMarksTheLocalRootAndPreventsTheTag() throws Exception { } @Test - void aRootSubResourceLocatorMarksItsSpan() throws Exception { + void aRootSubResourceLocatorDoesNotMark() throws Exception { AgentSpan span = routedSpan(); storeKeys.add(span); DECORATE.onJakartaRsSpan(span, null, Locator.class, locatorMethod()); - assertSame(JaxRsRequestMatch.SUBRESOURCE, REQUEST_MATCHES.get(span)); - verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + assertNull(REQUEST_MATCHES.get(span)); + } + + /** A nested locator under a server span that is not the local root sets no route: no mark. */ + @Test + void noMarkWhenTheLocatorDoesNotSetTheRoute() throws Exception { + AgentSpan localRoot = routedSpan(); + AgentSpan parent = mock(AgentSpan.class); + when(parent.getLocalRootSpan()).thenReturn(localRoot); + storeKeys.add(localRoot); + + DECORATE.onJakartaRsSpan(mock(AgentSpan.class), parent, Locator.class, locatorMethod()); + + assertNull(REQUEST_MATCHES.get(localRoot)); + } + + /** On Quarkus the locator keeps the server's catch-all route and marks the request. */ + @Test + void aLocatorUnderACatchAllServerRouteMarks() throws Exception { + AgentSpan localRoot = routedSpan(); + when(localRoot.getTag(HTTP_ROUTE)).thenReturn("/"); + AgentSpan parent = mock(AgentSpan.class); + when(parent.getLocalRootSpan()).thenReturn(localRoot); + when(parent.getTag(SPAN_KIND)).thenReturn(SPAN_KIND_SERVER); + storeKeys.add(localRoot); + + DECORATE.onJakartaRsSpan(mock(AgentSpan.class), parent, Locator.class, locatorMethod()); + + assertSame(JaxRsRequestMatch.SUBRESOURCE, REQUEST_MATCHES.get(localRoot)); + } + + @Test + void noMarkWhenAppSecIsInactive() throws Exception { + ActiveSubsystems.APPSEC_ACTIVE = false; + AgentSpan parent = localRoot(); + storeKeys.add(parent); + + DECORATE.onJakartaRsSpan(mock(AgentSpan.class), parent, Locator.class, locatorMethod()); + + assertNull(REQUEST_MATCHES.get(parent)); } private static CharSequence route(String expected) { @@ -240,6 +333,13 @@ private static Method get() throws NoSuchMethodException { return Files.class.getMethod("get"); } + /** A routed span that is its own local root, as a server span. */ + private static AgentSpan localRoot() { + AgentSpan localRoot = routedSpan(); + when(localRoot.getLocalRootSpan()).thenReturn(localRoot); + return localRoot; + } + /** A span that already carries {@code http.route}, as after {@code withRoute}. */ private static AgentSpan routedSpan() { AgentSpan span = mock(AgentSpan.class); diff --git a/dd-java-agent/instrumentation/rs/jax-rs/jax-rs-annotations/jax-rs-annotations-2.0/src/main/java/datadog/trace/instrumentation/jaxrs2/JaxRsAnnotationsDecorator.java b/dd-java-agent/instrumentation/rs/jax-rs/jax-rs-annotations/jax-rs-annotations-2.0/src/main/java/datadog/trace/instrumentation/jaxrs2/JaxRsAnnotationsDecorator.java index a2e28af3f26..33c6cc1dcd4 100644 --- a/dd-java-agent/instrumentation/rs/jax-rs/jax-rs-annotations/jax-rs-annotations-2.0/src/main/java/datadog/trace/instrumentation/jaxrs2/JaxRsAnnotationsDecorator.java +++ b/dd-java-agent/instrumentation/rs/jax-rs/jax-rs-annotations/jax-rs-annotations-2.0/src/main/java/datadog/trace/instrumentation/jaxrs2/JaxRsAnnotationsDecorator.java @@ -6,6 +6,7 @@ import static datadog.trace.bootstrap.instrumentation.decorator.http.HttpResourceDecorator.HTTP_RESOURCE_DECORATOR; import datadog.trace.api.GenericClassValue; +import datadog.trace.api.KnownTags; import datadog.trace.api.Pair; import datadog.trace.api.appsec.route.JaxRsRequestMatch; import datadog.trace.api.appsec.route.JaxRsRouteParser; @@ -81,16 +82,14 @@ public void onJaxRsSpan( final boolean isRootScope = parent == null; if (isRootScope) { if (httpMethodAndRoute.hasRight()) { // no route when no path was readable: keep the name - markSubResourceLocator(span, httpMethodAndRoute); HTTP_RESOURCE_DECORATOR.withRoute( span, httpMethodAndRoute.getLeft(), httpMethodAndRoute.getRight()); - tagNormalizedRoute(span, httpMethodAndRoute.getRight()); + // No normalized route: without a server span, no capture advice stored a match for it. } } else { span.setResourceName(DECORATE.spanNameForMethod(target, method)); final AgentSpan localRoot = parent.getLocalRootSpan(); - markSubResourceLocator(localRoot, httpMethodAndRoute); if (localRoot.getResourceNamePriority() < ResourceNamePriorities.HTTP_FRAMEWORK_ROUTE) { parent.setTag(Tags.COMPONENT, "jax-rs"); @@ -104,6 +103,7 @@ public void onJaxRsSpan( return; } + markSubResourceLocator(localRoot, httpMethodAndRoute); HTTP_RESOURCE_DECORATOR.withRoute( localRoot, httpMethodAndRoute.getLeft(), httpMethodAndRoute.getRight()); tagNormalizedRoute(localRoot, httpMethodAndRoute.getRight()); @@ -114,8 +114,8 @@ public void onJaxRsSpan( /** * Marks the request of {@code localRoot} as handled by a sub-resource locator (an annotated * method with a route but no http method): the route of its sub-resource methods is truncated, so - * they set no normalized route. Runs before the capture advice, which keeps the mark. Never - * throws. + * they set no normalized route. Only called where the locator sets {@code http.route}; runs + * before the capture advice, which keeps the mark. Never throws. */ private static void markSubResourceLocator( final AgentSpan localRoot, final Pair httpMethodAndRoute) { @@ -136,7 +136,8 @@ private static void markSubResourceLocator( /** * Sets {@code _dd.appsec.normalized_route} on {@code span}, the span that just received {@code * route} as {@code http.route} (the local root), from the request match a capture advice stored - * for it. No match (prefix unknown) or a sub-resource locator means no tag. Never throws. + * for it. A previous value is cleared first, so the last writer of {@code http.route} owns the + * tag. No match (prefix unknown) or a sub-resource locator means no tag. Never throws. */ private static void tagNormalizedRoute(final AgentSpan span, final CharSequence route) { if (!NormalizedRouteHelper.isEnabled()) { @@ -152,6 +153,7 @@ private static void tagNormalizedRoute(final AgentSpan span, final CharSequence @VisibleForTesting static void tagNormalizedRoute( final AgentSpan span, final CharSequence route, final JaxRsRequestMatch match) { + span.setTag(KnownTags.DD_APPSEC_NORMALIZED_ROUTE, (String) null); if (match == null || match == JaxRsRequestMatch.SUBRESOURCE || route == null) { return; } diff --git a/dd-java-agent/instrumentation/rs/jax-rs/jax-rs-annotations/jax-rs-annotations-2.0/src/test/java/datadog/trace/instrumentation/jaxrs2/JaxRsAnnotationsDecoratorTest.java b/dd-java-agent/instrumentation/rs/jax-rs/jax-rs-annotations/jax-rs-annotations-2.0/src/test/java/datadog/trace/instrumentation/jaxrs2/JaxRsAnnotationsDecoratorTest.java index c7c3ac8bae5..c129a7700fd 100644 --- a/dd-java-agent/instrumentation/rs/jax-rs/jax-rs-annotations/jax-rs-annotations-2.0/src/test/java/datadog/trace/instrumentation/jaxrs2/JaxRsAnnotationsDecoratorTest.java +++ b/dd-java-agent/instrumentation/rs/jax-rs/jax-rs-annotations/jax-rs-annotations-2.0/src/test/java/datadog/trace/instrumentation/jaxrs2/JaxRsAnnotationsDecoratorTest.java @@ -15,6 +15,7 @@ import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -26,6 +27,7 @@ import datadog.trace.bootstrap.ActiveSubsystems; import datadog.trace.bootstrap.ContextStore; import datadog.trace.bootstrap.instrumentation.api.AgentSpan; +import datadog.trace.bootstrap.instrumentation.api.ResourceNamePriorities; import java.lang.annotation.AnnotationFormatError; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -46,6 +48,7 @@ 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; /** @@ -316,14 +319,52 @@ void noTagForAMalformedRoute() { verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); } + /** A root jax-rs span has no server span, so no capture advice stores a match for it. */ @Test - void tagsTheRootSpanFromTheStoredMatch() throws Exception { + void noTagOnARootSpan() throws Exception { AgentSpan span = routedSpan(); store(span, JaxRsRequestMatch.of("/ctx/", singletonMap("path", "/"))); DECORATE.onJaxRsSpan(span, null, Files.class, Files.class.getMethod("get")); - verify(span).setTag(DD_APPSEC_NORMALIZED_ROUTE, "/ctx/files/"); + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), nullable(String.class)); + } + + /** The last writer of http.route owns the tag: a previous value never survives a new route. */ + @Test + void aNewRouteWithoutAMatchClearsAPreviousTag() { + assertClearedWithoutTag("/users/{id}", null); + } + + @Test + void aSubResourceLocatorMatchClearsAPreviousTag() { + assertClearedWithoutTag("/users/{id}", JaxRsRequestMatch.SUBRESOURCE); + } + + @Test + void aMalformedRouteClearsAPreviousTag() { + assertClearedWithoutTag("/users/{id", JaxRsRequestMatch.of("/ctx/", null)); + } + + @Test + void aNewRouteWithAMatchReplacesAPreviousTag() { + AgentSpan span = routedSpan(); + + JaxRsAnnotationsDecorator.tagNormalizedRoute( + span, "/users/{id}", JaxRsRequestMatch.of("/ctx/", singletonMap("id", "42"))); + + InOrder inOrder = inOrder(span); + inOrder.verify(span).setTag(DD_APPSEC_NORMALIZED_ROUTE, (String) null); + inOrder.verify(span).setTag(DD_APPSEC_NORMALIZED_ROUTE, "/ctx/users/{id}"); + } + + private static void assertClearedWithoutTag(String route, JaxRsRequestMatch match) { + AgentSpan span = routedSpan(); + + JaxRsAnnotationsDecorator.tagNormalizedRoute(span, route, match); + + verify(span).setTag(DD_APPSEC_NORMALIZED_ROUTE, (String) null); + verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); } @Test @@ -341,22 +382,24 @@ void tagsTheLocalRootSpanFromTheStoredMatch() throws Exception { @Test void noTagWithoutAStoredMatch() throws Exception { - AgentSpan span = routedSpan(); + AgentSpan localRoot = localRoot(); - DECORATE.onJaxRsSpan(span, null, Files.class, Files.class.getMethod("get")); + DECORATE.onJaxRsSpan( + mock(AgentSpan.class), localRoot, Files.class, Files.class.getMethod("get")); - verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + verify(localRoot, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); } @Test void noTagWhenAppSecIsInactive() throws Exception { ActiveSubsystems.APPSEC_ACTIVE = false; - AgentSpan span = routedSpan(); - store(span, JaxRsRequestMatch.of("/ctx/", null)); + AgentSpan localRoot = localRoot(); + store(localRoot, JaxRsRequestMatch.of("/ctx/", null)); - DECORATE.onJaxRsSpan(span, null, Files.class, Files.class.getMethod("get")); + DECORATE.onJaxRsSpan( + mock(AgentSpan.class), localRoot, Files.class, Files.class.getMethod("get")); - verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + verify(localRoot, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), nullable(String.class)); } @Test @@ -389,25 +432,37 @@ void aSubResourceLocatorMarksTheLocalRootAndPreventsTheTag() throws Exception { } @Test - void aRootSubResourceLocatorMarksItsSpan() throws Exception { + void aRootSubResourceLocatorDoesNotMark() throws Exception { AgentSpan span = routedSpan(); storeKeys.add(span); DECORATE.onJaxRsSpan(span, null, Locator.class, locatorMethod()); - assertSame(JaxRsRequestMatch.SUBRESOURCE, REQUEST_MATCHES.get(span)); - verify(span, never()).setTag(eq(DD_APPSEC_NORMALIZED_ROUTE), anyString()); + assertNull(REQUEST_MATCHES.get(span)); + } + + /** The framework already set the route, so the locator does not set it and does not mark. */ + @Test + void noMarkWhenTheFrameworkAlreadySetTheRoute() throws Exception { + AgentSpan localRoot = localRoot(); + when(localRoot.getResourceNamePriority()) + .thenReturn(ResourceNamePriorities.HTTP_FRAMEWORK_ROUTE); + storeKeys.add(localRoot); + + DECORATE.onJaxRsSpan(mock(AgentSpan.class), localRoot, Locator.class, locatorMethod()); + + assertNull(REQUEST_MATCHES.get(localRoot)); } @Test void noMarkWhenAppSecIsInactive() throws Exception { ActiveSubsystems.APPSEC_ACTIVE = false; - AgentSpan span = routedSpan(); - storeKeys.add(span); + AgentSpan localRoot = localRoot(); + storeKeys.add(localRoot); - DECORATE.onJaxRsSpan(span, null, Locator.class, locatorMethod()); + DECORATE.onJaxRsSpan(mock(AgentSpan.class), localRoot, Locator.class, locatorMethod()); - assertNull(REQUEST_MATCHES.get(span)); + assertNull(REQUEST_MATCHES.get(localRoot)); } private static CharSequence route(String expected) { @@ -427,6 +482,13 @@ private static Method subMethod() throws NoSuchMethodException { return SubResource.class.getMethod("get"); } + /** A routed span that is its own local root, as a server span. */ + private static AgentSpan localRoot() { + AgentSpan localRoot = routedSpan(); + when(localRoot.getLocalRootSpan()).thenReturn(localRoot); + return localRoot; + } + /** A span that already carries {@code http.route}, as after {@code withRoute}. */ private static AgentSpan routedSpan() { AgentSpan span = mock(AgentSpan.class);