Skip to content
Open
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 @@ -5,10 +5,13 @@
import static net.bytebuddy.matcher.ElementMatchers.isMethod;
import static net.bytebuddy.matcher.ElementMatchers.isPublic;
import static net.bytebuddy.matcher.ElementMatchers.takesArgument;
import static net.bytebuddy.matcher.ElementMatchers.takesArguments;

import com.google.auto.service.AutoService;
import datadog.trace.agent.tooling.Instrumenter;
import datadog.trace.agent.tooling.InstrumenterModule;
import java.util.Collections;
import java.util.Map;

@AutoService(InstrumenterModule.class)
public class RouteHandlerInstrumentation extends InstrumenterModule.Tracing
Expand All @@ -22,6 +25,12 @@ public String instrumentedType() {
return "io.vertx.ext.web.impl.RouteImpl";
}

/** Declared path of each route, as the app wrote it (with its trailing {@code *}). */
@Override
public Map<String, String> contextStore() {
return Collections.singletonMap("io.vertx.ext.web.Route", String.class.getName());
}

@Override
public void methodAdvice(MethodTransformer transformer) {
transformer.applyAdvice(
Expand All @@ -30,5 +39,11 @@ public void methodAdvice(MethodTransformer transformer) {
.and(isPublic())
.and(takesArgument(0, named("io.vertx.core.Handler"))),
packageName + ".RouteHandlerWrapperAdvice");
transformer.applyAdvice(
isMethod().and(named("setPath")).and(takesArguments(String.class)),
packageName + ".RouteSetPathAdvice");
transformer.applyAdvice(
isMethod().and(named("setRegex")).and(takesArguments(String.class)),
packageName + ".RouteSetRegexAdvice");
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package datadog.trace.instrumentation.vertx_3_4.server;

import static datadog.trace.api.appsec.route.VertxRouteParser.Grammar.LEGACY;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activateSpan;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activeSpan;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.startSpan;
Expand All @@ -8,23 +9,36 @@
import static datadog.trace.instrumentation.vertx_3_4.server.VertxDecorator.INSTRUMENTATION_NAME;

import datadog.context.ContextScope;
import datadog.trace.api.appsec.route.NormalizedRouteHelper;
import datadog.trace.api.appsec.route.VertxNormalizedRoute;
import datadog.trace.bootstrap.ContextStore;
import datadog.trace.bootstrap.instrumentation.api.AgentSpan;
import datadog.trace.bootstrap.instrumentation.api.Tags;
import io.vertx.core.Handler;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.impl.RouteImpl;
import io.vertx.ext.web.impl.RouterImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RouteHandlerWrapper implements Handler<RoutingContext> {
private static final Logger log = LoggerFactory.getLogger(RouteHandlerWrapper.class);

static final String PARENT_SPAN_CONTEXT_KEY = AgentSpan.class.getName() + ".parent";
static final String HANDLER_SPAN_CONTEXT_KEY = AgentSpan.class.getName() + ".handler";
static final String ROUTE_CONTEXT_KEY = "dd." + Tags.HTTP_ROUTE;

private final Handler<RoutingContext> actual;
private final boolean spanStarter;

public RouteHandlerWrapper(final Handler<RoutingContext> handler) {
/** Declared path of each route. */
private final ContextStore<Route, String> declaredPaths;

public RouteHandlerWrapper(
final Handler<RoutingContext> handler, final ContextStore<Route, String> declaredPaths) {
actual = handler;
this.declaredPaths = declaredPaths;
// When mounting a sub router, the handler is a lambda in either RouterImpl or RouteImpl, so
// this skips that. This prevents routers from creating a span during handling. In the event
// a route is not found, without this code, a span would be created for the router when it
Expand Down Expand Up @@ -106,6 +120,24 @@ private void setRoute(RoutingContext routingContext) {
if (method != null && path != null && shouldUpdateRoute(routingContext, parentSpan, path)) {
routingContext.put(ROUTE_CONTEXT_KEY, path);
HTTP_RESOURCE_DECORATOR.withRoute(parentSpan, method, path, true);
if (NormalizedRouteHelper.isEnabled()) {
tagNormalizedRoute(routingContext, parentSpan);
}
}
}

private void tagNormalizedRoute(final RoutingContext routingContext, final AgentSpan span) {
try {
final String declared = declaredPaths.get(routingContext.currentRoute());
VertxNormalizedRoute.tag(
span,
declared,
LEGACY,
routingContext.mountPoint(),
routingContext.normalisedPath(),
routingContext.pathParams());
} catch (Throwable t) {
log.debug("Failed to collect the Vert.x normalized route", t);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
package datadog.trace.instrumentation.vertx_3_4.server;

import datadog.trace.bootstrap.InstrumentationContext;
import io.vertx.core.Handler;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.RoutingContext;
import net.bytebuddy.asm.Advice;

public class RouteHandlerWrapperAdvice {
@Advice.OnMethodEnter(suppress = Throwable.class)
public static void wrapHandler(
@Advice.Argument(value = 0, readOnly = false) Handler<RoutingContext> handler) {
handler = new RouteHandlerWrapper(handler);
handler =
new RouteHandlerWrapper(handler, InstrumentationContext.get(Route.class, String.class));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package datadog.trace.instrumentation.vertx_3_4.server;

import datadog.trace.bootstrap.InstrumentationContext;
import io.vertx.ext.web.Route;
import net.bytebuddy.asm.Advice;

/**
* Keeps the path of {@code RouteImpl.setPath(String)} as declared: {@code Route.getPath()} drops
* the trailing {@code *}, so a catch-all route would look like an exact one.
*/
public class RouteSetPathAdvice {
@Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
public static void onExit(
@Advice.This final Route route,
@Advice.Argument(0) final String path,
@Advice.Thrown final Throwable thrown) {
if (thrown == null) {
InstrumentationContext.get(Route.class, String.class).put(route, path);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package datadog.trace.instrumentation.vertx_3_4.server;

import datadog.trace.bootstrap.InstrumentationContext;
import io.vertx.ext.web.Route;
import net.bytebuddy.asm.Advice;

/** A regex route has no declared path: drops any path stored by an earlier {@code path(..)}. */
public class RouteSetRegexAdvice {
@Advice.OnMethodExit(suppress = Throwable.class)
public static void onExit(@Advice.This final Route route) {
InstrumentationContext.get(Route.class, String.class).remove(route);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,12 @@ class VertxHttpServerForkedTest extends HttpServerTest<Vertx> {
}
}

@Override
Serializable expectedNormalizedRoute(ServerEndpoint endpoint) {
def route = endpoint == PATH_PARAM ? routerBasePath() + "path/{id}/param" : expectedServerSpanRoute(endpoint)
normalizedRouteOf('', route)
}

@Override
void handlerSpan(TraceAssert trace, ServerEndpoint endpoint = SUCCESS) {
if (endpoint == NOT_FOUND) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
package server.normalizedroute;

import static datadog.trace.api.appsec.route.NormalizedRouteHelper.NORMALIZED_ROUTE_TAG;
import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_ROUTE;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;

import datadog.trace.agent.test.AbstractInstrumentationTest;
import datadog.trace.agent.test.utils.OkHttpUtils;
import datadog.trace.bootstrap.ActiveSubsystems;
import datadog.trace.core.DDSpan;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestInstance;

/**
* Runs a Vert.x 3.x server with the normalized route test routes, with AppSec forced active like
* the Spock {@code InstrumentationSpecification}, and returns the tags of the server span.
*/
@TestInstance(PER_CLASS)
abstract class AbstractVertxNormalizedRouteTest extends AbstractInstrumentationTest {

private static final long TIMEOUT_SECONDS = 10;

/** Operation name of the server span, which carries both route tags. */
private static final String SERVER_SPAN = "netty.request";

private final OkHttpClient client = OkHttpUtils.client();
Vertx vertx;
private HttpServer server;
private int port;
private boolean appSecActiveBefore;
private boolean paramMountSupported;

@BeforeAll
void startServer() throws Exception {
vertx = Vertx.vertx();
Router router = Router.router(vertx);
router.route("/").handler(AbstractVertxNormalizedRouteTest::ok);
router.route("/multi/:id.:format").handler(AbstractVertxNormalizedRouteTest::ok);
router.route("/three/:a-:b-:c").handler(AbstractVertxNormalizedRouteTest::ok);
router.route("/static-text/user-:id").handler(AbstractVertxNormalizedRouteTest::ok);
router.route("/catch-all/*").handler(AbstractVertxNormalizedRouteTest::ok);
router.route("/encoded/caf%C3%A9").handler(AbstractVertxNormalizedRouteTest::ok);
router.routeWithRegex("/regex/(\\d+)").handler(AbstractVertxNormalizedRouteTest::ok);
// middleware with a declared path, then a regex route: the regex route must not keep its tag
router.route("/stale/*").handler(RoutingContext::next);
router.routeWithRegex("/stale/(\\d+)").handler(AbstractVertxNormalizedRouteTest::ok);
// same, but the regex route also has a path, so http.route is updated by the regex route
router.route("/stale-path/*").handler(RoutingContext::next);
router
.route("/stale-path/x")
.pathRegex("/stale-path/(\\d+)")
.handler(AbstractVertxNormalizedRouteTest::ok);

Router sub = Router.router(vertx);
sub.route("/users/:id").handler(AbstractVertxNormalizedRouteTest::ok);
sub.route("/files/*").handler(AbstractVertxNormalizedRouteTest::ok);
router.mountSubRouter("/sub", sub);

// a mount with a parameter (3.8.2+; 3.4 rejects patterns in sub-router mounts): the mount point
// is the concrete matched prefix
Router tenant = Router.router(vertx);
tenant.route("/items/:id").handler(AbstractVertxNormalizedRouteTest::ok);
try {
router.mountSubRouter("/:tenant/api", tenant);
paramMountSupported = true;
} catch (IllegalArgumentException e) {
paramMountSupported = false;
}

server =
await(
handler -> vertx.createHttpServer().requestHandler(router::accept).listen(0, handler));
port = server.actualPort();
}

@AfterAll
void stopServer() throws Exception {
if (server != null) {
AbstractVertxNormalizedRouteTest.<Void>await(server::close);
}
if (vertx != null) {
AbstractVertxNormalizedRouteTest.<Void>await(vertx::close);
}
}

@BeforeEach
void forceAppSecActive() {
appSecActiveBefore = ActiveSubsystems.APPSEC_ACTIVE;
ActiveSubsystems.APPSEC_ACTIVE = true;
}

@AfterEach
void restoreAppSecActive() {
ActiveSubsystems.APPSEC_ACTIVE = appSecActiveBefore;
}

private static void ok(RoutingContext ctx) {
ctx.response().setStatusCode(200).end("ok");
}

/**
* Starts the callback-style Vert.x {@code operation} and waits for its result; a failure is
* rethrown on the test thread.
*/
private static <T> T await(Consumer<Handler<AsyncResult<T>>> operation) throws Exception {
CountDownLatch done = new CountDownLatch(1);
AtomicReference<T> result = new AtomicReference<>();
AtomicReference<Throwable> failure = new AtomicReference<>();
operation.accept(ar -> {
if (ar.succeeded()) {
result.set(ar.result());
} else {
failure.set(ar.cause());
}
done.countDown();
});
if (!done.await(TIMEOUT_SECONDS, SECONDS)) {
throw new IllegalStateException("Vert.x operation did not complete in time");
}
if (failure.get() != null) {
throw new RuntimeException("Vert.x operation failed", failure.get());
}
return result.get();
}

/** Whether this Vert.x version accepted the {@code /:tenant/api} sub-router mount. */
boolean paramMountSupported() {
return paramMountSupported;
}

/** Sends {@code GET path} and returns the HTTP status. */
int get(String path) throws Exception {
Request request = new Request.Builder().url("http://localhost:" + port + path).get().build();
try (Response response = client.newCall(request).execute()) {
return response.code();
}
}

/** Tags of the {@link #SERVER_SPAN} span of the single trace written. */
Map<String, Object> serverSpanTags() throws Exception {
writer.waitForTraces(1);
DDSpan serverSpan = null;
for (List<DDSpan> trace : writer) {
for (DDSpan span : trace) {
if (SERVER_SPAN.equals(span.getOperationName().toString())) {
serverSpan = span;
}
}
}
assertNotNull(serverSpan, SERVER_SPAN + " span");
return serverSpan.getTags();
}

/**
* Sends {@code GET request}, expects a 200 with {@code expectedHttpRoute} (null for none) as
* {@code http.route} and no normalized route.
*/
void assertNoNormalizedRoute(String request, String expectedHttpRoute) throws Exception {
assertEquals(200, get(request));
Map<String, Object> tags = serverSpanTags();

assertEquals(expectedHttpRoute, Objects.toString(tags.get(HTTP_ROUTE), null));
assertNull(tags.get(NORMALIZED_ROUTE_TAG));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package server.normalizedroute;

import datadog.trace.api.config.AppSecConfig;
import datadog.trace.test.junit.utils.config.WithConfig;
import org.junit.jupiter.api.Test;

/** With API Security disabled the normalized route is not set; {@code http.route} still is. */
@WithConfig(key = AppSecConfig.API_SECURITY_ENABLED, value = "false")
class VertxNormalizedRouteApiSecurityDisabledForkedTest extends AbstractVertxNormalizedRouteTest {

@Test
void noNormalizedRouteWhenApiSecurityIsDisabled() throws Exception {
assertNoNormalizedRoute("/multi/1.json", "/multi/:id.:format");
}
}
Loading
Loading