fix(elbv2): dispatch same-port listeners by host (#1700)

* fix(elbv2): dispatch same-port listeners by host

* fix(elbv2): fall back to sole port listener

* fix(elbv2): avoid restricted Host header dependency

* fix(elbv2): keep same binding restarts in place

* docs: sync service action tables
This commit is contained in:
Jason van Zyl authored and GitHub committed 2026-07-09 00:15:46 -05:00
1 parent 0e85ac92c7
commit dd566857ef
8 files changed
+622 -57

No files matched your search

@@ -18,6 +18,7 @@ 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;
import io.github.hectorvent.floci.services.elbv2.model.Listener;
import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer;
import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
@@ -1269,18 +1270,15 @@ public class ApiGatewayExecuteController {
Matcher m = ELB_LISTENER_ARN.matcher(integrationUri);
if (m.matches()) {
String albRegion = m.group(1);
Integer listenerPort = resolveAlbListenerPort(albRegion, integrationUri);
if (listenerPort == null) {
AlbListenerEndpoint listenerEndpoint = resolveAlbListenerEndpoint(albRegion, integrationUri);
if (listenerEndpoint == null) {
LOG.warnv("ALB listener ARN unresolvable for v2 integration: {0}", integrationUri);
return Response.status(502)
.entity(jsonMessage("Bad Gateway: cannot resolve ALB listener: " + integrationUri))
.type(MediaType.APPLICATION_JSON).build();
}
// Use 127.0.0.1 explicitly: ElbV2DataPlane binds the listener on 0.0.0.0
// (IPv4-only). "localhost" resolves to ::1 first on IPv6-preferred systems,
// which would fail to connect.
String resolvedUrl = "http://127.0.0.1:" + listenerPort + path;
effective = withResolvedUri(integration, resolvedUrl);
String resolvedUrl = "http://127.0.0.1:" + listenerEndpoint.port() + path;
effective = withResolvedUriAndHost(integration, resolvedUrl, listenerEndpoint.host());
LOG.debugv("ALB integration: listener {0} → {1}", integrationUri, resolvedUrl);
}
}
@@ -1329,18 +1327,24 @@ public class ApiGatewayExecuteController {
return rb.build();
}
/** Returns the listener's bound port, or null if the ARN is unknown or describeListeners throws. */
private Integer resolveAlbListenerPort(String region, String listenerArn) {
/** Returns listener endpoint details, or null if the ARN is unknown or lookups fail. */
private AlbListenerEndpoint resolveAlbListenerEndpoint(String region, String listenerArn) {
try {
List<Listener> matches = elbV2Service.describeListeners(region, null, List.of(listenerArn));
if (matches.isEmpty()) return null;
return matches.get(0).getPort();
Listener listener = matches.get(0);
List<LoadBalancer> loadBalancers = elbV2Service.describeLoadBalancers(
region, List.of(listener.getLoadBalancerArn()), null, null, null);
if (loadBalancers.isEmpty()) return null;
return new AlbListenerEndpoint(listener.getPort(), loadBalancers.get(0).getDnsName());
} catch (Exception e) {
LOG.warnv("describeListeners failed for {0}: {1}", listenerArn, e.getMessage());
return null;
}
}
private record AlbListenerEndpoint(int port, String host) {}
/** Shallow copy with {@code integrationUri} replaced; never mutate the stored Integration. */
private static io.github.hectorvent.floci.services.apigatewayv2.model.Integration withResolvedUri(
io.github.hectorvent.floci.services.apigatewayv2.model.Integration original, String targetUri) {
@@ -1350,6 +1354,18 @@ public class ApiGatewayExecuteController {
return copy;
}
private static io.github.hectorvent.floci.services.apigatewayv2.model.Integration withResolvedUriAndHost(
io.github.hectorvent.floci.services.apigatewayv2.model.Integration original, String targetUri, String host) {
io.github.hectorvent.floci.services.apigatewayv2.model.Integration copy = withResolvedUri(original, targetUri);
Map<String, String> requestParameters = new java.util.LinkedHashMap<>();
if (copy.getRequestParameters() != null) {
requestParameters.putAll(copy.getRequestParameters());
}
requestParameters.put("overwrite:header.Host", host);
copy.setRequestParameters(requestParameters);
return copy;
}
private static String extractBearerToken(HttpHeaders headers) {
String auth = headers.getHeaderString("Authorization");
if (auth == null) return null;
@@ -3,6 +3,12 @@ package io.github.hectorvent.floci.services.apigatewayv2.proxy;
import io.github.hectorvent.floci.services.apigatewayv2.model.Integration;
import org.jboss.logging.Logger;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
@@ -12,6 +18,7 @@ import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
@@ -24,7 +31,7 @@ import java.util.StringJoiner;
*
* <p>Hop-by-hop headers (per RFC 7230 §6.1) are stripped from both the outgoing
* request and the response. Java's HttpClient also restricts certain headers
* (Host, Content-Length, etc.) — those are skipped silently.
* (Content-Length, etc.) — those are skipped silently.
*
* <p>If the backend is unreachable or times out, returns a 502 Bad Gateway
* ProxyResult so the controller can relay a clean error to the original client.
@@ -82,10 +89,20 @@ public class HttpProxyInvoker {
mapper.apply(integration.getRequestParameters(), builder, ctx);
// 5. Build java.net.http.HttpRequest
String finalUrl = buildFinalUrl(builder);
if (hasHeader(builder, "Host") && finalUrl.startsWith("http://")) {
try {
return invokeHttpWithHostOverride(finalUrl, method, builder);
} catch (Exception e) {
LOG.warnv("HTTP_PROXY backend call failed: {0}", e.getMessage());
return errorResult("Bad Gateway: " + e.getMessage());
}
}
HttpRequest.Builder hrb;
try {
hrb = HttpRequest.newBuilder()
.uri(URI.create(buildFinalUrl(builder)))
.uri(URI.create(finalUrl))
.timeout(Duration.ofSeconds(30));
} catch (IllegalArgumentException e) {
LOG.warnv("HTTP_PROXY: invalid target URL: {0}", e.getMessage());
@@ -124,6 +141,167 @@ public class HttpProxyInvoker {
}
}
private static boolean hasHeader(ProxyRequestBuilder builder, String headerName) {
return builder.headers().keySet().stream().anyMatch(headerName::equalsIgnoreCase);
}
private static String firstHeader(ProxyRequestBuilder builder, String headerName) {
for (Map.Entry<String, List<String>> entry : builder.headers().entrySet()) {
if (entry.getKey().equalsIgnoreCase(headerName) && !entry.getValue().isEmpty()) {
return entry.getValue().get(0);
}
}
return null;
}
private static ProxyResult invokeHttpWithHostOverride(String finalUrl, String method, ProxyRequestBuilder builder)
throws IOException {
URI uri = URI.create(finalUrl);
int port = uri.getPort() == -1 ? 80 : uri.getPort();
String path = uri.getRawPath();
if (path == null || path.isBlank()) {
path = "/";
}
if (uri.getRawQuery() != null) {
path += "?" + uri.getRawQuery();
}
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(uri.getHost(), port), 10_000);
socket.setSoTimeout(30_000);
OutputStream out = socket.getOutputStream();
byte[] body = builder.body() == null ? new byte[0] : builder.body();
StringBuilder request = new StringBuilder()
.append(method.toUpperCase(Locale.ROOT)).append(' ').append(path).append(" HTTP/1.1\r\n")
.append("Host: ").append(firstHeader(builder, "Host")).append("\r\n")
.append("Connection: close\r\n");
for (Map.Entry<String, List<String>> header : builder.headers().entrySet()) {
String name = header.getKey();
String lower = name.toLowerCase(Locale.ROOT);
if (RESTRICTED.contains(lower) || lower.equals("connection")) {
continue;
}
for (String value : header.getValue()) {
request.append(name).append(": ").append(value).append("\r\n");
}
}
if (body.length > 0) {
request.append("Content-Length: ").append(body.length).append("\r\n");
}
request.append("\r\n");
out.write(request.toString().getBytes(StandardCharsets.ISO_8859_1));
out.write(body);
out.flush();
return readRawHttpResponse(socket.getInputStream());
}
}
private static ProxyResult readRawHttpResponse(InputStream input) throws IOException {
ByteArrayOutputStream headerBytes = new ByteArrayOutputStream();
int previous3 = -1;
int previous2 = -1;
int previous1 = -1;
int current;
while ((current = input.read()) != -1) {
headerBytes.write(current);
if (previous3 == '\r' && previous2 == '\n' && previous1 == '\r' && current == '\n') {
break;
}
previous3 = previous2;
previous2 = previous1;
previous1 = current;
}
String headersText = headerBytes.toString(StandardCharsets.ISO_8859_1);
String[] lines = headersText.split("\r\n");
if (lines.length == 0 || !lines[0].startsWith("HTTP/")) {
throw new IOException("invalid HTTP response");
}
String[] status = lines[0].split(" ", 3);
int statusCode = Integer.parseInt(status[1]);
Map<String, String> headers = new LinkedHashMap<>();
String transferEncoding = null;
int contentLength = -1;
for (int i = 1; i < lines.length; i++) {
int separator = lines[i].indexOf(':');
if (separator <= 0) {
continue;
}
String name = lines[i].substring(0, separator);
String value = lines[i].substring(separator + 1).trim();
if (name.equalsIgnoreCase("Transfer-Encoding")) {
transferEncoding = value;
}
if (name.equalsIgnoreCase("Content-Length")) {
contentLength = Integer.parseInt(value);
}
if (!HOP_BY_HOP.contains(name.toLowerCase(Locale.ROOT))) {
headers.put(name, value);
}
}
byte[] body = transferEncoding != null && transferEncoding.toLowerCase(Locale.ROOT).contains("chunked")
? readChunkedBody(input)
: contentLength >= 0 ? input.readNBytes(contentLength) : input.readAllBytes();
return new ProxyResult(statusCode, headers, body);
}
private static byte[] readChunkedBody(InputStream input) throws IOException {
ByteArrayOutputStream body = new ByteArrayOutputStream();
while (true) {
String sizeLine = readAsciiLine(input);
if (sizeLine == null) {
throw new IOException("unexpected end of chunked response");
}
int extension = sizeLine.indexOf(';');
int size = Integer.parseInt((extension >= 0 ? sizeLine.substring(0, extension) : sizeLine).trim(), 16);
if (size == 0) {
while (true) {
String trailer = readAsciiLine(input);
if (trailer == null || trailer.isEmpty()) {
return body.toByteArray();
}
}
}
body.write(input.readNBytes(size));
expectCrlf(input);
}
}
private static String readAsciiLine(InputStream input) throws IOException {
ByteArrayOutputStream line = new ByteArrayOutputStream();
while (true) {
int b = input.read();
if (b == -1) {
return line.size() == 0 ? null : line.toString(StandardCharsets.ISO_8859_1);
}
if (b == '\n') {
return line.toString(StandardCharsets.ISO_8859_1);
}
if (b == '\r') {
int next = input.read();
if (next == '\n') {
return line.toString(StandardCharsets.ISO_8859_1);
}
line.write(b);
if (next != -1) {
line.write(next);
}
continue;
}
line.write(b);
}
}
private static void expectCrlf(InputStream input) throws IOException {
int cr = input.read();
int lf = input.read();
if (cr != '\r' || lf != '\n') {
throw new IOException("invalid chunked response");
}
}
private static String buildFinalUrl(ProxyRequestBuilder builder) {
if (builder.queryParams().isEmpty()) return builder.url();
URI parsed = URI.create(builder.url());
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.elbv2.model.Action;
import io.github.hectorvent.floci.services.elbv2.model.Listener;
import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer;
import io.github.hectorvent.floci.services.elbv2.model.Rule;
import io.github.hectorvent.floci.services.elbv2.model.RuleCondition;
import io.github.hectorvent.floci.services.elbv2.model.TargetDescription;
@@ -68,13 +69,17 @@ public class ElbV2DataPlane {
@Inject
ObjectMapper objectMapper;
private final Map<String, HttpServer> servers = new ConcurrentHashMap<>();
private final Map<Integer, HttpServer> servers = new ConcurrentHashMap<>();
private final Map<Integer, Map<String, String>> listenersByHostAndPort = new ConcurrentHashMap<>();
private final Map<String, ListenerBinding> listenerBindings = new ConcurrentHashMap<>();
private final Map<String, AtomicReference<List<CompiledRule>>> ruleChains = new ConcurrentHashMap<>();
private final Map<String, AtomicInteger> rrCounters = new ConcurrentHashMap<>();
private final Map<String, String> listenerRegions = new ConcurrentHashMap<>();
private HttpClient proxyClient;
private record ListenerBinding(int port, String host) {}
@PostConstruct
void init() {
proxyClient = vertx.createHttpClient(new HttpClientOptions()
@@ -85,10 +90,12 @@ public class ElbV2DataPlane {
@PreDestroy
void shutdown() {
for (Map.Entry<String, HttpServer> e : servers.entrySet()) {
for (Map.Entry<Integer, HttpServer> e : servers.entrySet()) {
e.getValue().close();
}
servers.clear();
listenersByHostAndPort.clear();
listenerBindings.clear();
ruleChains.clear();
rrCounters.clear();
listenerRegions.clear();
@@ -102,40 +109,47 @@ public class ElbV2DataPlane {
List<CompiledRule> compiled = compileRules(rules);
ruleChains.put(listenerArn, new AtomicReference<>(compiled));
listenerRegions.put(listenerArn, region);
HttpServer server = vertx.createHttpServer(new HttpServerOptions()
.setHost("0.0.0.0")
.setPort(listener.getPort()));
server.requestHandler(req -> handleRequest(req, listenerArn, region));
server.listen()
.onSuccess(s -> {
servers.put(listenerArn, s);
LOG.infov("ELBv2 listener started on port {0} for {1}", String.valueOf(listener.getPort()), listenerArn);
})
.onFailure(err -> {
ruleChains.remove(listenerArn);
listenerRegions.remove(listenerArn);
LOG.warnv("ELBv2 listener failed to start on port {0}: {1}", String.valueOf(listener.getPort()), err.getMessage());
});
ListenerBinding binding = binding(listener, region);
listenerBindings.put(listenerArn, binding);
listenersByHostAndPort.computeIfAbsent(binding.port(), ignored -> new ConcurrentHashMap<>())
.put(binding.host(), listenerArn);
servers.computeIfAbsent(binding.port(), this::startPortServer);
}
public void restartListener(Listener listener, String region, List<Rule> rules) {
if (config.services().elbv2().mock()) {
return;
}
HttpServer server = servers.remove(listener.getListenerArn());
if (server == null) {
startListener(listener, region, rules);
String listenerArn = listener.getListenerArn();
ListenerBinding newBinding = binding(listener, region);
ListenerBinding oldBinding = listenerBindings.get(listenerArn);
if (newBinding.equals(oldBinding)) {
ruleChains.put(listenerArn, new AtomicReference<>(compileRules(rules)));
listenerRegions.put(listenerArn, region);
listenersByHostAndPort.computeIfAbsent(newBinding.port(), ignored -> new ConcurrentHashMap<>())
.put(newBinding.host(), listenerArn);
servers.computeIfAbsent(newBinding.port(), this::startPortServer);
return;
}
server.close().onComplete(ignored -> startListener(listener, region, rules));
oldBinding = listenerBindings.remove(listenerArn);
if (oldBinding != null) {
Map<String, String> listenersByHost = listenersByHostAndPort.get(oldBinding.port());
if (listenersByHost != null) {
listenersByHost.remove(oldBinding.host(), listenerArn);
closePortServerIfUnused(oldBinding.port(), listenersByHost);
}
}
startListener(listener, region, rules);
}
public void stopListener(String listenerArn) {
HttpServer server = servers.remove(listenerArn);
if (server != null) {
server.close();
ListenerBinding binding = listenerBindings.remove(listenerArn);
if (binding != null) {
Map<String, String> listenersByHost = listenersByHostAndPort.get(binding.port());
if (listenersByHost != null) {
listenersByHost.remove(binding.host(), listenerArn);
closePortServerIfUnused(binding.port(), listenersByHost);
}
}
ruleChains.remove(listenerArn);
listenerRegions.remove(listenerArn);
@@ -148,7 +162,62 @@ public class ElbV2DataPlane {
}
}
private void handleRequest(io.vertx.core.http.HttpServerRequest req, String listenerArn, String region) {
private HttpServer startPortServer(int port) {
HttpServer server = vertx.createHttpServer(new HttpServerOptions()
.setHost("0.0.0.0")
.setPort(port));
server.requestHandler(req -> handleRequest(req, port));
server.listen()
.onSuccess(s -> LOG.infov("ELBv2 listener port started on {0}", String.valueOf(port)))
.onFailure(err -> {
servers.remove(port);
clearPortBindings(port);
server.close();
LOG.warnv("ELBv2 listener port failed to start on {0}: {1}", String.valueOf(port), err.getMessage());
});
return server;
}
private void closePortServerIfUnused(int port, Map<String, String> listenersByHost) {
if (!listenersByHost.isEmpty()) {
return;
}
listenersByHostAndPort.remove(port, listenersByHost);
HttpServer server = servers.remove(port);
if (server != null) {
server.close();
}
}
private void clearPortBindings(int port) {
Map<String, String> listenersByHost = listenersByHostAndPort.remove(port);
if (listenersByHost == null) {
return;
}
for (String listenerArn : listenersByHost.values()) {
listenerBindings.remove(listenerArn);
ruleChains.remove(listenerArn);
listenerRegions.remove(listenerArn);
}
}
private ListenerBinding binding(Listener listener, String region) {
LoadBalancer loadBalancer = elbV2Service.getLoadBalancer(region, listener.getLoadBalancerArn());
String host = loadBalancer != null ? normalizeHost(loadBalancer.getDnsName()) : listener.getLoadBalancerArn();
return new ListenerBinding(listener.getPort(), host);
}
private void handleRequest(io.vertx.core.http.HttpServerRequest req, int port) {
String listenerArn = resolveListenerArn(port, req.host());
if (listenerArn == null) {
req.response().setStatusCode(502).end("No listener for host");
return;
}
String region = listenerRegions.get(listenerArn);
if (region == null) {
req.response().setStatusCode(502).end("No listener region");
return;
}
AtomicReference<List<CompiledRule>> ref = ruleChains.get(listenerArn);
if (ref == null) {
req.response().setStatusCode(502).end("No rule chain");
@@ -164,6 +233,35 @@ public class ElbV2DataPlane {
req.response().setStatusCode(502).end("No matching rule");
}
private String resolveListenerArn(int port, String hostHeader) {
Map<String, String> listenersByHost = listenersByHostAndPort.get(port);
if (listenersByHost == null || listenersByHost.isEmpty()) {
return null;
}
String host = normalizeHost(hostHeader);
String listenerArn = listenersByHost.get(host);
if (listenerArn != null) {
return listenerArn;
}
if (listenersByHost.size() == 1) {
return listenersByHost.values().iterator().next();
}
return null;
}
private static String normalizeHost(String host) {
if (host == null) {
return "";
}
String normalized = host.trim().toLowerCase();
int colon = normalized.lastIndexOf(':');
int bracket = normalized.lastIndexOf(']');
if (colon > -1 && colon > bracket) {
normalized = normalized.substring(0, colon);
}
return normalized;
}
private void executeAction(io.vertx.core.http.HttpServerRequest req, Action action, String region) {
if (action == null) {
req.response().setStatusCode(502).end("No action");
@@ -259,6 +259,10 @@ public class ElbV2Service {
persistRegion(loadBalancers, region);
}
LoadBalancer getLoadBalancer(String region, String arn) {
return loadBalancers.getOrDefault(region, Map.of()).get(arn);
}
/** Capacity reservation status for a load balancer. All fields are {@code null} when no
* capacity is reserved, which is always the case in Floci (capacity cannot be reserved). */
public record CapacityReservation(Integer decreaseRequestsRemaining,