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 @@ -2,18 +2,27 @@

import static datadog.trace.bootstrap.instrumentation.decorator.http.HttpResourceDecorator.HTTP_RESOURCE_DECORATOR;

import datadog.trace.api.appsec.route.NormalizedRouteHelper;
import datadog.trace.api.appsec.route.RatpackPresenceResolver;
import datadog.trace.api.appsec.route.RatpackRouteParser;
import datadog.trace.api.appsec.route.RouteTemplate;
import datadog.trace.bootstrap.instrumentation.api.AgentPropagation;
import datadog.trace.bootstrap.instrumentation.api.AgentSpan;
import datadog.trace.bootstrap.instrumentation.api.URIDataAdapter;
import datadog.trace.bootstrap.instrumentation.api.UTF8BytesString;
import datadog.trace.bootstrap.instrumentation.decorator.HttpServerDecorator;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ratpack.handling.Context;
import ratpack.http.Request;
import ratpack.http.Response;
import ratpack.http.Status;
import ratpack.path.PathBinding;
import ratpack.path.internal.RootPathBinding;

public class RatpackServerDecorator extends HttpServerDecorator<Request, Request, Response, Void> {
private static final Logger log = LoggerFactory.getLogger(RatpackServerDecorator.class);
public static final CharSequence RATPACK_HANDLER = UTF8BytesString.create("ratpack.handler");
public static final CharSequence RATPACK = UTF8BytesString.create("ratpack");
public static final RatpackServerDecorator DECORATE = new RatpackServerDecorator();
Expand Down Expand Up @@ -79,15 +88,47 @@ protected int status(final Response response) {
}

public void onContext(final AgentSpan span, final Context ctx) {

String description = ctx.getPathBinding().getDescription();
final PathBinding binding = ctx.getPathBinding();
final String rawDescription = binding.getDescription();
String description = rawDescription;
if (description == null || description.isEmpty()) {
description = "/";
} else if (!description.startsWith("/")) {
description = "/" + description;
}

HTTP_RESOURCE_DECORATOR.withRoute(span, ctx.getRequest().getMethod().getName(), description);

if (NormalizedRouteHelper.isEnabled()) {
tagNormalizedRoute(span, binding, rawDescription);
}
}

/**
* No mount prefix: the description already holds the whole {@code prefix(...)} chain and Ratpack
* has no context path. A {@link RootPathBinding} means no route was declared, so no tag.
*/
private static void tagNormalizedRoute(
final AgentSpan span, final PathBinding binding, final String rawDescription) {
try {
if (binding instanceof RootPathBinding) {
return;
}
final String boundTo = binding.getBoundTo();
final String remainder = binding.getPastBinding();
final boolean hasRemainder = remainder != null && !remainder.isEmpty();
final RouteTemplate template =
RatpackRouteParser.cached(
rawDescription, boundTo == null || boundTo.isEmpty(), hasRemainder);
NormalizedRouteHelper.tag(
span,
template,
null,
RatpackPresenceResolver.of(
template, binding.getAllTokens(), hasRemainder ? remainder : null));
} catch (final Throwable t) {
log.debug("Failed to compute the normalized route", t);
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import datadog.trace.agent.test.InstrumentationSpecification
import datadog.trace.agent.test.utils.OkHttpUtils
import datadog.trace.api.DDSpanTypes
import datadog.trace.api.appsec.route.NormalizedRouteHelper
import datadog.trace.bootstrap.instrumentation.api.Tags
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
Expand Down Expand Up @@ -78,6 +79,7 @@ class RatpackOtherTest extends InstrumentationSpecification {
"$Tags.HTTP_METHOD" "GET"
"$Tags.HTTP_STATUS" 200
"$Tags.HTTP_ROUTE" "/$route"
"$NormalizedRouteHelper.NORMALIZED_ROUTE_TAG" normalizedRoute
"$Tags.HTTP_USER_AGENT" String
"$Tags.HTTP_CLIENT_IP" "127.0.0.1"
"$Tags.NETWORK_CLIENT_IP" "127.0.0.1"
Expand All @@ -100,6 +102,7 @@ class RatpackOtherTest extends InstrumentationSpecification {
"$Tags.HTTP_METHOD" "GET"
"$Tags.HTTP_STATUS" 200
"$Tags.HTTP_ROUTE" "/$route"
"$NormalizedRouteHelper.NORMALIZED_ROUTE_TAG" normalizedRoute
"$Tags.HTTP_CLIENT_IP" "127.0.0.1"
"$Tags.NETWORK_CLIENT_IP" "127.0.0.1"
defaultTags()
Expand All @@ -109,17 +112,17 @@ class RatpackOtherTest extends InstrumentationSpecification {
}

where:
path | route
"a" | "a"
"b/123" | "b/::\\d+"
"c" | "c/:val?"
"c/123" | "c/:val?"
"c/foo" | "c/:val?"
"d/123" | "d/:val"
"d/foo" | "d/:val"
"e" | "e/:val?:\\d+"
"e/123" | "e/:val?:\\d+"
"e/foo" | "e/:val?:\\d+"
"f/123" | "f/:val:\\d+"
path | route | normalizedRoute
"a" | "a" | "/a"
"b/123" | "b/::\\d+" | "/b/{param1}"
"c" | "c/:val?" | "/c"
"c/123" | "c/:val?" | "/c/{val}"
"c/foo" | "c/:val?" | "/c/{val}"
"d/123" | "d/:val" | "/d/{val}"
"d/foo" | "d/:val" | "/d/{val}"
"e" | "e/:val?:\\d+" | "/e"
"e/123" | "e/:val?:\\d+" | "/e/{val}"
"e/foo" | "e/:val?:\\d+" | "/e/{param1}" // optional absent, "foo" is the unbound remainder
"f/123" | "f/:val:\\d+" | "/f/{val}"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import datadog.trace.api.Config
import datadog.trace.api.DDSpanTypes
import datadog.trace.api.DDTags
import datadog.trace.api.KnownTags
import datadog.trace.api.appsec.route.NormalizedRouteHelper
import datadog.trace.bootstrap.instrumentation.api.Tags
import datadog.trace.instrumentation.netty41.server.NettyHttpServerDecorator
import datadog.trace.instrumentation.ratpack.RatpackServerDecorator
Expand Down Expand Up @@ -119,6 +120,12 @@ class RatpackHttpServerTest extends HttpServerTest<EmbeddedApp> {
return endpoint == PATH_PARAM ? testPathParam() : endpoint.rawPath
}

@Override
Serializable expectedNormalizedRoute(ServerEndpoint endpoint) {
// Every endpoint is a prefix(...) { all {} } hit exactly, except get('path/:id/param')
return endpoint == PATH_PARAM ? '/path/{id}/param' : endpoint.rawPath
}

@Override
boolean hasDecodedResource() {
false
Expand All @@ -135,6 +142,7 @@ class RatpackHttpServerTest extends HttpServerTest<EmbeddedApp> {
def otelSemantics = Config.get().isTraceOtelSemanticsEnabled()
def requestUrl = endpoint.resolve(address)
def expectedRoute = expectedServerSpanRoute(endpoint)
def expectedNormalizedRoute = expectedNormalizedRoute(endpoint)
trace.span {
serviceName expectedServiceName()
operationName "ratpack.handler"
Expand All @@ -159,6 +167,9 @@ class RatpackHttpServerTest extends HttpServerTest<EmbeddedApp> {
"$Tags.HTTP_METHOD" String
"$Tags.HTTP_STATUS" Integer
"$Tags.HTTP_ROUTE" expectedRoute
if (null != expectedNormalizedRoute) {
"$NormalizedRouteHelper.NORMALIZED_ROUTE_TAG" expectedNormalizedRoute
}
"$Tags.HTTP_CLIENT_IP" (endpoint == FORWARDED ? endpoint.body : '127.0.0.1')
"$Tags.NETWORK_CLIENT_IP" '127.0.0.1'
if (endpoint == EXCEPTION) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
package test.normalizedroute;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;

import datadog.trace.agent.test.AbstractInstrumentationTest;
import datadog.trace.agent.test.utils.OkHttpUtils;
import datadog.trace.bootstrap.ActiveSubsystems;
import datadog.trace.core.DDSpan;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
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;
import ratpack.handling.Handler;
import ratpack.test.embed.EmbeddedApp;

/**
* Runs an embedded Ratpack app with the route shapes that need presence logic in the normalized
* route, with AppSec forced active like the Spock {@code InstrumentationSpecification}, and returns
* the tags of the {@code netty.request} and {@code ratpack.handler} spans of a request.
*/
@TestInstance(PER_CLASS)
abstract class AbstractNormalizedRouteTest extends AbstractInstrumentationTest {

static final String NETTY_SPAN = "netty.request";
static final String RATPACK_SPAN = "ratpack.handler";

private static final Handler OK = ctx -> ctx.render("ok");

private final OkHttpClient client = OkHttpUtils.client();
private EmbeddedApp app;
private boolean appSecActiveBefore;

@BeforeAll
void startApp() {
app =
EmbeddedApp.fromHandlers(chain ->
chain
.get("api_security/optional-segment/:id/:tab?", OK)
.get("api_security/optional-chain/:x?/:y?", OK)
.prefix("api_security/catch-all", c -> c.all(OK))
.get("api_security/encoded/caf%C3%A9", OK)
.prefix("users", c -> c.get(OK).get(":id", OK))
.prefix("t/:tenant", c -> c.get("items/:id", OK))
.get("regex/:id:\\d+", OK)
.get("unnamed/::\\d+", OK)
.prefix("pfx/::\\d+", c -> c.all(OK))
.get("files/:name.json", OK)
.get("fmt/:f?.json", OK)
.prefix(
"err/:tenant",
c ->
c.get(
"boom/:id",
ctx -> {
throw new RuntimeException("boom");
})
.get("bad/:id", ctx -> ctx.clientError(400)))
.prefix("dup/:id", c -> c.get(":id?", OK))
.get("", OK));
// starts the server
app.getAddress();
}

/** The shared app with the routes declared in {@link #startApp()}. */
EmbeddedApp app() {
return app;
}

@AfterAll
void stopApp() {
if (app != null) {
app.close();
}
}

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

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

/** Sends {@code GET path}, expects a 200 and returns the span tags by operation name. */
Map<String, Map<String, Object>> spanTags(String path) throws Exception {
return spanTags(path, 200);
}

/** Sends {@code GET path}, expects {@code status} and returns the span tags by operation name. */
Map<String, Map<String, Object>> spanTags(String path, int status) throws Exception {
return spanTags(app, "GET", path, status);
}

/**
* Sends {@code method path} to {@code target}, expects {@code status} and returns the tags of the
* {@code netty.request} and {@code ratpack.handler} spans by operation name. The URL is parsed
* from the literal string so empty segments and percent-encoded octets reach the server
* unchanged.
*/
Map<String, Map<String, Object>> spanTags(
EmbeddedApp target, String method, String path, int status) throws Exception {
String base = target.getAddress().toString();
if (base.endsWith("/")) {
base = base.substring(0, base.length() - 1);
}
HttpUrl url = HttpUrl.parse(base + path);
assertNotNull(url, "url");
assertEquals(path, url.encodedPath(), "the client must not normalize the path");
RequestBody body = "GET".equals(method) ? null : RequestBody.create(null, new byte[0]);
Request request = new Request.Builder().url(url).method(method, body).build();
try (Response response = client.newCall(request).execute()) {
assertEquals(status, response.code());
}
writer.waitForTraces(1);
Map<String, Map<String, Object>> tags = new HashMap<>();
for (List<DDSpan> trace : writer) {
for (DDSpan span : trace) {
String name = span.getOperationName().toString();
if (NETTY_SPAN.equals(name) || RATPACK_SPAN.equals(name)) {
tags.put(name, span.getTags());
}
}
}
assertNotNull(tags.get(NETTY_SPAN), NETTY_SPAN + " span");
assertNotNull(tags.get(RATPACK_SPAN), RATPACK_SPAN + " span");
return tags;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package test.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 NormalizedRouteApiSecurityDisabledForkedTest extends AbstractNormalizedRouteTest {

@Test
void noNormalizedRouteWhenApiSecurityIsDisabled() throws Exception {
Map<String, Map<String, Object>> tags = spanTags("/regex/12");

for (String span : new String[] {NETTY_SPAN, RATPACK_SPAN}) {
assertEquals("/regex/:id:\\d+", String.valueOf(tags.get(span).get(HTTP_ROUTE)), span);
assertNull(tags.get(span).get(NORMALIZED_ROUTE_TAG), span);
}
}
}
Loading
Loading