Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Jason van Zyldd566857ef34
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 3988022a7d..c5ff93829a 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
@@ -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;
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java
index 62b8b5d765..7c41aa937d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java
@@ -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());
diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java
index 222dc69138..b13b141354 100644
--- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java
+++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java
@@ -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");
diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java
index 5de1a4b379..72d2c4b585 100644
--- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java
@@ -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,
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2AlbIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2AlbIntegrationTest.java
index 347657e441..130414085e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2AlbIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2AlbIntegrationTest.java
@@ -14,15 +14,13 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
+import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
-import java.net.URI;
-import java.net.http.HttpClient;
-import java.net.http.HttpRequest;
-import java.net.http.HttpResponse;
+import java.net.Socket;
import java.nio.charset.StandardCharsets;
-import java.time.Duration;
import java.util.Map;
import static io.restassured.RestAssured.given;
@@ -52,6 +50,7 @@ class ApiGatewayV2AlbIntegrationTest {
private static int stubPort;
private static String lbArn;
+ private static String lbDnsName;
private static String tgArn;
private static String listenerArn;
private static String vpcLinkId;
@@ -86,7 +85,7 @@ class ApiGatewayV2AlbIntegrationTest {
@Test
@Order(1)
void createLoadBalancer() {
- lbArn = given()
+ Response response = given()
.formParam("Action", "CreateLoadBalancer")
.formParam("Name", "apigw-alb-test")
.formParam("Type", "application")
@@ -97,7 +96,9 @@ class ApiGatewayV2AlbIntegrationTest {
.then()
.statusCode(200)
.extract()
- .path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn");
+ .response();
+ lbArn = response.path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn");
+ lbDnsName = response.path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.DNSName");
}
@Test
@@ -254,19 +255,11 @@ class ApiGatewayV2AlbIntegrationTest {
// Verifies the ALB data plane independently of the API Gateway path: hit the
// listener directly. Polls because server.listen() is async — if the listener
// never accepts a connection we get a fast ConnectException and retry.
- HttpClient client = HttpClient.newBuilder()
- .connectTimeout(Duration.ofSeconds(2))
- .build();
- HttpRequest req = HttpRequest.newBuilder()
- .uri(URI.create("http://127.0.0.1:" + LISTENER_PORT + "/health"))
- .timeout(Duration.ofSeconds(3))
- .GET()
- .build();
long deadline = System.currentTimeMillis() + 15_000;
Exception lastErr = null;
while (System.currentTimeMillis() < deadline) {
try {
- HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
+ RawHttpResponse resp = rawGetWithHost("/health", lbDnsName);
if (resp.statusCode() == 200 && resp.body().contains("\"status\":\"ok\"")) {
return;
}
@@ -279,6 +272,47 @@ class ApiGatewayV2AlbIntegrationTest {
Assertions.fail("listener direct probe never succeeded: " + lastErr);
}
+ private static RawHttpResponse rawGetWithHost(String path, String host) throws IOException {
+ try (Socket socket = new Socket()) {
+ socket.connect(new InetSocketAddress("127.0.0.1", LISTENER_PORT), 2_000);
+ socket.setSoTimeout(3_000);
+ OutputStream output = socket.getOutputStream();
+ String request = "GET " + path + " HTTP/1.1\r\n"
+ + "Host: " + host + "\r\n"
+ + "Connection: close\r\n"
+ + "\r\n";
+ output.write(request.getBytes(StandardCharsets.ISO_8859_1));
+ output.flush();
+ return readRawHttpResponse(socket.getInputStream());
+ }
+ }
+
+ private static RawHttpResponse 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[] lines = headerBytes.toString(StandardCharsets.ISO_8859_1).split("\r\n");
+ if (lines.length == 0 || !lines[0].startsWith("HTTP/")) {
+ throw new IOException("invalid HTTP response");
+ }
+ int statusCode = Integer.parseInt(lines[0].split(" ", 3)[1]);
+ return new RawHttpResponse(statusCode, new String(input.readAllBytes(), StandardCharsets.UTF_8));
+ }
+
+ private record RawHttpResponse(int statusCode, String body) {}
+
/** Full HttpAlbIntegration happy path: execute-api → ALB resolver → listener → stub returns 200. */
@Test
@Order(11)
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvokerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvokerTest.java
index 6c8144711e..b941f6c7a0 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvokerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvokerTest.java
@@ -113,6 +113,41 @@ class HttpProxyInvokerTest {
assertEquals("u-42", received.get().headers().getFirst("X-User-Id"));
}
+ @Test
+ void appliesRequestParametersHostHeaderOverride() {
+ Integration integration = httpProxyIntegration(
+ "http://127.0.0.1:" + backendPort + "/public/{proxy}",
+ Map.of("overwrite:header.Host", "lb.localhost.test"));
+ RequestContext ctx = ctxFor("GET", "/wallet/balance", "balance",
+ Map.of("Host", "client.example.test"), Map.of(), null, Map.of());
+
+ new HttpProxyInvoker().invoke(integration, ctx);
+
+ assertEquals("lb.localhost.test", received.get().headers().getFirst("Host"));
+ }
+
+ @Test
+ void hostHeaderOverrideDecodesChunkedResponse() {
+ backend.removeContext("/");
+ backend.createContext("/", exchange -> {
+ byte[] resp = "chunked-body".getBytes(StandardCharsets.UTF_8);
+ exchange.sendResponseHeaders(200, 0);
+ exchange.getResponseBody().write(resp);
+ exchange.close();
+ });
+ Integration integration = httpProxyIntegration(
+ "http://127.0.0.1:" + backendPort + "/public/{proxy}",
+ Map.of("overwrite:header.Host", "lb.localhost.test"));
+ RequestContext ctx = ctxFor("GET", "/wallet/balance", "balance",
+ Map.of("Host", "client.example.test"), Map.of(), null, Map.of());
+
+ ProxyResult result = new HttpProxyInvoker().invoke(integration, ctx);
+
+ assertEquals(200, result.statusCode());
+ assertEquals("chunked-body", new String(result.body(), StandardCharsets.UTF_8));
+ assertFalse(result.headers().containsKey("Transfer-encoding"));
+ }
+
@Test
void overwritePathReplacesBackendPath() {
Integration integration = httpProxyIntegration(
diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2LambdaTargetDataPlaneIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2LambdaTargetDataPlaneIntegrationTest.java
index 827c2449d6..6aa692403c 100644
--- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2LambdaTargetDataPlaneIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2LambdaTargetDataPlaneIntegrationTest.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.elbv2;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
+import io.restassured.response.Response;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
@@ -48,6 +49,7 @@ class ElbV2LambdaTargetDataPlaneIntegrationTest {
private static final int LISTENER_PORT = 7782;
private static String lbArn;
+ private static String lbDnsName;
private static String tgArn;
private static String listenerArn;
private static String functionArn;
@@ -96,7 +98,7 @@ class ElbV2LambdaTargetDataPlaneIntegrationTest {
@Test
@Order(2)
void createLoadBalancer() {
- lbArn = given()
+ Response response = given()
.formParam("Action", "CreateLoadBalancer")
.formParam("Name", "alb-dataplane-lb")
.formParam("Type", "application")
@@ -106,7 +108,9 @@ class ElbV2LambdaTargetDataPlaneIntegrationTest {
.then()
.statusCode(200)
.extract()
- .path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn");
+ .response();
+ lbArn = response.path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn");
+ lbDnsName = response.path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.DNSName");
}
@Test
@@ -165,7 +169,7 @@ class ElbV2LambdaTargetDataPlaneIntegrationTest {
@Order(5)
void httpRequestThroughListenerInvokesLambda() {
given()
- .baseUri("http://localhost")
+ .baseUri("http://" + lbDnsName)
.port(LISTENER_PORT)
.contentType("text/plain")
.body("hello")
diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2SamePortHostDispatchIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2SamePortHostDispatchIntegrationTest.java
new file mode 100644
index 0000000000..650e83e751
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2SamePortHostDispatchIntegrationTest.java
@@ -0,0 +1,196 @@
+package io.github.hectorvent.floci.services.elbv2;
+
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.QuarkusTestProfile;
+import io.quarkus.test.junit.TestProfile;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import java.util.Map;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.anyOf;
+import static org.hamcrest.Matchers.equalTo;
+
+@QuarkusTest
+@TestProfile(ElbV2SamePortHostDispatchIntegrationTest.RealElbV2DataPlaneProfile.class)
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class ElbV2SamePortHostDispatchIntegrationTest {
+
+ public static final class RealElbV2DataPlaneProfile implements QuarkusTestProfile {
+ @Override
+ public Map<String, String> getConfigOverrides() {
+ return Map.of("floci.services.elbv2.mock", "false");
+ }
+ }
+
+ private static final String AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260629/us-east-1/elasticloadbalancing/aws4_request";
+ private static final int LISTENER_PORT = 7793;
+
+ private static String firstLbArn;
+ private static String firstDnsName;
+ private static String firstListenerArn;
+ private static String secondLbArn;
+ private static String secondDnsName;
+ private static String secondListenerArn;
+
+ @Test
+ @Order(1)
+ void createFirstLoadBalancerAndListener() {
+ firstLbArn = given()
+ .formParam("Action", "CreateLoadBalancer")
+ .formParam("Name", "same-port-first")
+ .formParam("Type", "application")
+ .formParam("Scheme", "internet-facing")
+ .header("Authorization", AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn");
+
+ firstDnsName = given()
+ .formParam("Action", "DescribeLoadBalancers")
+ .formParam("LoadBalancerArns.member.1", firstLbArn)
+ .header("Authorization", AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.DNSName");
+
+ firstListenerArn = createFixedResponseListener(firstLbArn, "first");
+ }
+
+ @Test
+ @Order(2)
+ void singleListenerFallsBackForUnknownHostHeader() {
+ assertHostResponse("unknown.example.test", "first");
+ }
+
+ @Test
+ @Order(3)
+ void createSecondLoadBalancerAndListenerOnSamePort() {
+ secondLbArn = given()
+ .formParam("Action", "CreateLoadBalancer")
+ .formParam("Name", "same-port-second")
+ .formParam("Type", "application")
+ .formParam("Scheme", "internet-facing")
+ .header("Authorization", AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn");
+
+ secondDnsName = given()
+ .formParam("Action", "DescribeLoadBalancers")
+ .formParam("LoadBalancerArns.member.1", secondLbArn)
+ .header("Authorization", AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.DNSName");
+
+ secondListenerArn = createFixedResponseListener(secondLbArn, "second");
+ }
+
+ @Test
+ @Order(4)
+ void samePortListenersDispatchByHostHeader() {
+ assertHostResponse(firstDnsName, "first");
+ assertHostResponse(secondDnsName, "second");
+ }
+
+ @Test
+ @Order(5)
+ void samePortListenersRejectUnknownHostHeader() {
+ assertNoListenerForHost("unknown.example.test");
+ }
+
+ @Test
+ @Order(Integer.MAX_VALUE)
+ void cleanup() {
+ deleteListener(firstListenerArn);
+ deleteListener(secondListenerArn);
+ deleteLoadBalancer(firstLbArn);
+ deleteLoadBalancer(secondLbArn);
+ }
+
+ private static String createFixedResponseListener(String lbArn, String body) {
+ return given()
+ .formParam("Action", "CreateListener")
+ .formParam("LoadBalancerArn", lbArn)
+ .formParam("Protocol", "HTTP")
+ .formParam("Port", String.valueOf(LISTENER_PORT))
+ .formParam("DefaultActions.member.1.Type", "fixed-response")
+ .formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")
+ .formParam("DefaultActions.member.1.FixedResponseConfig.ContentType", "text/plain")
+ .formParam("DefaultActions.member.1.FixedResponseConfig.MessageBody", body)
+ .header("Authorization", AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("CreateListenerResponse.CreateListenerResult.Listeners.member.ListenerArn");
+ }
+
+ private static void assertHostResponse(String host, String body) {
+ given()
+ .baseUri("http://127.0.0.1")
+ .port(LISTENER_PORT)
+ .header("Host", host)
+ .when()
+ .get("/")
+ .then()
+ .statusCode(200)
+ .body(equalTo(body));
+ }
+
+ private static void assertNoListenerForHost(String host) {
+ given()
+ .baseUri("http://127.0.0.1")
+ .port(LISTENER_PORT)
+ .header("Host", host)
+ .when()
+ .get("/")
+ .then()
+ .statusCode(502)
+ .body(equalTo("No listener for host"));
+ }
+
+ private static void deleteListener(String listenerArn) {
+ if (listenerArn != null) {
+ given()
+ .formParam("Action", "DeleteListener")
+ .formParam("ListenerArn", listenerArn)
+ .header("Authorization", AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(anyOf(equalTo(200), equalTo(204)));
+ }
+ }
+
+ private static void deleteLoadBalancer(String lbArn) {
+ if (lbArn != null) {
+ given()
+ .formParam("Action", "DeleteLoadBalancer")
+ .formParam("LoadBalancerArn", lbArn)
+ .header("Authorization", AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(anyOf(equalTo(200), equalTo(204)));
+ }
+ }
+}