fix(elbv2): serve and restore load balancers outside the default account (#7620)

A listener port carries no credentials, so the data plane read target
groups, load balancers and listeners as the default account and answered
502 for any other account. Read them as the account in the listener ARN.

Startup ran outside a request too, so only the default account's indexes,
listeners and health monitors came back. Rebuild the indexes from every
account and restore each stored account as itself.

Signed-off-by: ShryukGrandhi <85529990+ShryukGrandhi@users.noreply.github.com>
This commit is contained in:
ShryukGrandhi authored and GitHub committed 2026-11-05 16:38:40 -04:00
1 parent 221d25a4cd
commit 13d6dd18d4
4 files changed
+182 -26

No files matched your search

@@ -4,10 +4,12 @@ import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.TlsProxyServer;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;
import io.github.hectorvent.floci.core.common.CertificateReferenceResolver.CertificateMaterial;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.core.common.RequestHost;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.WebSocketUpgrades;
import io.github.hectorvent.floci.core.common.tls.ReloadingKeyManager;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
@@ -698,7 +700,8 @@ public class ElbV2DataPlane {
.filter(candidate -> candidate != null && "forward".equals(candidate.getType()))
.findFirst().orElse(null);
String tgArn = action == null ? null : resolveTgArn(action);
TargetGroup tg = tgArn == null ? null : elbV2Service.getTargetGroup(listener.region(), tgArn);
TargetGroup tg = tgArn == null ? null
: asOwner(listener.arn(), () -> elbV2Service.getTargetGroup(listener.region(), tgArn));
if (tg == null || "lambda".equals(tg.getTargetType())) {
socket.close();
return;
@@ -1105,7 +1108,7 @@ public class ElbV2DataPlane {
req.response().setStatusCode(502).end("No target group");
return;
}
TargetGroup tg = elbV2Service.getTargetGroup(region, tgArn);
TargetGroup tg = asOwner(listenerArn, () -> elbV2Service.getTargetGroup(region, tgArn));
if (tg == null) {
req.response().setStatusCode(502).end("Target group not found");
return;
@@ -1167,13 +1170,19 @@ public class ElbV2DataPlane {
if (binding == null) {
return null;
}
LoadBalancer loadBalancer = elbV2Service.getLoadBalancer(region, binding.loadBalancerArn());
LoadBalancer loadBalancer = asOwner(listenerArn,
() -> elbV2Service.getLoadBalancer(region, binding.loadBalancerArn()));
if (loadBalancer == null || loadBalancer.getAttributes() == null) {
return null;
}
return loadBalancer.getAttributes().get(key);
}
/** A request on a listener port carries no credentials, so its reads run as the listener's owner. */
private static <T> T asOwner(String listenerArn, Supplier<T> read) {
return RequestScopes.callAs(AwsArnUtils.parse(listenerArn).accountId(), read);
}
private long parseTimeoutMillis(String configured, String attributeKey, long defaultSeconds) {
long seconds = defaultSeconds;
if (configured != null) {
@@ -1192,7 +1201,7 @@ public class ElbV2DataPlane {
}
private String listenerAttribute(String listenerArn, String region, String key) {
Listener listener = elbV2Service.getListener(region, listenerArn);
Listener listener = asOwner(listenerArn, () -> elbV2Service.getListener(region, listenerArn));
if (listener == null || listener.getAttributes() == null) {
return null;
}
@@ -7,12 +7,14 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegionFacts;
import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import io.github.hectorvent.floci.core.common.SsrfProtection;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackedMap;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.acm.AcmCertificateReferenceProvider.CertificateReference;
@@ -81,6 +83,12 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
private Map<String, Map<String, Listener>> listeners = new ConcurrentHashMap<>();
private Map<String, Map<String, Rule>> rules = new ConcurrentHashMap<>();
// The stores behind the maps above, which only see the current account; null without a StorageFactory
private AccountAwareStorageBackend<Map<String, LoadBalancer>> loadBalancerStore;
private AccountAwareStorageBackend<Map<String, TargetGroup>> targetGroupStore;
private AccountAwareStorageBackend<Map<String, Listener>> listenerStore;
private AccountAwareStorageBackend<Map<String, Rule>> ruleStore;
// indexes
private final Map<String, List<String>> lbToListeners = new ConcurrentHashMap<>(); // LB-ARN → listener ARNs
private final Map<String, List<String>> listenerToRules = new ConcurrentHashMap<>(); // Listener-ARN → rule ARNs
@@ -95,14 +103,18 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
if (storageFactory == null) {
return;
}
this.loadBalancers = storageBacked("elbv2-load-balancers.json",
this.loadBalancerStore = storageFactory.create("elbv2", "elbv2-load-balancers.json",
new TypeReference<Map<String, Map<String, LoadBalancer>>>() {});
this.targetGroups = storageBacked("elbv2-target-groups.json",
this.targetGroupStore = storageFactory.create("elbv2", "elbv2-target-groups.json",
new TypeReference<Map<String, Map<String, TargetGroup>>>() {});
this.listeners = storageBacked("elbv2-listeners.json",
this.listenerStore = storageFactory.create("elbv2", "elbv2-listeners.json",
new TypeReference<Map<String, Map<String, Listener>>>() {});
this.rules = storageBacked("elbv2-rules.json",
this.ruleStore = storageFactory.create("elbv2", "elbv2-rules.json",
new TypeReference<Map<String, Map<String, Rule>>>() {});
this.loadBalancers = new StorageBackedMap<>(loadBalancerStore);
this.targetGroups = new StorageBackedMap<>(targetGroupStore);
this.listeners = new StorageBackedMap<>(listenerStore);
this.rules = new StorageBackedMap<>(ruleStore);
this.tags = storageBacked("elbv2-tags.json",
new TypeReference<Map<String, Map<String, String>>>() {});
normalizeRegionMaps(loadBalancers);
@@ -158,32 +170,54 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
listenerToRules.clear();
tgToLbs.clear();
for (Map<String, Listener> regionListeners : listeners.values()) {
for (Map<String, Listener> regionListeners : allAccounts(listeners, listenerStore)) {
for (Listener listener : regionListeners.values()) {
lbToListeners.computeIfAbsent(listener.getLoadBalancerArn(), k -> new CopyOnWriteArrayList<>())
.add(listener.getListenerArn());
}
}
for (Map<String, Rule> regionRules : rules.values()) {
for (Map<String, Rule> regionRules : allAccounts(rules, ruleStore)) {
for (Rule rule : regionRules.values()) {
listenerToRules.computeIfAbsent(rule.getListenerArn(), k -> new CopyOnWriteArrayList<>())
.add(rule.getRuleArn());
}
}
for (Map.Entry<String, Map<String, TargetGroup>> regionEntry : targetGroups.entrySet()) {
for (TargetGroup targetGroup : regionEntry.getValue().values()) {
for (Map<String, TargetGroup> regionTargetGroups : allAccounts(targetGroups, targetGroupStore)) {
for (TargetGroup targetGroup : regionTargetGroups.values()) {
tgToLbs.computeIfAbsent(targetGroup.getTargetGroupArn(), k -> ConcurrentHashMap.newKeySet())
.addAll(targetGroup.getLoadBalancerArns());
}
}
}
/** Every account's region maps; the indexes are keyed by ARN, which already names the account. */
private static <V> Collection<Map<String, V>> allAccounts(Map<String, Map<String, V>> resources,
AccountAwareStorageBackend<Map<String, V>> store) {
return store == null ? resources.values() : store.scanAllAccounts();
}
/**
* Brings the data plane and health checks back up for state restored from disk. Invoked from
* {@code EmulatorLifecycle} once the bean is fully constructed, alongside the other services that
* restore persisted runtime after {@code storageFactory.loadAll()}.
* restore persisted runtime after {@code storageFactory.loadAll()}. Startup has no request, so each
* account that stored anything is restored as itself rather than as the default account.
*/
public void restorePersistedRuntime()
{
if (loadBalancerStore == null) {
restoreAccountRuntime();
return;
}
Set<String> accountIds = new TreeSet<>();
for (AccountAwareStorageBackend<?> store : List.of(loadBalancerStore, targetGroupStore, listenerStore, ruleStore)) {
store.scanAllAccountEntries(key -> true).forEach(entry -> accountIds.add(entry.accountId()));
}
for (String accountId : accountIds) {
RequestScopes.runAs(accountId, this::restoreAccountRuntime);
}
}
private void restoreAccountRuntime()
{
refreshCanonicalHostedZones();
if (healthChecker != null) {
@@ -0,0 +1,82 @@
package io.github.hectorvent.floci.services.elbv2;
import io.github.hectorvent.floci.testing.RealElbV2DataPlaneProfile;
import io.github.hectorvent.floci.testutil.FreePorts;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import static io.github.hectorvent.floci.testing.AlbFixtures.createListener;
import static io.github.hectorvent.floci.testing.AlbFixtures.createLoadBalancer;
import static io.github.hectorvent.floci.testing.AlbFixtures.createTargetGroup;
import static io.github.hectorvent.floci.testing.AlbFixtures.deleteListener;
import static io.github.hectorvent.floci.testing.AlbFixtures.deleteLoadBalancer;
import static io.github.hectorvent.floci.testing.AlbFixtures.deleteTargetGroup;
import static io.github.hectorvent.floci.testing.AlbFixtures.registerTarget;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** A listener port carries no credentials, so a load balancer outside the default account must still serve. */
@QuarkusTest
@TestProfile(RealElbV2DataPlaneProfile.class)
class ElbV2OtherAccountDataPlaneIntegrationTest {
private static final String ACCOUNT = "111122223333";
@Inject
Vertx vertx;
@Inject
ElbV2DataPlane dataPlane;
@Inject
ElbV2Service elbV2Service;
@Test
void listenerForwardsAndIsRestoredForItsOwnAccount() throws Exception {
HttpServer backend = vertx.createHttpServer()
.requestHandler(request -> request.response().end("other-account"))
.listen(0, "127.0.0.1")
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
int listenerPort = FreePorts.anyInterfacePort();
String loadBalancerArn = null;
String targetGroupArn = null;
String listenerArn = null;
try {
loadBalancerArn = createLoadBalancer(ACCOUNT, "other-account-lb");
targetGroupArn = createTargetGroup(ACCOUNT, "other-account-tg", "ip", backend.actualPort());
registerTarget(ACCOUNT, targetGroupArn, "127.0.0.1", backend.actualPort());
listenerArn = createListener(ACCOUNT, loadBalancerArn, targetGroupArn, listenerPort);
awaitForwarded(listenerPort);
assertTrue(dataPlane.removeListener(listenerArn, listenerPort, () -> true));
elbV2Service.initializeStorage();
elbV2Service.restorePersistedRuntime();
awaitForwarded(listenerPort);
} finally {
try {
deleteListener(ACCOUNT, listenerArn);
deleteTargetGroup(ACCOUNT, targetGroupArn);
deleteLoadBalancer(ACCOUNT, loadBalancerArn);
} finally {
backend.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
}
}
}
private static void awaitForwarded(int listenerPort) {
await().atMost(Duration.ofSeconds(5)).ignoreExceptions().untilAsserted(() -> given()
.baseUri("http://127.0.0.1").port(listenerPort)
.get("/").then().statusCode(200).body(equalTo("other-account")));
}
}
@@ -16,20 +16,23 @@ import static org.hamcrest.Matchers.equalTo;
*/
public final class AlbFixtures {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261101/us-east-1/elasticloadbalancing/aws4_request";
private static final String DEFAULT_ACCOUNT = "test";
private AlbFixtures() {
}
public static String createLoadBalancer(String name) {
return createLoadBalancer(DEFAULT_ACCOUNT, name);
}
public static String createLoadBalancer(String account, String name) {
return given()
.formParam("Action", "CreateLoadBalancer")
.formParam("Name", name)
.formParam("Type", "application")
.formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a"))
.formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b"))
.header("Authorization", AUTH)
.header("Authorization", auth(account))
.when()
.post("/")
.then()
@@ -42,7 +45,7 @@ public final class AlbFixtures {
return given()
.formParam("Action", "DescribeLoadBalancers")
.formParam("LoadBalancerArns.member.1", loadBalancerArn)
.header("Authorization", AUTH)
.header("Authorization", auth(DEFAULT_ACCOUNT))
.when()
.post("/")
.then()
@@ -53,6 +56,10 @@ public final class AlbFixtures {
/** An HTTP target group with health checks off, so a target serves as soon as it is registered. */
public static String createTargetGroup(String name, String targetType, int targetPort) {
return createTargetGroup(DEFAULT_ACCOUNT, name, targetType, targetPort);
}
public static String createTargetGroup(String account, String name, String targetType, int targetPort) {
return given()
.formParam("Action", "CreateTargetGroup")
.formParam("Name", name)
@@ -60,7 +67,7 @@ public final class AlbFixtures {
.formParam("Port", targetPort)
.formParam("TargetType", targetType)
.formParam("HealthCheckEnabled", "false")
.header("Authorization", AUTH)
.header("Authorization", auth(account))
.when()
.post("/")
.then()
@@ -70,12 +77,16 @@ public final class AlbFixtures {
}
public static void registerTarget(String targetGroupArn, String targetId, int targetPort) {
registerTarget(DEFAULT_ACCOUNT, targetGroupArn, targetId, targetPort);
}
public static void registerTarget(String account, String targetGroupArn, String targetId, int targetPort) {
given()
.formParam("Action", "RegisterTargets")
.formParam("TargetGroupArn", targetGroupArn)
.formParam("Targets.member.1.Id", targetId)
.formParam("Targets.member.1.Port", targetPort)
.header("Authorization", AUTH)
.header("Authorization", auth(account))
.when()
.post("/")
.then()
@@ -84,6 +95,10 @@ public final class AlbFixtures {
/** An HTTP listener on {@code port} that forwards every request to {@code targetGroupArn}. */
public static String createListener(String loadBalancerArn, String targetGroupArn, int port) {
return createListener(DEFAULT_ACCOUNT, loadBalancerArn, targetGroupArn, port);
}
public static String createListener(String account, String loadBalancerArn, String targetGroupArn, int port) {
return given()
.formParam("Action", "CreateListener")
.formParam("LoadBalancerArn", loadBalancerArn)
@@ -91,7 +106,7 @@ public final class AlbFixtures {
.formParam("Port", port)
.formParam("DefaultActions.member.1.Type", "forward")
.formParam("DefaultActions.member.1.TargetGroupArn", targetGroupArn)
.header("Authorization", AUTH)
.header("Authorization", auth(account))
.when()
.post("/")
.then()
@@ -106,7 +121,7 @@ public final class AlbFixtures {
.formParam("ListenerArn", listenerArn)
.formParam("DefaultActions.member.1.Type", "forward")
.formParam("DefaultActions.member.1.TargetGroupArn", targetGroupArn)
.header("Authorization", AUTH)
.header("Authorization", auth(DEFAULT_ACCOUNT))
.when()
.post("/")
.then()
@@ -114,15 +129,27 @@ public final class AlbFixtures {
}
public static void deleteListener(String listenerArn) {
delete("DeleteListener", "ListenerArn", listenerArn);
deleteListener(DEFAULT_ACCOUNT, listenerArn);
}
public static void deleteListener(String account, String listenerArn) {
delete(account, "DeleteListener", "ListenerArn", listenerArn);
}
public static void deleteTargetGroup(String targetGroupArn) {
delete("DeleteTargetGroup", "TargetGroupArn", targetGroupArn);
deleteTargetGroup(DEFAULT_ACCOUNT, targetGroupArn);
}
public static void deleteTargetGroup(String account, String targetGroupArn) {
delete(account, "DeleteTargetGroup", "TargetGroupArn", targetGroupArn);
}
public static void deleteLoadBalancer(String loadBalancerArn) {
delete("DeleteLoadBalancer", "LoadBalancerArn", loadBalancerArn);
deleteLoadBalancer(DEFAULT_ACCOUNT, loadBalancerArn);
}
public static void deleteLoadBalancer(String account, String loadBalancerArn) {
delete(account, "DeleteLoadBalancer", "LoadBalancerArn", loadBalancerArn);
}
/** Sends {@code text} on the socket and returns the next text message it receives. */
@@ -133,17 +160,21 @@ public final class AlbFixtures {
return reply.get(5, TimeUnit.SECONDS);
}
private static void delete(String action, String arnParameter, String arn) {
private static void delete(String account, String action, String arnParameter, String arn) {
if (arn == null) {
return;
}
given()
.formParam("Action", action)
.formParam(arnParameter, arn)
.header("Authorization", AUTH)
.header("Authorization", auth(account))
.when()
.post("/")
.then()
.statusCode(anyOf(equalTo(200), equalTo(204)));
}
private static String auth(String account) {
return "AWS4-HMAC-SHA256 Credential=" + account + "/20261101/us-east-1/elasticloadbalancing/aws4_request";
}
}