mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
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:
1 parent
72321539dd
commit
5d8546a1ff
10 files changed
+617
-25
No files matched your search
+1
-1
@@ -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);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user