Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,12 @@ class DropwizardTest extends HttpServerTest<DropwizardTestSupport> {
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -43,6 +50,14 @@ 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')
testImplementation libs.bundles.mockito
}

// tested in grizzly-http-2.3.20
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
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.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;
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<Object, Object> 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<String, ?> 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<String, ?> boundValues) {
try {
String rawBasePath = baseUri == null ? null : baseUri.getRawPath();
AgentSpan localRoot =
rawBasePath == null || span == null || !NormalizedRouteHelper.isEnabled()
? 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);
}
}
}
Original file line number Diff line number Diff line change
@@ -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<String, ?> 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);
}
}
}
Original file line number Diff line number Diff line change
@@ -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<Object, Object> 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<String, ?> BOUND_VALUES = singletonMap("path", singletonList("a/b"));

private final List<AgentSpan> 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));
}
}
Loading
Loading