From 72321539ddc41c82b829c9c88ca35cdd577405ad Mon Sep 17 00:00:00 2001 From: Abhigya Date: Mon, 2 Nov 2026 16:58:30 +0530 Subject: [PATCH] fix(elbv2): add X-Amzn-Trace-Id to requests forwarded to targets (#7280) An ALB adds or updates X-Amzn-Trace-Id before it sends a request to a target, but Floci passed through only what the client sent. Generate a Root field when the header is absent, insert or update a Self field when it is present, keep other fields, and rewrite to a new Root field above 7 KB of request headers. --- docs/services/elb.md | 1 + .../floci/services/elbv2/ElbV2DataPlane.java | 1 + .../services/elbv2/ElbV2TraceHeader.java | 66 ++++++++++ .../ElbV2TraceHeaderIntegrationTest.java | 120 ++++++++++++++++++ .../services/elbv2/ElbV2TraceHeaderTest.java | 62 +++++++++ 5 files changed, 250 insertions(+) create mode 100644 src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2TraceHeader.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TraceHeaderIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TraceHeaderTest.java diff --git a/docs/services/elb.md b/docs/services/elb.md index 823283498d..45528ddaf9 100644 --- a/docs/services/elb.md +++ b/docs/services/elb.md @@ -131,6 +131,7 @@ Gateway Load Balancer listeners require omitted `Port` and `Protocol` fields on stickiness is not applied with target-group cross-zone balancing disabled or `weighted_random` routing. - `routing.http.preserve_host_header.enabled` (default `false`) controls whether the original client Host header is forwarded to targets unchanged, or replaced with the target's `host:port`. - `RegisterTargets` rejects link-local and cloud instance-metadata addresses (`169.254.0.0/16`, `fe80::/10`, `fd00:ec2::254`) with `InvalidTarget`, and the load balancer and its health checks refuse to connect to them. Loopback and private addresses stay reachable so a load balancer can front a neighbouring container. +- Requests forwarded to a target carry `X-Amzn-Trace-Id`. A request without the header gets a new `Root` field, a request with a `Root` field gets a new `Self` field, and an existing `Self` field is updated. Other fields are kept. Above 7 KB of request headers the header is rewritten to a new `Root` field. Floci does not send these traces to X-Ray. ## Forwarding and network-security boundaries diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java index 3689303307..942623b984 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java +++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java @@ -1045,6 +1045,7 @@ public class ElbV2DataPlane { } private void executeForward(HttpServerRequest req, Action action, String region, String listenerArn) { + ElbV2TraceHeader.update(req.headers()); String tgArn = resolveTgArn(action); if (tgArn == null) { req.response().setStatusCode(502).end("No target group"); diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2TraceHeader.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2TraceHeader.java new file mode 100644 index 0000000000..f72fcd5b0c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2TraceHeader.java @@ -0,0 +1,66 @@ +package io.github.hectorvent.floci.services.elbv2; + +import io.vertx.core.MultiMap; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; + +/** + * The {@code X-Amzn-Trace-Id} header an Application Load Balancer adds or updates before it sends a + * request to a target. Each field has the form {@code Field=1-<8 hex epoch seconds>-<24 hex id>}. + */ +final class ElbV2TraceHeader { + + static final String NAME = "X-Amzn-Trace-Id"; + + private static final int REWRITE_ABOVE_BYTES = 7 * 1024; + private static final String ROOT = "Root="; + private static final String SELF = "Self="; + + private ElbV2TraceHeader() { + } + + static void update(MultiMap headers) { + String received = String.join(";", headers.getAll(NAME)); + headers.set(NAME, next(received, headerBytes(headers) > REWRITE_ABOVE_BYTES)); + } + + static String next(String received, boolean oversized) { + List fields = new ArrayList<>(); + if (!oversized) { + for (String field : received.split(";")) { + if (!field.isBlank()) { + fields.add(field.trim()); + } + } + } + boolean hasRoot = false; + for (int i = 0; i < fields.size(); i++) { + if (fields.get(i).startsWith(SELF)) { + fields.set(i, SELF + traceId()); + return String.join(";", fields); + } + hasRoot |= fields.get(i).startsWith(ROOT); + } + fields.addFirst(hasRoot ? SELF + traceId() : ROOT + traceId()); + return String.join(";", fields); + } + + private static int headerBytes(MultiMap headers) { + int total = 0; + for (Map.Entry header : headers) { + total += header.getKey().length() + header.getValue().length(); + } + return total; + } + + private static String traceId() { + byte[] id = new byte[12]; + ThreadLocalRandom.current().nextBytes(id); + return "1-" + String.format("%08x", Instant.now().getEpochSecond()) + "-" + HexFormat.of().formatHex(id); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TraceHeaderIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TraceHeaderIntegrationTest.java new file mode 100644 index 0000000000..f47154cb8f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TraceHeaderIntegrationTest.java @@ -0,0 +1,120 @@ +package io.github.hectorvent.floci.services.elbv2; + +import io.github.hectorvent.floci.testing.RealElbV2DataPlaneProfile; +import io.github.hectorvent.floci.testutil.FreePorts; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpClient; +import io.vertx.core.http.HttpServer; +import io.vertx.core.http.WebSocket; +import io.vertx.core.http.WebSocketConnectOptions; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import static io.github.hectorvent.floci.testing.AlbFixtures.createListener; +import static io.github.hectorvent.floci.testing.AlbFixtures.createLoadBalancer; +import static io.github.hectorvent.floci.testing.AlbFixtures.createTargetGroup; +import static io.github.hectorvent.floci.testing.AlbFixtures.deleteListener; +import static io.github.hectorvent.floci.testing.AlbFixtures.deleteLoadBalancer; +import static io.github.hectorvent.floci.testing.AlbFixtures.deleteTargetGroup; +import static io.github.hectorvent.floci.testing.AlbFixtures.registerTarget; +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.matchesPattern; + +/** What a target receives through a real listener socket, against the ALB request tracing guide. */ +@QuarkusTest +@TestProfile(RealElbV2DataPlaneProfile.class) +class ElbV2TraceHeaderIntegrationTest { + + private static final String ID = "1-[0-9a-f]{8}-[0-9a-f]{24}"; + private static final String ROOT = "Root=1-67891233-abcdef012345678912345678"; + + @Inject + Vertx vertx; + + private final CompletableFuture handshake = new CompletableFuture<>(); + private HttpServer backend; + private int listenerPort; + private String loadBalancerArn; + private String targetGroupArn; + private String listenerArn; + + @BeforeEach + void startBackend() throws Exception { + backend = vertx.createHttpServer() + .requestHandler(request -> { + String trace = String.valueOf(request.getHeader(ElbV2TraceHeader.NAME)); + if ("websocket".equalsIgnoreCase(request.getHeader("Upgrade"))) { + handshake.complete(trace); + request.toWebSocket(); + return; + } + request.response().end(trace); + }) + .listen(0, "127.0.0.1") + .toCompletionStage() + .toCompletableFuture() + .get(2, TimeUnit.SECONDS); + listenerPort = FreePorts.anyInterfacePort(); + loadBalancerArn = createLoadBalancer("trace-header-lb"); + targetGroupArn = createTargetGroup("trace-header-tg", "ip", backend.actualPort()); + registerTarget(targetGroupArn, "127.0.0.1", backend.actualPort()); + listenerArn = createListener(loadBalancerArn, targetGroupArn, listenerPort); + await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> given() + .baseUri("http://127.0.0.1").port(listenerPort) + .get("/").then().statusCode(200)); + } + + @AfterEach + void stopBackend() throws Exception { + deleteListener(listenerArn); + deleteTargetGroup(targetGroupArn); + deleteLoadBalancer(loadBalancerArn); + backend.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS); + } + + @Test + void targetReceivesAGeneratedRootField() { + String seen = given().baseUri("http://127.0.0.1").port(listenerPort).get("/").asString(); + + assertThat(seen, matchesPattern("Root=" + ID)); + } + + @Test + void targetReceivesASelfFieldForACallersRoot() { + String seen = given().baseUri("http://127.0.0.1").port(listenerPort) + .header(ElbV2TraceHeader.NAME, ROOT + ";CalledFrom=app") + .get("/").asString(); + + assertThat(seen, matchesPattern("Self=" + ID + ";" + ROOT + ";CalledFrom=app")); + } + + @Test + void webSocketHandshakeCarriesTheHeader() throws Exception { + HttpClient client = vertx.createHttpClient(); + try { + WebSocket socket = client.webSocket(new WebSocketConnectOptions() + .setHost("127.0.0.1") + .setPort(listenerPort) + .setURI("/socket")) + .toCompletionStage() + .toCompletableFuture() + .get(5, TimeUnit.SECONDS); + String seen = handshake.get(5, TimeUnit.SECONDS); + socket.close(); + + assertThat(seen, matchesPattern("Root=" + ID)); + } finally { + client.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TraceHeaderTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TraceHeaderTest.java new file mode 100644 index 0000000000..27fbeef114 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2TraceHeaderTest.java @@ -0,0 +1,62 @@ +package io.github.hectorvent.floci.services.elbv2; + +import io.vertx.core.MultiMap; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.matchesPattern; +import static org.hamcrest.Matchers.not; + +class ElbV2TraceHeaderTest { + + private static final String ID = "1-[0-9a-f]{8}-[0-9a-f]{24}"; + private static final String ROOT = "Root=1-67891233-abcdef012345678912345678"; + private static final String OLD_SELF = "1-67891233-000000000000000000000000"; + + @Test + void absentHeaderGetsARootField() { + assertThat(ElbV2TraceHeader.next("", false), matchesPattern("Root=" + ID)); + } + + @Test + void rootFieldGetsASelfFieldInFrontOfIt() { + assertThat(ElbV2TraceHeader.next(ROOT, false), matchesPattern("Self=" + ID + ";" + ROOT)); + } + + @Test + void customFieldsArePreserved() { + assertThat(ElbV2TraceHeader.next(ROOT + ";CalledFrom=app", false), + matchesPattern("Self=" + ID + ";" + ROOT + ";CalledFrom=app")); + } + + @Test + void existingSelfFieldIsUpdatedInPlace() { + String updated = ElbV2TraceHeader.next("Self=" + OLD_SELF + ";" + ROOT, false); + + assertThat(updated, matchesPattern("Self=" + ID + ";" + ROOT)); + assertThat(updated, not(matchesPattern(".*" + OLD_SELF + ".*"))); + } + + @Test + void customFieldsWithoutARootGetARootField() { + assertThat(ElbV2TraceHeader.next("CalledFrom=app", false), matchesPattern("Root=" + ID + ";CalledFrom=app")); + } + + @Test + void oversizedRequestIsRewrittenToARootField() { + assertThat(ElbV2TraceHeader.next(ROOT + ";CalledFrom=app", true), matchesPattern("Root=" + ID)); + } + + @Test + void updateMeasuresTheRequestHeaders() { + MultiMap small = MultiMap.caseInsensitiveMultiMap().add("x-amzn-trace-id", ROOT); + ElbV2TraceHeader.update(small); + assertThat(small.get(ElbV2TraceHeader.NAME), matchesPattern("Self=" + ID + ";" + ROOT)); + + MultiMap large = MultiMap.caseInsensitiveMultiMap() + .add("x-amzn-trace-id", ROOT) + .add("X-Large", "x".repeat(8 * 1024)); + ElbV2TraceHeader.update(large); + assertThat(large.get(ElbV2TraceHeader.NAME), matchesPattern("Root=" + ID)); + } +}