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

@@ -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)
@@ -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(
@@ -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")
@@ -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)));
}
}
}