fix(elbv2): add X-Forwarded headers to ALB requests as AWS does (#7278)

* fix(elbv2): add X-Forwarded headers to ALB requests as AWS does

An ALB forwarded client headers unchanged, so a target never learned the
client address and trusted whatever X-Forwarded-For the client sent. The
routing.http.xff_* attributes were stored but never read.

Apply routing.http.xff_header_processing.mode and
routing.http.xff_client_port.enabled on HTTP, WebSocket and Lambda targets,
and set X-Forwarded-Proto and X-Forwarded-Port from the listener connection.
ModifyLoadBalancerAttributes now rejects invalid values for both attributes.

Keep every line of a repeated request header when proxying, and use the last
value in a Lambda event's headers map, as the ALB guide describes.

Take the HTTP API $context.identity.sourceIp from the TCP connection instead
of the caller's X-Forwarded-For, which let a caller spoof it.

* docs(apigatewayv2): limit the X-Forwarded-For hop note to ALB listeners
This commit is contained in:
Abhigya authored and GitHub committed 2026-11-02 07:32:52 -04:00
1 parent 72321539dd
commit 5d8546a1ff
10 files changed
+617 -25

No files matched your search

+6
View File
@@ -857,6 +857,12 @@ The `integrationUri` names the backend:
The request path is forwarded as received. The stage name is not added to it, and `tlsConfig` is not
applied: the call to a Cloud Map instance uses plain HTTP.
`$context.identity.sourceIp` is the address of the TCP connection to Floci, whatever `X-Forwarded-For`
the client sent. Floci forwards a client's `X-Forwarded-For` to the backend unchanged and does not add
the client address to it, so map `$context.identity.sourceIp` to a header of your own to pass the
address on. An ALB HTTP or HTTPS listener integration goes through the listener, which adds its own hop.
An NLB TCP listener relays the request unchanged and does not add a hop.
### Supported Operations
| Category | Operations |
+2
View File
@@ -130,6 +130,8 @@ Gateway Load Balancer listeners require omitted `Port` and `Protocol` fields on
weighted target-group affinity, and NLB stickiness are not implemented. Cookie
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`.
- `routing.http.xff_header_processing.mode` (default `append`) controls `X-Forwarded-For` for HTTP, WebSocket and Lambda targets. `append` adds the client address to any value the client sent, `preserve` forwards the client's header unchanged, and `remove` drops it. `routing.http.xff_client_port.enabled` (default `false`) adds the client port as `ip:port` or `[ipv6]:port`, in `append` mode only. `ModifyLoadBalancerAttributes` answers `InvalidConfigurationRequest` for any other value of either attribute.
- `X-Forwarded-Proto` and `X-Forwarded-Port` are always set from the client's connection to the listener, replacing any value the client sent.
- `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.
@@ -3000,7 +3000,7 @@ public class ApiGatewayExecuteController {
Map<String, Object> authorizerContext = lambdaAuthorizerContext == null
? Map.of() : objectMapper.convertValue(lambdaAuthorizerContext, MAP_TYPE);
String sourceIp = requestHeaders.getOrDefault("X-Forwarded-For", "127.0.0.1");
String sourceIp = routeContext.sourceIp();
io.github.hectorvent.floci.services.apigatewayv2.proxy.RequestContext ctx =
new io.github.hectorvent.floci.services.apigatewayv2.proxy.RequestContext(
apiId, stageName, httpMethod, path,
@@ -1057,6 +1057,11 @@ public class ElbV2DataPlane {
return;
}
ElbV2ForwardedHeaders forwarded = ElbV2ForwardedHeaders.of(req,
loadBalancerAttribute(listenerArn, region, ElbV2ForwardedHeaders.XFF_MODE_ATTRIBUTE),
Boolean.parseBoolean(
loadBalancerAttribute(listenerArn, region, ElbV2ForwardedHeaders.XFF_CLIENT_PORT_ATTRIBUTE)));
if ("lambda".equals(tg.getTargetType())) {
if (isWebSocketUpgrade(req)) {
req.response().setStatusCode(400).end("WebSockets are not supported for Lambda targets");
@@ -1068,7 +1073,7 @@ public class ElbV2DataPlane {
return;
}
String functionArn = targets.get(0).getId();
invokeLambdaTarget(req, functionArn, region);
invokeLambdaTarget(req, functionArn, region, forwarded);
return;
}
@@ -1090,10 +1095,11 @@ public class ElbV2DataPlane {
boolean preserveHostHeader = Boolean.parseBoolean(
loadBalancerAttribute(listenerArn, region, PRESERVE_HOST_HEADER_ATTRIBUTE));
if (isWebSocketUpgrade(req)) {
proxyUpgrade(req, host, targetPort, preserveHostHeader, idleTimeoutMillis(listenerArn, region), cookies);
proxyUpgrade(req, host, targetPort, preserveHostHeader, forwarded,
idleTimeoutMillis(listenerArn, region), cookies);
return;
}
proxyRequest(req, host, targetPort, preserveHostHeader, cookies);
proxyRequest(req, host, targetPort, preserveHostHeader, forwarded, cookies);
}
private String loadBalancerAttribute(String listenerArn, String region, String key) {
@@ -1155,9 +1161,10 @@ public class ElbV2DataPlane {
return candidates.get(index);
}
private void invokeLambdaTarget(HttpServerRequest req, String functionArn, String region) {
private void invokeLambdaTarget(HttpServerRequest req, String functionArn, String region,
ElbV2ForwardedHeaders forwarded) {
if (req.isEnded()) {
invokeLambdaWithBody(req, functionArn, region, Buffer.buffer());
invokeLambdaWithBody(req, functionArn, region, forwarded, Buffer.buffer());
return;
}
ByteArrayOutputStream body = new ByteArrayOutputStream();
@@ -1182,13 +1189,13 @@ public class ElbV2DataPlane {
if (rejected.get()) {
return;
}
invokeLambdaWithBody(req, functionArn, region, Buffer.buffer(body.toByteArray()));
invokeLambdaWithBody(req, functionArn, region, forwarded, Buffer.buffer(body.toByteArray()));
});
}
private void invokeLambdaWithBody(HttpServerRequest req, String functionArn,
String region, Buffer body) {
Map<String, Object> event = buildAlbEvent(req, body);
private void invokeLambdaWithBody(HttpServerRequest req, String functionArn, String region,
ElbV2ForwardedHeaders forwarded, Buffer body) {
Map<String, Object> event = buildAlbEvent(req, forwarded, body);
// Lambda invocation is synchronous and may take seconds while a cold container
// boots and polls the Runtime API. The Runtime API itself runs on Vert.x event
// loops, so blocking the listener's event loop here would deadlock the runtime
@@ -1277,7 +1284,7 @@ public class ElbV2DataPlane {
}
}
private Map<String, Object> buildAlbEvent(HttpServerRequest req, Buffer body) {
Map<String, Object> buildAlbEvent(HttpServerRequest req, ElbV2ForwardedHeaders forwarded, Buffer body) {
Map<String, Object> event = new HashMap<>();
event.put("requestContext", Map.of("elb", Map.of("targetGroupArn", "")));
event.put("httpMethod", req.method().name());
@@ -1300,9 +1307,11 @@ public class ElbV2DataPlane {
Map<String, String> headers = new HashMap<>();
Map<String, List<String>> multiValueHeaders = new HashMap<>();
req.headers().forEach(entry -> {
MultiMap eventHeaders = MultiMap.caseInsensitiveMultiMap().addAll(req.headers());
forwarded.applyTo(req.headers(), eventHeaders);
eventHeaders.forEach(entry -> {
String key = entry.getKey().toLowerCase();
headers.putIfAbsent(key, entry.getValue());
headers.put(key, entry.getValue());
multiValueHeaders.computeIfAbsent(key, k -> new ArrayList<>()).add(entry.getValue());
});
event.put("headers", headers);
@@ -1346,19 +1355,20 @@ public class ElbV2DataPlane {
return tuples.get(tuples.size() - 1).getTargetGroupArn();
}
private void proxyRequest(HttpServerRequest req, String host, int port,
boolean preserveHostHeader, List<String> cookies) {
private void proxyRequest(HttpServerRequest req, String host, int port, boolean preserveHostHeader,
ElbV2ForwardedHeaders forwarded, List<String> cookies) {
req.pause();
if (ElbV2TargetResolver.isIpLiteral(host)) {
try {
proxyRequestTo(req, ElbV2TargetResolver.resolveCheckedAddress(host), host, port, preserveHostHeader, cookies);
proxyRequestTo(req, ElbV2TargetResolver.resolveCheckedAddress(host), host, port,
preserveHostHeader, forwarded, cookies);
} catch (IOException e) {
rejectTarget(req, host, e);
}
return;
}
vertx.<String>executeBlocking(() -> ElbV2TargetResolver.resolveCheckedAddress(host))
.onSuccess(address -> proxyRequestTo(req, address, host, port, preserveHostHeader, cookies))
.onSuccess(address -> proxyRequestTo(req, address, host, port, preserveHostHeader, forwarded, cookies))
.onFailure(err -> rejectTarget(req, host, err));
}
@@ -1369,7 +1379,7 @@ public class ElbV2DataPlane {
}
private void proxyRequestTo(HttpServerRequest req, String address, String host, int port,
boolean preserveHostHeader, List<String> cookies) {
boolean preserveHostHeader, ElbV2ForwardedHeaders forwarded, List<String> cookies) {
RequestOptions opts = new RequestOptions()
.setHost(address)
.setPort(port)
@@ -1379,9 +1389,10 @@ public class ElbV2DataPlane {
.onSuccess(clientReq -> {
req.headers().forEach(entry -> {
if (!HOP_BY_HOP_HEADERS.contains(entry.getKey().toLowerCase())) {
clientReq.putHeader(entry.getKey(), entry.getValue());
clientReq.headers().add(entry.getKey(), entry.getValue());
}
});
forwarded.applyTo(req.headers(), clientReq.headers());
if (!preserveHostHeader) {
clientReq.putHeader("Host", ElbV2TargetResolver.hostHeader(host, port));
}
@@ -1441,12 +1452,12 @@ public class ElbV2DataPlane {
}
private void proxyUpgrade(HttpServerRequest req, String host, int port, boolean preserveHostHeader,
long idleTimeoutMillis, List<String> cookies) {
ElbV2ForwardedHeaders forwarded, long idleTimeoutMillis, List<String> cookies) {
req.pause();
if (ElbV2TargetResolver.isIpLiteral(host)) {
try {
proxyUpgradeTo(req, ElbV2TargetResolver.resolveCheckedAddress(host), host, port,
preserveHostHeader, idleTimeoutMillis, cookies);
preserveHostHeader, forwarded, idleTimeoutMillis, cookies);
} catch (IOException e) {
rejectTarget(req, host, e);
}
@@ -1454,7 +1465,7 @@ public class ElbV2DataPlane {
}
vertx.<String>executeBlocking(() -> ElbV2TargetResolver.resolveCheckedAddress(host))
.onSuccess(address -> proxyUpgradeTo(req, address, host, port, preserveHostHeader,
idleTimeoutMillis, cookies))
forwarded, idleTimeoutMillis, cookies))
.onFailure(err -> rejectTarget(req, host, err));
}
@@ -1464,7 +1475,8 @@ public class ElbV2DataPlane {
* the target refused the upgrade and is relayed as an ordinary response.
*/
private void proxyUpgradeTo(HttpServerRequest req, String address, String host, int port,
boolean preserveHostHeader, long idleTimeoutMillis, List<String> cookies) {
boolean preserveHostHeader, ElbV2ForwardedHeaders forwarded,
long idleTimeoutMillis, List<String> cookies) {
RequestOptions opts = new RequestOptions()
.setHost(address)
.setPort(port)
@@ -1474,9 +1486,10 @@ public class ElbV2DataPlane {
.onSuccess(clientReq -> {
req.headers().forEach(entry -> {
if (!HOP_BY_HOP_HEADERS.contains(entry.getKey().toLowerCase())) {
clientReq.putHeader(entry.getKey(), entry.getValue());
clientReq.headers().add(entry.getKey(), entry.getValue());
}
});
forwarded.applyTo(req.headers(), clientReq.headers());
clientReq.putHeader("Connection", "Upgrade");
clientReq.putHeader("Upgrade", req.getHeader("Upgrade"));
if (!preserveHostHeader) {
@@ -0,0 +1,74 @@
package io.github.hectorvent.floci.services.elbv2;
import io.vertx.core.MultiMap;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* The {@code X-Forwarded-*} headers an Application Load Balancer sends a target, taken from the client's
* connection to the listener rather than from anything the client sent.
*
* <p>{@code routing.http.xff_header_processing.mode} decides {@code X-Forwarded-For}: {@code append} (the
* default) adds the client address to whatever the client sent, {@code preserve} leaves the header untouched
* and {@code remove} drops it. {@code routing.http.xff_client_port.enabled} only affects {@code append}.
*/
record ElbV2ForwardedHeaders(SocketAddress client, boolean secure, int listenerPort,
String xffMode, boolean xffClientPort) {
static final String XFF_MODE_ATTRIBUTE = "routing.http.xff_header_processing.mode";
static final String XFF_CLIENT_PORT_ATTRIBUTE = "routing.http.xff_client_port.enabled";
static final Set<String> XFF_MODES = Set.of("append", "preserve", "remove");
private static final String FORWARDED_FOR = "X-Forwarded-For";
private static final String FORWARDED_PROTO = "X-Forwarded-Proto";
private static final String FORWARDED_PORT = "X-Forwarded-Port";
static ElbV2ForwardedHeaders of(HttpServerRequest req, String xffMode, boolean xffClientPort) {
return new ElbV2ForwardedHeaders(req.remoteAddress(), req.isSSL(), req.localAddress().port(),
xffMode, xffClientPort);
}
/** Sets the headers on {@code outbound}, which may already hold a copy of {@code inbound}. */
void applyTo(MultiMap inbound, MultiMap outbound) {
List<String> received = inbound.getAll(FORWARDED_FOR);
outbound.remove(FORWARDED_FOR);
switch (xffMode != null ? xffMode : "append") {
case "preserve" -> outbound.set(FORWARDED_FOR, received);
case "remove" -> { }
default -> {
String appended = appended(received);
if (!appended.isEmpty()) {
outbound.set(FORWARDED_FOR, appended);
}
}
}
outbound.set(FORWARDED_PROTO, secure ? "https" : "http");
outbound.set(FORWARDED_PORT, String.valueOf(listenerPort));
}
private String appended(List<String> received) {
List<String> entries = new ArrayList<>();
for (String value : received) {
if (!value.isBlank()) {
entries.add(value);
}
}
if (client != null) {
entries.add(clientEntry());
}
return String.join(", ", entries);
}
private String clientEntry() {
String address = client.host();
if (!xffClientPort) {
return address;
}
String host = address.contains(":") ? "[" + address + "]" : address;
return host + ":" + client.port();
}
}
@@ -397,10 +397,20 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
public void modifyLoadBalancerAttributes(String region, String arn, Map<String, String> newAttrs) {
LoadBalancer lb = requireLoadBalancer(region, arn);
requireValidAttributeValue(newAttrs, ElbV2ForwardedHeaders.XFF_MODE_ATTRIBUTE, ElbV2ForwardedHeaders.XFF_MODES);
requireValidAttributeValue(newAttrs, ElbV2ForwardedHeaders.XFF_CLIENT_PORT_ATTRIBUTE, Set.of("true", "false"));
lb.getAttributes().putAll(newAttrs);
persistRegion(loadBalancers, region);
}
private static void requireValidAttributeValue(Map<String, String> attributes, String key, Set<String> allowed) {
String value = attributes.get(key);
if (value != null && !allowed.contains(value)) {
throw new AwsException("InvalidConfigurationRequest",
"Load balancer attribute '" + key + "' cannot have the value '" + value + "'", 400);
}
}
LoadBalancer getLoadBalancer(String region, String arn) {
return loadBalancers.getOrDefault(region, Map.of()).get(arn);
}
@@ -20,6 +20,7 @@ import java.util.concurrent.CopyOnWriteArrayList;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
@@ -119,6 +120,21 @@ class ApiGatewayV2CloudMapIntegrationTest {
new Received("POST", "/orders", "tag=a&tag=b", "hello", "probe-value")));
}
@Test
void contextSourceIpIsTheConnectionAddressAndNotTheCallersForwardedFor() throws IOException {
Stub stub = startStub("only");
String serviceId = createService(null);
register(serviceId, "i-1", stub, "");
String apiId = createApi(serviceArn(serviceId), "VPC_LINK", createVpcLink(),
",\"requestParameters\":{\"overwrite:header.X-Probe\":\"$context.identity.sourceIp\"}");
given().header("X-Forwarded-For", "198.51.100.7")
.when().get("/execute-api/" + apiId + "/$default/orders")
.then().statusCode(200);
assertThat(stub.received.get(0).header(), anyOf(equalTo("127.0.0.1"), equalTo("0:0:0:0:0:0:0:1")));
}
@Test
void encodedPathAndTrailingSlashReachTheInstanceAsTheCallerSentThem() throws IOException {
Stub stub = startStub("raw");
@@ -356,6 +372,11 @@ class ApiGatewayV2CloudMapIntegrationTest {
}
private String createApi(String integrationUri, String connectionType, String connectionId) {
return createApi(integrationUri, connectionType, connectionId, "");
}
private String createApi(String integrationUri, String connectionType, String connectionId,
String extraIntegrationFields) {
String apiId = given().contentType(ContentType.JSON)
.body("{\"name\":\"cm-api\",\"protocolType\":\"HTTP\"}")
.when().post("/v2/apis").then().statusCode(201).extract().path("apiId");
@@ -365,7 +386,8 @@ class ApiGatewayV2CloudMapIntegrationTest {
+ (connectionId == null ? "" : ",\"connectionId\":\"" + connectionId + "\"");
String integrationId = given().contentType(ContentType.JSON)
.body("{\"integrationType\":\"HTTP_PROXY\",\"integrationUri\":\"" + integrationUri
+ "\",\"payloadFormatVersion\":\"1.0\",\"integrationMethod\":\"ANY\"" + connection + "}")
+ "\",\"payloadFormatVersion\":\"1.0\",\"integrationMethod\":\"ANY\"" + connection
+ extraIntegrationFields + "}")
.when().post("/v2/apis/" + apiId + "/integrations")
.then().statusCode(201).extract().path("integrationId");
@@ -0,0 +1,301 @@
package io.github.hectorvent.floci.services.elbv2;
import io.github.hectorvent.floci.services.acm.AcmService;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.Certificate;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
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.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.RequestOptions;
import io.vertx.core.http.WebSocket;
import io.vertx.core.http.WebSocketConnectOptions;
import io.vertx.core.net.SocketAddress;
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.List;
import java.util.Map;
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.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** What a target receives through a real listener socket, against the header tables in the ALB guide. */
@QuarkusTest
@TestProfile(RealElbV2DataPlaneProfile.class)
class ElbV2ForwardedHeadersIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261102/us-east-1/elasticloadbalancing/aws4_request";
private static final String REGION = "us-east-1";
private static final String CLIENT = "127.0.0.1";
private static final String SPOOFED = "198.51.100.7";
@Inject
Vertx vertx;
@Inject
AcmService acmService;
private final CompletableFuture<MultiMap> 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 -> {
if ("websocket".equalsIgnoreCase(request.getHeader("Upgrade"))) {
handshake.complete(MultiMap.caseInsensitiveMultiMap().addAll(request.headers()));
request.toWebSocket();
return;
}
request.response()
.putHeader("X-Seen-For", String.join("|", request.headers().getAll("X-Forwarded-For")))
.putHeader("X-Seen-Multi", String.join("|", request.headers().getAll("X-Multi")))
.putHeader("X-Seen-Proto", String.valueOf(request.getHeader("X-Forwarded-Proto")))
.putHeader("X-Seen-Port", String.valueOf(request.getHeader("X-Forwarded-Port")))
.end("ok");
})
.listen(0, "127.0.0.1")
.toCompletionStage()
.toCompletableFuture()
.get(2, TimeUnit.SECONDS);
listenerPort = FreePorts.anyInterfacePort();
loadBalancerArn = createLoadBalancer("forwarded-headers-lb");
targetGroupArn = createTargetGroup("forwarded-headers-tg", "ip", backend.actualPort());
registerTarget(targetGroupArn, "127.0.0.1", backend.actualPort());
}
@AfterEach
void stopBackend() throws Exception {
deleteListener(listenerArn);
deleteTargetGroup(targetGroupArn);
deleteLoadBalancer(loadBalancerArn);
backend.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
private void startHttpListener() {
listenerArn = createListener(loadBalancerArn, targetGroupArn, listenerPort);
await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> assertEquals(200, send().statusCode()));
}
private Response send(String... forwardedFor) {
RequestSpecification request = given()
.baseUri("http://127.0.0.1")
.port(listenerPort);
for (String value : forwardedFor) {
request.header("X-Forwarded-For", value);
}
return request.get("/headers");
}
private void setAttribute(String key, String value) {
given()
.formParam("Action", "ModifyLoadBalancerAttributes")
.formParam("LoadBalancerArn", loadBalancerArn)
.formParam("Attributes.member.1.Key", key)
.formParam("Attributes.member.1.Value", value)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
void appendIsTheDefaultAndAddsTheClientAddress() {
startHttpListener();
assertEquals(CLIENT, send().getHeader("X-Seen-For"));
assertEquals(SPOOFED + ", " + CLIENT, send(SPOOFED).getHeader("X-Seen-For"));
}
@Test
void appendAddsTheClientPortWhenTheAttributeIsEnabled() {
startHttpListener();
setAttribute("routing.http.xff_client_port.enabled", "true");
String seen = send().getHeader("X-Seen-For");
assertTrue(seen.matches("127\\.0\\.0\\.1:\\d+"), seen);
}
@Test
void preserveForwardsTheClientHeaderUnchanged() {
startHttpListener();
setAttribute("routing.http.xff_header_processing.mode", "preserve");
assertEquals("", send().getHeader("X-Seen-For"));
assertEquals(SPOOFED, send(SPOOFED).getHeader("X-Seen-For"));
}
@Test
void removeDropsTheClientHeader() {
startHttpListener();
setAttribute("routing.http.xff_header_processing.mode", "remove");
assertEquals("", send(SPOOFED).getHeader("X-Seen-For"));
}
@Test
void repeatedHeaderLinesAreJoinedInAppendAndKeptInPreserve() {
startHttpListener();
assertEquals("10.0.0.1, 10.0.0.2, " + CLIENT, send("10.0.0.1", "10.0.0.2").getHeader("X-Seen-For"));
setAttribute("routing.http.xff_header_processing.mode", "preserve");
assertEquals("10.0.0.1|10.0.0.2", send("10.0.0.1", "10.0.0.2").getHeader("X-Seen-For"));
}
@Test
void otherRepeatedRequestHeadersAllReachTheTarget() {
startHttpListener();
Response response = given()
.baseUri("http://127.0.0.1")
.port(listenerPort)
.header("X-Multi", "one")
.header("X-Multi", "two")
.get("/headers");
assertEquals("one|two", response.getHeader("X-Seen-Multi"));
}
@Test
void invalidAttributeValuesAreRejected() {
for (String key : List.of("routing.http.xff_header_processing.mode", "routing.http.xff_client_port.enabled")) {
given()
.formParam("Action", "ModifyLoadBalancerAttributes")
.formParam("LoadBalancerArn", loadBalancerArn)
.formParam("Attributes.member.1.Key", key)
.formParam("Attributes.member.1.Value", "bogus")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("InvalidConfigurationRequest"));
}
}
@Test
void protoAndPortReplaceWhatTheClientSent() {
startHttpListener();
Response response = given()
.baseUri("http://127.0.0.1")
.port(listenerPort)
.header("X-Forwarded-Proto", "https")
.header("X-Forwarded-Port", "1")
.get("/headers");
assertEquals("http", response.getHeader("X-Seen-Proto"));
assertEquals(String.valueOf(listenerPort), response.getHeader("X-Seen-Port"));
}
@Test
void webSocketHandshakeCarriesTheForwardedHeaders() throws Exception {
startHttpListener();
HttpClient client = vertx.createHttpClient();
try {
WebSocket socket = client.webSocket(new WebSocketConnectOptions()
.setHost("127.0.0.1")
.setPort(listenerPort)
.setURI("/socket")
.addHeader("X-Forwarded-For", SPOOFED))
.toCompletionStage()
.toCompletableFuture()
.get(5, TimeUnit.SECONDS);
MultiMap headers = handshake.get(5, TimeUnit.SECONDS);
socket.close();
assertEquals(List.of(SPOOFED + ", " + CLIENT), headers.getAll("X-Forwarded-For"));
assertEquals("http", headers.get("X-Forwarded-Proto"));
assertEquals(String.valueOf(listenerPort), headers.get("X-Forwarded-Port"));
} finally {
client.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
}
@Test
void httpsListenerReportsHttpsToAPlainHttpTarget() throws Exception {
CertificateGenerator.GeneratedCertificate pair = new CertificateGenerator().generateSelfSignedCertificate(
"forwarded.elb.invalid", List.of(), KeyAlgorithm.RSA_2048);
Certificate certificate = acmService.importCertificate(pair.certificatePem(), pair.privateKeyPem(),
null, null, Map.of(), REGION);
HttpClient client = vertx.createHttpClient(new HttpClientOptions().setSsl(true).setTrustAll(true)
.setVerifyHost(false).setForceSni(true));
try {
listenerArn = given()
.formParam("Action", "CreateListener")
.formParam("LoadBalancerArn", loadBalancerArn)
.formParam("Protocol", "HTTPS")
.formParam("Port", String.valueOf(listenerPort))
.formParam("SslPolicy", "ELBSecurityPolicy-TLS13-1-2-2021-06")
.formParam("Certificates.member.1.CertificateArn", certificate.getArn())
.formParam("DefaultActions.member.1.Type", "forward")
.formParam("DefaultActions.member.1.TargetGroupArn", targetGroupArn)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.extract()
.path("CreateListenerResponse.CreateListenerResult.Listeners.member.ListenerArn");
ElbV2TlsReadiness.await(Duration.ofSeconds(10), () -> {
HttpClientResponse response = client.request(new RequestOptions()
.setMethod(HttpMethod.GET)
.setServer(SocketAddress.inetSocketAddress(listenerPort, "127.0.0.1"))
.setHost("forwarded.elb.invalid")
.setPort(listenerPort)
.setURI("/headers"))
.compose(HttpClientRequest::send)
.toCompletionStage()
.toCompletableFuture()
.get(2, TimeUnit.SECONDS);
assertEquals("https", response.getHeader("X-Seen-Proto"));
assertEquals(String.valueOf(listenerPort), response.getHeader("X-Seen-Port"));
assertEquals(CLIENT, response.getHeader("X-Seen-For"));
});
} finally {
deleteListener(listenerArn);
listenerArn = null;
client.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
await().atMost(Duration.ofSeconds(5)).untilAsserted(
() -> acmService.deleteCertificate(certificate.getArn(), REGION));
}
}
}
@@ -0,0 +1,149 @@
package io.github.hectorvent.floci.services.elbv2;
import io.vertx.core.MultiMap;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ElbV2ForwardedHeadersTest {
private static final SocketAddress CLIENT_V4 = SocketAddress.inetSocketAddress(8080, "12.34.56.78");
private static final SocketAddress CLIENT_V6 =
SocketAddress.inetSocketAddress(8080, "2001:db8:85a3:8d3:1319:8a2e:370:7348");
private static List<String> xff(ElbV2ForwardedHeaders headers, String... received) {
MultiMap inbound = MultiMap.caseInsensitiveMultiMap();
for (String value : received) {
inbound.add("x-forwarded-for", value);
}
MultiMap outbound = MultiMap.caseInsensitiveMultiMap().addAll(inbound);
headers.applyTo(inbound, outbound);
return outbound.getAll("X-Forwarded-For");
}
private static ElbV2ForwardedHeaders mode(String mode) {
return new ElbV2ForwardedHeaders(CLIENT_V4, false, 80, mode, false);
}
@Test
void appendCreatesTheHeaderWhenTheClientSentNone() {
assertEquals(List.of("12.34.56.78"), xff(mode("append")));
}
@Test
void appendAddsTheClientAfterExistingAddresses() {
assertEquals(List.of("127.0.0.4, 127.0.0.8, 12.34.56.78"), xff(mode("append"), "127.0.0.4, 127.0.0.8"));
}
@Test
void appendJoinsRepeatedHeaderLinesInOrder() {
assertEquals(List.of("127.0.0.4, 127.0.0.8, 12.34.56.78"), xff(mode("append"), "127.0.0.4", "127.0.0.8"));
}
@Test
void appendIgnoresABlankClientValue() {
assertEquals(List.of("12.34.56.78"), xff(mode("append"), " "));
}
@Test
void appendIsTheModeWhenTheAttributeIsMissingOrUnknown() {
assertEquals(List.of("12.34.56.78"), xff(mode(null)));
assertEquals(List.of("12.34.56.78"), xff(mode("bogus")));
}
@Test
void preserveLeavesTheHeaderUnchanged() {
assertEquals(List.of(), xff(mode("preserve")));
assertEquals(List.of("127.0.0.4, 127.0.0.8"), xff(mode("preserve"), "127.0.0.4, 127.0.0.8"));
assertEquals(List.of("127.0.0.4", "127.0.0.8"), xff(mode("preserve"), "127.0.0.4", "127.0.0.8"));
}
@Test
void removeDropsTheHeader() {
assertEquals(List.of(), xff(mode("remove")));
assertEquals(List.of(), xff(mode("remove"), "127.0.0.4"));
}
@Test
void clientPortIsAddedToAnIpv4Address() {
assertEquals(List.of("12.34.56.78:8080"), xff(new ElbV2ForwardedHeaders(CLIENT_V4, false, 80, "append", true)));
}
@Test
void ipv6AddressIsBracketedOnlyWithAClientPort() {
assertEquals(List.of("2001:db8:85a3:8d3:1319:8a2e:370:7348"),
xff(new ElbV2ForwardedHeaders(CLIENT_V6, false, 80, "append", false)));
assertEquals(List.of("[2001:db8:85a3:8d3:1319:8a2e:370:7348]:8080"),
xff(new ElbV2ForwardedHeaders(CLIENT_V6, false, 80, "append", true)));
}
@Test
void clientPortIsIgnoredOutsideAppendMode() {
assertEquals(List.of("127.0.0.4"),
xff(new ElbV2ForwardedHeaders(CLIENT_V4, false, 80, "preserve", true), "127.0.0.4"));
assertEquals(List.of(), xff(new ElbV2ForwardedHeaders(CLIENT_V4, false, 80, "remove", true), "127.0.0.4"));
}
@Test
void protoAndPortComeFromTheListenerConnectionInEveryMode() {
for (String mode : List.of("append", "preserve", "remove")) {
MultiMap inbound = MultiMap.caseInsensitiveMultiMap()
.add("X-Forwarded-Proto", "gopher")
.add("X-Forwarded-Port", "1");
MultiMap outbound = MultiMap.caseInsensitiveMultiMap().addAll(inbound);
new ElbV2ForwardedHeaders(CLIENT_V4, true, 443, mode, false).applyTo(inbound, outbound);
assertEquals(List.of("https"), outbound.getAll("X-Forwarded-Proto"));
assertEquals(List.of("443"), outbound.getAll("X-Forwarded-Port"));
}
}
@Test
@SuppressWarnings("unchecked")
void lambdaEventCarriesTheForwardedHeadersInBothHeaderMaps() {
HttpServerRequest request = mock(HttpServerRequest.class);
when(request.method()).thenReturn(HttpMethod.GET);
when(request.path()).thenReturn("/");
when(request.headers()).thenReturn(MultiMap.caseInsensitiveMultiMap()
.add("X-Forwarded-For", "127.0.0.4")
.add("X-Forwarded-Proto", "gopher"));
ElbV2ForwardedHeaders forwarded = new ElbV2ForwardedHeaders(CLIENT_V4, true, 443, "append", false);
Map<String, Object> event = new ElbV2DataPlane(new ConcurrentHashMap<>())
.buildAlbEvent(request, forwarded, Buffer.buffer());
Map<String, String> headers = (Map<String, String>) event.get("headers");
assertEquals("127.0.0.4, 12.34.56.78", headers.get("x-forwarded-for"));
assertEquals("https", headers.get("x-forwarded-proto"));
assertEquals("443", headers.get("x-forwarded-port"));
Map<String, List<String>> multiValueHeaders = (Map<String, List<String>>) event.get("multiValueHeaders");
assertEquals(List.of("127.0.0.4, 12.34.56.78"), multiValueHeaders.get("x-forwarded-for"));
}
@Test
@SuppressWarnings("unchecked")
void lambdaEventHeadersMapKeepsTheLastOfARepeatedHeader() {
HttpServerRequest request = mock(HttpServerRequest.class);
when(request.method()).thenReturn(HttpMethod.GET);
when(request.path()).thenReturn("/");
when(request.headers()).thenReturn(MultiMap.caseInsensitiveMultiMap()
.add("Cookie", "name1=value1")
.add("Cookie", "name2=value2"));
Map<String, Object> event = new ElbV2DataPlane(new ConcurrentHashMap<>())
.buildAlbEvent(request, mode("append"), Buffer.buffer());
assertEquals("name2=value2", ((Map<String, String>) event.get("headers")).get("cookie"));
}
}
@@ -74,6 +74,9 @@ class ElbV2LambdaTargetDataPlaneIntegrationTest {
" return {\"statusCode\": 200, \"body\": \"x\" * (1024 * 1024)}\n" +
" if event.get(\"path\") == \"/response-oversized\":\n" +
" return {\"statusCode\": 200, \"headers\": {\"Content-Length\": \"1048577\"}, \"body\": \"x\" * (1024 * 1024 + 1)}\n" +
" if event.get(\"path\") == \"/forwarded-headers\":\n" +
" names = [\"x-forwarded-for\", \"x-forwarded-proto\", \"x-forwarded-port\"]\n" +
" return {\"statusCode\": 200, \"body\": \"|\".join(event[\"headers\"].get(n, \"\") for n in names)}\n" +
" return {\"statusCode\": 200, \"body\": \"ok\"}\n"
).getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
@@ -287,6 +290,18 @@ class ElbV2LambdaTargetDataPlaneIntegrationTest {
.body(equalTo("unexpected host"));
}
@Test
@Order(11)
void eventCarriesTheForwardedHeaders() {
listenerRequest(lbDnsName)
.header("X-Forwarded-For", "198.51.100.7")
.when()
.get("/forwarded-headers")
.then()
.statusCode(200)
.body(equalTo("198.51.100.7, 127.0.0.1|http|" + LISTENER_PORT));
}
/**
* Cleanup. Lives as the highest-ordered @Test rather than {@code @AfterAll} because
* Quarkus tears the test endpoint down before JUnit's @AfterAll runs, so HTTP-based