fix(apigatewayv2): send HTTP_PROXY backends the client address in Forwarded (#7281)

This commit is contained in:
Abhigya authored and GitHub committed 2026-11-02 10:46:57 -04:00
1 parent 33052fa101
commit ebd2b70b32
6 files changed
+176 -5

No files matched your search

+12 -4
View File
@@ -858,10 +858,18 @@ The request path is forwarded as received. The stage name is not added to it, an
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.
the client sent. An HTTP API `HTTP_PROXY` backend receives a `Forwarded` header holding the client's
`X-Forwarded-For` entries and the client address, for example
`Forwarded: for=198.51.100.7,for=192.0.2.43;by=10.0.0.1;host=api.example.test;proto=https`, and an
`X-Forwarded-For` naming only the address Floci accepted the request on. A client's own `Forwarded`
header is replaced. `$request.header.X-Forwarded-For` mappings still see the client's value. The
[API Gateway important notes](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-known-issues.html)
say HTTP APIs translate `X-Forwarded-*` into `Forwarded` and append the egress IP, Host and protocol.
They do not give the syntax or the `X-Forwarded-For` value, which follow third-party descriptions of
observed behavior. Floci translates only `X-Forwarded-For`: `X-Forwarded-Host`, `X-Forwarded-Proto` and
`X-Forwarded-Port` reach the backend as the client sent them.
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
@@ -44,6 +44,7 @@ import io.github.hectorvent.floci.services.apigatewayv2.model.Api;
import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
import io.github.hectorvent.floci.services.apigatewayv2.proxy.CloudMapInstanceResolver;
import io.github.hectorvent.floci.services.apigatewayv2.proxy.HttpApiForwardedHeaders;
import io.github.hectorvent.floci.services.apigatewayv2.websocket.ConnectionInfo;
import io.github.hectorvent.floci.services.apigatewayv2.websocket.WebSocketConnectionManager;
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
@@ -3001,13 +3002,16 @@ public class ApiGatewayExecuteController {
? Map.of() : objectMapper.convertValue(lambdaAuthorizerContext, MAP_TYPE);
String sourceIp = routeContext.sourceIp();
// $request.header.* mappings keep the caller's values; only what reaches the backend changes.
Map<String, List<String>> backendHeaders = HttpApiForwardedHeaders.apply(multiValueHeaders, sourceIp,
routeContext.localIp(), headers.getHeaderString("Host"), isSecureTransport(uriInfo) ? "https" : "http");
io.github.hectorvent.floci.services.apigatewayv2.proxy.RequestContext ctx =
new io.github.hectorvent.floci.services.apigatewayv2.proxy.RequestContext(
apiId, stageName, httpMethod, path,
pathParams.getOrDefault("proxy", ""), route.getRouteKey(),
UUID.randomUUID().toString(), sourceIp,
requestHeaders, queryParams, pathParams, body,
claims, authorizerContext, multiValueHeaders, multiValueQueryParams);
claims, authorizerContext, backendHeaders, multiValueQueryParams);
LOG.debugv("execute-api v2: {0} {1}/{2}{3} → HTTP_PROXY {4}",
httpMethod, apiId, stageName, path, effective.getIntegrationUri());
@@ -33,6 +33,11 @@ public class ApiGatewayExecuteRouteContext {
return context != null ? context.request().connection().remoteAddress().hostAddress() : "127.0.0.1";
}
String localIp() {
RoutingContext context = currentVertxRequest != null ? currentVertxRequest.getCurrent() : null;
return context != null ? context.request().connection().localAddress().hostAddress() : "127.0.0.1";
}
private final Instant requestTime = Instant.now();
private final String extendedRequestId = UUID.randomUUID().toString();
private String requestId;
@@ -0,0 +1,75 @@
package io.github.hectorvent.floci.services.apigatewayv2.proxy;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* The forwarding headers an HTTP API sends an {@code HTTP_PROXY} backend: the caller's chain moves to an
* RFC 7239 {@code Forwarded} header and {@code X-Forwarded-For} names the gateway itself.
*
* <p>The API Gateway important notes say HTTP APIs translate {@code X-Forwarded-*} into {@code Forwarded}
* and append the egress IP, Host and protocol. They do not give the syntax or the {@code X-Forwarded-For}
* value, which follow third-party descriptions of observed behavior. Only {@code X-Forwarded-For} is
* translated here.
*/
public final class HttpApiForwardedHeaders {
private static final String FORWARDED = "Forwarded";
private static final String FORWARDED_FOR = "X-Forwarded-For";
private static final Pattern TOKEN = Pattern.compile("[A-Za-z0-9._-]+");
private HttpApiForwardedHeaders() {
}
/** Returns a copy of {@code headers} with both headers replaced. */
public static Map<String, List<String>> apply(Map<String, List<String>> headers, String clientIp,
String gatewayIp, String host, String proto) {
Map<String, List<String>> result = new LinkedHashMap<>();
List<String> chain = new ArrayList<>();
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
if (FORWARDED_FOR.equalsIgnoreCase(header.getKey())) {
for (String line : header.getValue()) {
for (String entry : line.split(",")) {
if (!entry.isBlank()) {
chain.add(entry.trim());
}
}
}
} else if (!FORWARDED.equalsIgnoreCase(header.getKey())) {
result.put(header.getKey(), header.getValue());
}
}
chain.add(clientIp);
List<String> forElements = new ArrayList<>();
for (String node : chain) {
forElements.add("for=" + parameter(node(node)));
}
StringBuilder forwarded = new StringBuilder(String.join(",", forElements))
.append(";by=").append(parameter(node(gatewayIp)));
if (host != null && !host.isBlank()) {
forwarded.append(";host=").append(parameter(host));
}
forwarded.append(";proto=").append(proto);
result.put(FORWARDED, List.of(forwarded.toString()));
result.put(FORWARDED_FOR, List.of(gatewayIp));
return result;
}
private static String node(String address) {
boolean ipv6 = address.indexOf(':') != address.lastIndexOf(':') && !address.startsWith("[");
return ipv6 ? "[" + address + "]" : address;
}
/** RFC 7239 parameter values are tokens, so anything else, such as a port or an IPv6 node, is quoted. */
private static String parameter(String value) {
if (TOKEN.matcher(value).matches()) {
return value;
}
return "\"" + value.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
}
}
@@ -25,6 +25,7 @@ import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.startsWith;
@@ -55,6 +56,7 @@ class ApiGatewayV2CloudMapIntegrationTest {
final HttpServer server;
final List<Received> received = new CopyOnWriteArrayList<>();
final List<String> rawRequestTargets = new CopyOnWriteArrayList<>();
final List<String> forwardingHeaders = new CopyOnWriteArrayList<>();
Stub(String name) throws IOException {
this.name = name;
@@ -62,6 +64,8 @@ class ApiGatewayV2CloudMapIntegrationTest {
server.createContext("/", exchange -> {
String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
rawRequestTargets.add(exchange.getRequestURI().getRawPath());
forwardingHeaders.add(exchange.getRequestHeaders().getFirst("Forwarded")
+ "|" + exchange.getRequestHeaders().get("X-Forwarded-For"));
received.add(new Received(exchange.getRequestMethod(), exchange.getRequestURI().getPath(),
exchange.getRequestURI().getRawQuery(), body,
exchange.getRequestHeaders().getFirst("X-Probe")));
@@ -184,6 +188,21 @@ class ApiGatewayV2CloudMapIntegrationTest {
assertThat(stub.rawRequestTargets, contains("/orders"));
}
@Test
void instanceReceivesTheCallersChainInForwarded() throws IOException {
Stub stub = startStub("only");
String serviceId = createService(null);
register(serviceId, "i-1", stub, "");
String apiId = createApi(serviceArn(serviceId), "VPC_LINK", createVpcLink());
given().header("X-Forwarded-For", "198.51.100.7")
.when().get("/execute-api/" + apiId + "/$default/orders")
.then().statusCode(200);
assertThat(stub.forwardingHeaders.get(0), matchesPattern(
"for=198\\.51\\.100\\.7,for=[^;]+;by=[^;]+;host=\"?[^;]+;proto=http\\|\\[(?!198\\.51)[^,]+\\]"));
}
@Test
void serviceWithoutInstancesAnswers503() {
String serviceId = createService(null);
@@ -0,0 +1,60 @@
package io.github.hectorvent.floci.services.apigatewayv2.proxy;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
class HttpApiForwardedHeadersTest {
private static Map<String, List<String>> apply(Map<String, List<String>> headers) {
return HttpApiForwardedHeaders.apply(headers, "192.0.2.43", "10.0.0.1", "api.example.test", "https");
}
@Test
void callerWithoutAChainIsTheOnlyForElement() {
Map<String, List<String>> result = apply(Map.of());
assertEquals(List.of("for=192.0.2.43;by=10.0.0.1;host=api.example.test;proto=https"), result.get("Forwarded"));
assertEquals(List.of("10.0.0.1"), result.get("X-Forwarded-For"));
}
@Test
void callersChainMovesToForwardedAndClientComesLast() {
Map<String, List<String>> result = apply(Map.of("x-forwarded-for", List.of("198.51.100.7, 198.51.100.8", "198.51.100.9")));
assertEquals(List.of("for=198.51.100.7,for=198.51.100.8,for=198.51.100.9,for=192.0.2.43"
+ ";by=10.0.0.1;host=api.example.test;proto=https"), result.get("Forwarded"));
assertEquals(List.of("10.0.0.1"), result.get("X-Forwarded-For"));
assertFalse(result.containsKey("x-forwarded-for"));
}
@Test
void callersForwardedHeaderIsReplacedAndOtherHeadersAreKept() {
Map<String, List<String>> result = apply(Map.of("forwarded", List.of("for=203.0.113.1"), "X-Probe", List.of("kept")));
assertFalse(result.containsKey("forwarded"));
assertEquals(List.of("for=192.0.2.43;by=10.0.0.1;host=api.example.test;proto=https"), result.get("Forwarded"));
assertEquals(List.of("kept"), result.get("X-Probe"));
}
@Test
void ipv6NodesAndHostPortsAreQuoted() {
Map<String, List<String>> result = HttpApiForwardedHeaders.apply(Map.of(), "2001:db8::1", "::1",
"localhost:4566", "http");
assertEquals(List.of("for=\"[2001:db8::1]\";by=\"[::1]\";host=\"localhost:4566\";proto=http"),
result.get("Forwarded"));
}
@Test
void quotesInACallersEntryCannotBreakOutOfTheParameter() {
Map<String, List<String>> result = apply(Map.of("X-Forwarded-For", List.of("a\"b;by=evil")));
assertEquals(List.of("for=\"a\\\"b;by=evil\",for=192.0.2.43;by=10.0.0.1;host=api.example.test;proto=https"),
result.get("Forwarded"));
}
}