Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(elbv2): dispatch a shared listener port by the hostnames rules declare (#4207)

Abhigya8d9ae9554d0f
diff --git a/docs/services/elb.md b/docs/services/elb.md
index 9b4b4c793f..c04243bd92 100644
--- a/docs/services/elb.md
+++ b/docs/services/elb.md
@@ -174,3 +174,32 @@ aws elbv2 delete-target-group \
## Listener Ports
Listener sockets bind on the Floci host. Expose any listener ports you need in Docker Compose when Floci itself runs in a container, similar to RDS and ElastiCache proxy ports.
+
+### Two load balancers on the same port
+
+In AWS each load balancer has its own DNS name and addresses, so two of them can both listen on
+port 80 and never interact: the network picks the load balancer, and a `host-header` rule only picks
+a rule inside one listener. Floci serves every load balancer from a single socket per port, so the
+Host header has to carry both decisions. A template that puts a public and an internal load balancer
+on port 80 is correct for AWS and stays accepted here, but the request has to name the one it wants.
+
+A listener is chosen in this order:
+
+1. The Host header equals a load balancer's own DNS name (`{name}-{id}.elb.localhost.floci.io`).
+2. Exactly one listener on the port has a rule whose `host-header` condition matches the Host
+ header. This uses the same matching as the rule evaluation that follows, so it is
+ case-insensitive, ignores the port, and applies AWS's wildcards: `*` matches 0 or more
+ characters and `?` matches exactly 1, which means `*.example.com` claims `test.example.com`
+ but not `example.com`. `HostHeaderConfig.RegexValues` is not supported, by rule evaluation or
+ by selection, so a load balancer that names itself only through a regex cannot be selected
+ this way.
+3. Only one listener is on the port, in which case it answers any Host header.
+
+If none of those resolve, and in particular when two load balancers declare the same hostname or
+neither declares any, the request answers `502 No listener for host`. Floci logs a warning naming
+both load balancers the first time a second one takes a port, because the targets behind them stay
+healthy and nothing else reports the collision.
+
+Giving each load balancer a `host-header` rule for the hostname it serves is usually enough, and it
+is the same configuration AWS needs. Moving one load balancer to a different listener port also
+works, at the cost of a Floci-only difference from the deployed template.
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 e4f864a965..6c9e532e57 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
@@ -123,8 +123,10 @@ public class ElbV2DataPlane {
listenerRegions.put(listenerArn, region);
ListenerBinding binding = binding(listener, region);
listenerBindings.put(listenerArn, binding);
- listenersByHostAndPort.computeIfAbsent(binding.port(), ignored -> new ConcurrentHashMap<>())
- .put(binding.host(), listenerArn);
+ Map<String, String> listenersOnPort =
+ listenersByHostAndPort.computeIfAbsent(binding.port(), ignored -> new ConcurrentHashMap<>());
+ warnOnSharedPort(binding, listenersOnPort);
+ listenersOnPort.put(binding.host(), listenerArn);
ensureReleaseHandlerRegistered();
servers.computeIfAbsent(binding.port(), this::startPortServer);
}
@@ -279,6 +281,29 @@ public class ElbV2DataPlane {
}
}
+ /**
+ * Warns when a second load balancer takes a port another one already serves. Real AWS gives
+ * every load balancer its own address, so two listeners on port 80 are correct there and a
+ * template that works in AWS is not wrong. Floci serves them all from one socket per port,
+ * which leaves the collision invisible: nothing fails, and every request whose Host header
+ * names neither load balancer answers 502 with perfectly healthy targets behind it.
+ */
+ private void warnOnSharedPort(ListenerBinding binding, Map<String, String> listenersOnPort) {
+ for (String otherArn : listenersOnPort.values()) {
+ ListenerBinding other = listenerBindings.get(otherArn);
+ if (other == null || other.loadBalancerArn().equals(binding.loadBalancerArn())) {
+ continue;
+ }
+ LOG.warnv("ELBv2 port {0} now serves two load balancers, {1} and {2}. Floci runs them "
+ + "on one socket and dispatches by Host header, so a request must send {3} "
+ + "or {4}, or a hostname one of their rules declares in a host-header "
+ + "condition. Any other Host header answers 502.",
+ String.valueOf(binding.port()), other.loadBalancerArn(), binding.loadBalancerArn(),
+ other.host(), binding.host());
+ return;
+ }
+ }
+
private ListenerBinding binding(Listener listener, String region) {
LoadBalancer loadBalancer = elbV2Service.getLoadBalancer(region, listener.getLoadBalancerArn());
String host = loadBalancer != null ? normalizeHost(loadBalancer.getDnsName()) : listener.getLoadBalancerArn();
@@ -311,6 +336,20 @@ public class ElbV2DataPlane {
req.response().setStatusCode(502).end("No matching rule");
}
+ /**
+ * Chooses the listener that serves a request arriving on a shared port.
+ *
+ * <p>Real AWS has no such step. Every load balancer gets its own DNS name and addresses, so
+ * the network picks the load balancer and a {@code host-header} rule only picks a rule inside
+ * one listener. Floci serves every load balancer from a single socket per port, so the Host
+ * header has to carry both decisions.
+ *
+ * <p>The load balancer's own DNS name wins first. Failing that, a listener whose rules already
+ * declare the hostname claims it: a deployment that puts two load balancers on port 80 names
+ * them in host-header conditions anyway, so this reuses what the template already says instead
+ * of inventing a Floci-only knob. A lone listener on the port still answers anything, so a
+ * single load balancer needs no hostname at all.
+ */
private String resolveListenerArn(int port, String hostHeader) {
Map<String, String> listenersByHost = listenersByHostAndPort.get(port);
if (listenersByHost == null || listenersByHost.isEmpty()) {
@@ -321,12 +360,39 @@ public class ElbV2DataPlane {
if (listenerArn != null) {
return listenerArn;
}
+ List<String> declaring = listenersDeclaringHost(listenersByHost, host);
+ if (declaring.size() == 1) {
+ return declaring.get(0);
+ }
+ if (declaring.size() > 1) {
+ LOG.debugv("ELBv2 port {0}: {1} listeners declare Host {2} in a host-header condition, "
+ + "so none of them can claim it", String.valueOf(port),
+ String.valueOf(declaring.size()), host);
+ return null;
+ }
if (listenersByHost.size() == 1) {
return listenersByHost.values().iterator().next();
}
return null;
}
+ private List<String> listenersDeclaringHost(Map<String, String> listenersByHost, String host) {
+ List<String> declaring = new ArrayList<>();
+ for (String listenerArn : listenersByHost.values()) {
+ AtomicReference<List<CompiledRule>> ref = ruleChains.get(listenerArn);
+ if (ref == null) {
+ continue;
+ }
+ for (CompiledRule compiled : ref.get()) {
+ if (compiled.declaresHost(host)) {
+ declaring.add(listenerArn);
+ break;
+ }
+ }
+ }
+ return declaring;
+ }
+
private static String normalizeHost(String host) {
if (host == null) {
return "";
@@ -796,10 +862,38 @@ public class ElbV2DataPlane {
private class CompiledRule {
final Rule rule;
final Action action;
+ final List<String> hostHeaderPatterns;
CompiledRule(Rule rule) {
this.rule = rule;
this.action = getRoutingAction(rule);
+ this.hostHeaderPatterns = hostHeaderPatterns(rule);
+ }
+
+ /**
+ * The hostnames this rule declares through its {@code host-header} conditions. Collected
+ * at compile time because listener selection consults them on every request, before any
+ * rule is evaluated. The default rule declares nothing: it matches every Host header, so
+ * counting it would make every listener claim every hostname.
+ */
+ private static List<String> hostHeaderPatterns(Rule rule) {
+ if (rule.isDefault() || rule.getConditions() == null) {
+ return List.of();
+ }
+ List<String> patterns = new ArrayList<>();
+ for (RuleCondition condition : rule.getConditions()) {
+ if (!"host-header".equals(condition.getField())) {
+ continue;
+ }
+ patterns.addAll(condition.getHostHeaderValues().isEmpty()
+ ? condition.getValues()
+ : condition.getHostHeaderValues());
+ }
+ return patterns;
+ }
+
+ boolean declaresHost(String host) {
+ return hostHeaderPatterns.stream().anyMatch(p -> globMatches(p, host));
}
boolean matches(io.vertx.core.http.HttpServerRequest req) {
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
index 97b57eee29..3b2dc01ac8 100644
--- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2SamePortHostDispatchIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2SamePortHostDispatchIntegrationTest.java
@@ -3,11 +3,14 @@ package io.github.hectorvent.floci.services.elbv2;
import io.github.hectorvent.floci.testing.RealElbV2DataPlaneProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
+import io.restassured.specification.RequestSpecification;
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.List;
+
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.equalTo;
@@ -27,6 +30,8 @@ class ElbV2SamePortHostDispatchIntegrationTest {
private static String secondLbArn;
private static String secondDnsName;
private static String secondListenerArn;
+ private static String firstRuleArn;
+ private static String secondRuleArn;
@Test
@Order(1)
@@ -107,15 +112,92 @@ class ElbV2SamePortHostDispatchIntegrationTest {
assertNoListenerForHost("unknown.example.test");
}
+ @Test
+ @Order(6)
+ void samePortListenerClaimsAHostItsRulesDeclare() {
+ secondRuleArn = createHostHeaderRule(secondListenerArn, 10,
+ List.of("app.example.test", "*.wild.example.test"), "second-rule");
+
+ assertHostResponse("app.example.test", "second-rule");
+ assertHostResponse("api.wild.example.test", "second-rule");
+ assertHostResponse("APP.EXAMPLE.TEST", "second-rule");
+ }
+
+ /**
+ * AWS states that the rule {@code *.example.com} matches {@code test.example.com} but not
+ * {@code example.com}, so a wildcard must not let a listener claim the bare domain either.
+ */
+ @Test
+ @Order(7)
+ void aWildcardRuleDoesNotClaimTheBareDomain() {
+ assertNoListenerForHost("wild.example.test");
+ }
+
+ @Test
+ @Order(8)
+ void aDeclaredHostDoesNotDisplaceTheLoadBalancerDnsName() {
+ assertHostResponse(firstDnsName, "first");
+ assertHostResponse(secondDnsName, "second");
+ }
+
+ @Test
+ @Order(9)
+ void aHostBothListenersDeclareStaysUnclaimed() {
+ firstRuleArn = createHostHeaderRule(firstListenerArn, 10,
+ List.of("app.example.test"), "first-rule");
+
+ assertNoListenerForHost("app.example.test");
+ assertHostResponse("api.wild.example.test", "second-rule");
+ }
+
@Test
@Order(Integer.MAX_VALUE)
void cleanup() {
+ deleteRule(firstRuleArn);
+ deleteRule(secondRuleArn);
deleteListener(firstListenerArn);
deleteListener(secondListenerArn);
deleteLoadBalancer(firstLbArn);
deleteLoadBalancer(secondLbArn);
}
+ private static String createHostHeaderRule(String listenerArn, int priority, List<String> hosts, String body) {
+ RequestSpecification request = given()
+ .formParam("Action", "CreateRule")
+ .formParam("ListenerArn", listenerArn)
+ .formParam("Priority", String.valueOf(priority))
+ .formParam("Conditions.member.1.Field", "host-header")
+ .formParam("Actions.member.1.Type", "fixed-response")
+ .formParam("Actions.member.1.FixedResponseConfig.StatusCode", "200")
+ .formParam("Actions.member.1.FixedResponseConfig.ContentType", "text/plain")
+ .formParam("Actions.member.1.FixedResponseConfig.MessageBody", body)
+ .header("Authorization", AUTH);
+ for (int i = 0; i < hosts.size(); i++) {
+ request = request.formParam(
+ "Conditions.member.1.HostHeaderConfig.Values.member." + (i + 1), hosts.get(i));
+ }
+ return request
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("CreateRuleResponse.CreateRuleResult.Rules.member.RuleArn");
+ }
+
+ private static void deleteRule(String ruleArn) {
+ if (ruleArn != null) {
+ given()
+ .formParam("Action", "DeleteRule")
+ .formParam("RuleArn", ruleArn)
+ .header("Authorization", AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(anyOf(equalTo(200), equalTo(204)));
+ }
+ }
+
private static String createFixedResponseListener(String lbArn, String body) {
return given()
.formParam("Action", "CreateListener")