fix(elbv2): support explicit ALB zone-rule overrides (#8533)

* fix(elbv2): apply regional ALB zone defaults with overrides
* fix(elbv2): restore legacy subnet snapshots during stack rollback
* fix(elbv2): require two ALB zones for the AWS default
* fix(elbv2): simplify explicit ALB zone rules
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-16 07:42:42 -04:00
1 parent bd3431283b
commit 4a5d5fbb49
12 files changed
+369 -23

No files matched your search

@@ -0,0 +1,46 @@
package io.floci.aws.config;
import io.smallrye.config.ConfigMapping;
import io.smallrye.config.PropertiesConfigSource;
import io.smallrye.config.SmallRyeConfigBuilder;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class AlbZoneRuleConfigTest {
@ConfigMapping(prefix = "floci.services.elbv2")
interface Settings extends EmulatorConfig.ElbV2ServiceConfig {}
@Test
void defaultsToAwsWithNoRegionalOverrides() {
Settings settings = settings(Map.of());
assertEquals(EmulatorConfig.AlbZoneRule.AWS, settings.albZoneRule());
assertEquals(Map.of(), settings.albZoneRuleByRegion());
}
@Test
void mapsGlobalAndRegionalRulesIndependently() {
Settings settings = settings(Map.of(
"floci.services.elbv2.alb-zone-rule", "allow-single-zone",
"floci.services.elbv2.alb-zone-rule-by-region.ap-northeast-3", "aws",
"floci.services.elbv2.alb-zone-rule-by-region.us-east-1", "allow-single-zone"));
assertEquals(EmulatorConfig.AlbZoneRule.ALLOW_SINGLE_ZONE, settings.albZoneRule());
assertEquals(Map.of("ap-northeast-3", EmulatorConfig.AlbZoneRule.AWS,
"us-east-1", EmulatorConfig.AlbZoneRule.ALLOW_SINGLE_ZONE), settings.albZoneRuleByRegion());
}
@Test
void rejectsAnUnknownRule() {
assertThrows(RuntimeException.class,
() -> settings(Map.of("floci.services.elbv2.alb-zone-rule", "anything")));
}
private static Settings settings(Map<String, String> properties) {
return new SmallRyeConfigBuilder().addDefaultInterceptors().withMapping(Settings.class)
.withSources(new PropertiesConfigSource(properties, "zone-rule-test", 400))
.build().getConfigMapping(Settings.class);
}
}
@@ -3,6 +3,8 @@ package io.floci.aws.services.cloudformation;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.XmlParser;
import io.floci.aws.services.elbv2.ElbV2Service;
import io.floci.aws.services.elbv2.model.AvailabilityZone;
import io.floci.aws.services.elbv2.model.LoadBalancer;
import io.floci.aws.testing.CfnStackWaits;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
@@ -26,7 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.reset;
/**
@@ -307,15 +309,40 @@ class CloudFormationElbV2SubnetUpdateIntegrationTest {
}
}
@Test
void failedStackUpdateRestoresLegacyDuplicateZoneSubnetSnapshot() {
String stack = "alb-legacy-rollback-" + Long.toString(System.nanoTime(), 36);
try {
Map<String, String> created = createStack(stack, branchTemplate(""), "first");
LoadBalancer legacy = elbService.describeLoadBalancers("us-east-1", List.of(created.get("Alb")),
null, null, null).getFirst();
AvailabilityZone legacyZone = new AvailabilityZone();
legacyZone.setSubnetId(created.get("SubnetC"));
legacyZone.setZoneName("us-east-1a");
// Seed the persisted shape that older versions accepted, without relaxing a new request.
legacy.getAvailabilityZones().add(legacyZone);
Set<String> prior = Set.copyOf(loadBalancerSubnets(created.get("Alb")));
request(CFN_AUTH, "UpdateStack", "StackName", stack, "TemplateBody",
branchTemplate(failingSecret(stack, "Alb")),
"Parameters.member.1.ParameterKey", "Placement",
"Parameters.member.1.ParameterValue", "second").statusCode(200);
CfnStackWaits.awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE");
assertEquals(prior, Set.copyOf(loadBalancerSubnets(created.get("Alb"))));
} finally {
deleteStack(stack);
}
}
/**
* The update's own move onto the new subnets goes through, the first move back fails as if its
* subnet had been deleted meanwhile, and any later call goes through again.
*/
private void failTheFirstMoveBack() {
doCallRealMethod()
.doThrow(new AwsException("SubnetNotFound", "The subnet ID was not found", 400))
doThrow(new AwsException("SubnetNotFound", "The subnet ID was not found", 400))
.doCallRealMethod()
.when(elbService).setSubnets(anyString(), anyString(), anyList());
.when(elbService).restoreSubnetSnapshot(anyString(), anyString(), anyList());
}
/** Moves the load balancer onto SubnetA and an added SubnetC in an update a later resource fails. */
@@ -531,7 +531,7 @@ class ElbV2CfnProvisionerTest {
assertEquals(LB_ARN, lb.getPhysicalId());
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
verify(elb).restoreSubnetSnapshot(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
}
/** The subnets a load balancer is on, as its hidden uses attributes record them. */
@@ -597,7 +597,7 @@ class ElbV2CfnProvisionerTest {
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb).setSubnets(REGION, LB_ARN, List.of());
verify(elb).restoreSubnetSnapshot(REGION, LB_ARN, List.of());
assertEquals(Set.of(), usedSubnets(lb));
}
@@ -620,7 +620,7 @@ class ElbV2CfnProvisionerTest {
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-3"));
verify(elb, never()).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
verify(elb, never()).restoreSubnetSnapshot(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
}
@Test
@@ -628,12 +628,12 @@ class ElbV2CfnProvisionerTest {
StackResource lb = keptLoadBalancerUpdatedTo(loadBalancerOn("web", "subnet-1", "subnet-2"),
"subnet-1", "subnet-3");
doThrow(new AwsException("SubnetNotFound", "The subnet ID 'subnet-2' does not exist", 400)).doNothing()
.when(elb).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
.when(elb).restoreSubnetSnapshot(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
AwsException failure = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(lb));
assertEquals("SubnetNotFound", failure.getErrorCode());
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb, times(2)).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
verify(elb, times(2)).restoreSubnetSnapshot(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
}
@Test
@@ -644,7 +644,7 @@ class ElbV2CfnProvisionerTest {
provisioner.clearUpdate(lb);
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb, never()).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
verify(elb, never()).restoreSubnetSnapshot(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
}
@Test
@@ -657,7 +657,7 @@ class ElbV2CfnProvisionerTest {
provisioner.provision(lb, props, ctx(LB_ARN));
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb, never()).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
verify(elb, never()).restoreSubnetSnapshot(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
}
@Test
@@ -0,0 +1,52 @@
package io.floci.aws.services.elbv2;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.testing.AwsTestClients;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client;
import software.amazon.awssdk.services.elasticloadbalancingv2.model.ElasticLoadBalancingV2Exception;
import software.amazon.awssdk.services.elasticloadbalancingv2.model.LoadBalancerNotFoundException;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
class ElbV2RegionalZoneIntegrationTest {
@Test
void awsDefaultRequiresTwoZonesInBothRegionsForCreateAndSetSubnets() {
try (ElasticLoadBalancingV2Client osaka = AwsTestClients.create(ElasticLoadBalancingV2Client.builder(),
"000000000000", Region.AP_NORTHEAST_3);
ElasticLoadBalancingV2Client virginia = AwsTestClients.create(ElasticLoadBalancingV2Client.builder(),
"000000000000", Region.US_EAST_1)) {
String name = "regional-" + UUID.randomUUID().toString().substring(0, 12);
ElasticLoadBalancingV2Exception rejected = assertThrows(ElasticLoadBalancingV2Exception.class,
() -> virginia.createLoadBalancer(r -> r.name(name).scheme("internal")
.type("application").subnets(Ec2Service.defaultSubnetId("us-east-1", "a"))));
assertEquals("ValidationError", rejected.awsErrorDetails().errorCode());
ElasticLoadBalancingV2Exception osakaRejected = assertThrows(ElasticLoadBalancingV2Exception.class,
() -> osaka.createLoadBalancer(r -> r.name(name).scheme("internal").type("application")
.subnets(Ec2Service.defaultSubnetId("ap-northeast-3", "a"))));
assertEquals("ValidationError", osakaRejected.awsErrorDetails().errorCode());
String arn = osaka.createLoadBalancer(r -> r.name(name).scheme("internal").type("application")
.subnets(Ec2Service.defaultSubnetId("ap-northeast-3", "a"),
Ec2Service.defaultSubnetId("ap-northeast-3", "b")))
.loadBalancers().getFirst().loadBalancerArn();
try {
ElasticLoadBalancingV2Exception updateRejected = assertThrows(
ElasticLoadBalancingV2Exception.class, () -> osaka.setSubnets(r -> r.loadBalancerArn(arn)
.subnets(Ec2Service.defaultSubnetId("ap-northeast-3", "b"))));
assertEquals("ValidationError", updateRejected.awsErrorDetails().errorCode());
assertEquals(2, osaka.describeLoadBalancers(r -> r.loadBalancerArns(arn))
.loadBalancers().getFirst().availabilityZones().size());
} finally {
osaka.deleteLoadBalancer(r -> r.loadBalancerArn(arn));
assertThrows(LoadBalancerNotFoundException.class,
() -> osaka.describeLoadBalancers(r -> r.loadBalancerArns(arn)));
}
}
}
}
@@ -10,6 +10,9 @@ import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.PersistentStorage;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.cloudformation.provisioners.CfnRollback;
import io.floci.aws.services.cloudformation.provisioners.ElbV2CfnProvisioner;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.Subnet;
import io.floci.aws.services.elbv2.model.Action;
@@ -111,6 +114,133 @@ class ElbV2ServiceTest {
stubAlbSubnets(ec2Service);
}
@Test
void rollbackRestoresLegacyDuplicateZoneSubnetsWhileNewRequestsRemainStrict() {
LoadBalancer lb = service.createLoadBalancer(REGION, "legacy-subnets", "internal", "application", "ipv4",
ALB_SUBNETS, List.of(), Map.of());
List<String> legacy = List.of("subnet-a", "subnet-b", "subnet-c");
when(ec2Service.describeSubnets(REGION, legacy, Map.of())).thenReturn(List.of(
subnet("subnet-a", REGION + "a"), subnet("subnet-b", REGION + "b"),
subnet("subnet-c", REGION + "a")));
assertThrows(AwsException.class, () -> service.setSubnetsFromRequest(REGION,
lb.getLoadBalancerArn(), legacy));
StackResource resource = subnetRollbackResource(lb, legacy);
assertTrue(new ElbV2CfnProvisioner(service).rollbackUpdate(resource));
assertEquals(legacy, lb.getAvailabilityZones().stream().map(AvailabilityZone::getSubnetId).toList());
assertFalse(resource.getAttributes().containsKey(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR));
assertThrows(AwsException.class, () -> service.setSubnetsFromRequest(REGION,
lb.getLoadBalancerArn(), legacy));
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void rollbackRetainsSnapshotAndStateWhenPriorSubnetsAreMissingOrInAnotherVpc(boolean foreignVpc) {
LoadBalancer lb = service.createLoadBalancer(REGION, "rollback-invalid-subnets", "internal", "application",
"ipv4", ALB_SUBNETS, List.of(), Map.of());
List<String> prior = List.of("subnet-a", "subnet-b", "subnet-c");
Subnet other = subnet("subnet-c", REGION + "a");
other.setVpcId("vpc-other");
when(ec2Service.describeSubnets(REGION, prior, Map.of())).thenReturn(foreignVpc
? List.of(subnet("subnet-a", REGION + "a"), subnet("subnet-b", REGION + "b"), other)
: List.of(subnet("subnet-a", REGION + "a"), subnet("subnet-b", REGION + "b")));
StackResource resource = subnetRollbackResource(lb, prior);
AwsException failure = assertThrows(AwsException.class,
() -> new ElbV2CfnProvisioner(service).rollbackUpdate(resource));
assertEquals(foreignVpc ? "InvalidConfigurationRequest" : "SubnetNotFound", failure.getErrorCode());
assertEquals(ALB_SUBNETS, lb.getAvailabilityZones().stream().map(AvailabilityZone::getSubnetId).toList());
assertEquals(String.join(",", prior), resource.getAttributes()
.get(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR));
assertEquals("vpc-a", lb.getVpcId());
}
private static StackResource subnetRollbackResource(LoadBalancer lb, List<String> subnets) {
StackResource resource = new StackResource();
resource.setResourceType("AWS::ElasticLoadBalancingV2::LoadBalancer");
resource.setPhysicalId(lb.getLoadBalancerArn());
resource.getAttributes().put(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR,
String.join(",", subnets));
return resource;
}
@ParameterizedTest
@CsvSource({
"ap-northeast-3,AWS,none,false",
"us-east-1,AWS,none,false",
"us-east-1,ALLOW_SINGLE_ZONE,none,true",
"us-east-1,AWS,ALLOW_SINGLE_ZONE,true",
"ap-northeast-3,ALLOW_SINGLE_ZONE,AWS,false",
"us-east-1,ALLOW_SINGLE_ZONE,AWS,false"
})
void albZonePolicyAppliesToCreateAndSetSubnets(String region, EmulatorConfig.AlbZoneRule global,
String regional, boolean allowed) {
Map<String, EmulatorConfig.AlbZoneRule> overrides = "none".equals(regional) ? Map.of()
: Map.of(region, EmulatorConfig.AlbZoneRule.valueOf(regional));
service.config = albZoneConfig(global, overrides);
service.regionResolver = new RegionResolver(region, "000000000000");
lenient().when(ec2Service.describeSubnets(eq(region), anyList(), eq(Map.of())))
.thenAnswer(invocation -> invocation.<List<String>>getArgument(1).stream()
.map(id -> subnet(id, region + ("subnet-a".equals(id) ? "a" : "b"))).toList());
lenient().when(ec2Service.requireSubnet(eq(region), anyString()))
.thenAnswer(invocation -> subnet(invocation.getArgument(1), region + "a"));
LoadBalancer twoZones = service.createLoadBalancer(region, "two-zones", "internal", "application",
"ipv4", ALB_SUBNETS, List.of(), Map.of());
if (allowed) {
LoadBalancer single = service.createLoadBalancer(region, "one-zone", "internal", "application",
"ipv4", List.of("subnet-a"), List.of(), Map.of());
assertEquals(1, single.getAvailabilityZones().size());
service.setSubnetsFromRequest(region, twoZones.getLoadBalancerArn(), List.of("subnet-a"));
assertEquals(1, twoZones.getAvailabilityZones().size());
} else {
assertThrows(AwsException.class, () -> service.createLoadBalancer(region, "one-zone", "internal",
"application", "ipv4", List.of("subnet-a"), List.of(), Map.of()));
assertThrows(AwsException.class, () -> service.setSubnetsFromRequest(region,
twoZones.getLoadBalancerArn(), List.of("subnet-a")));
assertEquals(2, twoZones.getAvailabilityZones().size());
}
assertThrows(AwsException.class, () -> service.createLoadBalancer(region, "no-zone", "internal",
"application", "ipv4", List.of(), List.of(), Map.of()));
assertThrows(AwsException.class, () -> service.setSubnetsFromRequest(region,
twoZones.getLoadBalancerArn(), List.of()));
}
@Test
void singleZonePolicyStillRejectsMultipleSubnetsInTheSameZone() {
String region = "ap-northeast-3";
service.config = albZoneConfig(EmulatorConfig.AlbZoneRule.ALLOW_SINGLE_ZONE, Map.of());
Subnet first = subnet("subnet-a", region + "a");
Subnet second = subnet("subnet-b", region + "a");
when(ec2Service.describeSubnets(region, ALB_SUBNETS, Map.of())).thenReturn(List.of(first, second));
when(ec2Service.describeSubnets(region, List.of("subnet-a"), Map.of())).thenReturn(List.of(first));
AwsException rejected = assertThrows(AwsException.class, () -> service.createLoadBalancer(region,
"same-zone", "internal", "application", "ipv4", ALB_SUBNETS, List.of(), Map.of()));
assertEquals("InvalidConfigurationRequest", rejected.getErrorCode());
assertEquals("A load balancer cannot be attached to multiple subnets in the same Availability Zone",
rejected.getMessage());
LoadBalancer single = service.createLoadBalancer(region, "single-zone", "internal", "application",
"ipv4", List.of("subnet-a"), List.of(), Map.of());
assertThrows(AwsException.class,
() -> service.setSubnetsFromRequest(region, single.getLoadBalancerArn(), ALB_SUBNETS));
assertEquals(List.of("subnet-a"), single.getAvailabilityZones().stream()
.map(AvailabilityZone::getSubnetId).toList());
}
private static EmulatorConfig albZoneConfig(EmulatorConfig.AlbZoneRule global,
Map<String, EmulatorConfig.AlbZoneRule> overrides) {
EmulatorConfig settings = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.ElbV2ServiceConfig elbv2 = mock(EmulatorConfig.ElbV2ServiceConfig.class);
when(settings.services()).thenReturn(services);
when(services.elbv2()).thenReturn(elbv2);
when(elbv2.albZoneRule()).thenReturn(global);
when(elbv2.albZoneRuleByRegion()).thenReturn(overrides);
lenient().when(settings.hostname()).thenReturn(Optional.empty());
return settings;
}
@Test
void describeListenersRequiresEveryExplicitArn() {
String lb = service.createLoadBalancer(REGION, "listener-lookup", "internal", "application", "ipv4",
@@ -995,6 +1125,9 @@ class ElbV2ServiceTest {
void createLoadBalancerUsesConfiguredHostnameForDnsSuffix() {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.hostname()).thenReturn(Optional.of("floci"));
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
when(config.services()).thenReturn(services);
when(services.elbv2()).thenReturn(mock(EmulatorConfig.ElbV2ServiceConfig.class));
service.config = config;
String dnsName = service.createLoadBalancer(