diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index ff69d1fe7e..2176d56a1a 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -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 diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java index 907a7b7792..aec3745065 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java @@ -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> 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()); diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java index a10fe38847..777fed939e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java @@ -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; diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpApiForwardedHeaders.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpApiForwardedHeaders.java new file mode 100644 index 0000000000..71fbdaf972 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpApiForwardedHeaders.java @@ -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. + * + *

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> apply(Map> headers, String clientIp, + String gatewayIp, String host, String proto) { + Map> result = new LinkedHashMap<>(); + List chain = new ArrayList<>(); + for (Map.Entry> 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 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("\"", "\\\"") + "\""; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2CloudMapIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2CloudMapIntegrationTest.java index b67110b9a4..c9dc691109 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2CloudMapIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2CloudMapIntegrationTest.java @@ -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 = new CopyOnWriteArrayList<>(); final List rawRequestTargets = new CopyOnWriteArrayList<>(); + final List 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); diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpApiForwardedHeadersTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpApiForwardedHeadersTest.java new file mode 100644 index 0000000000..37828ba518 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpApiForwardedHeadersTest.java @@ -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> apply(Map> headers) { + return HttpApiForwardedHeaders.apply(headers, "192.0.2.43", "10.0.0.1", "api.example.test", "https"); + } + + @Test + void callerWithoutAChainIsTheOnlyForElement() { + Map> 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> 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> 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> 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> 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")); + } +}