Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(elbv2): answer SetSubnets with one ALB subnet with ValidationError (#6116)

Jackson Priceab0737798d23
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ElbV2Test.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ElbV2Test.java
index 12472d53f8..9311c8031d 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ElbV2Test.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ElbV2Test.java
@@ -284,6 +284,30 @@ class ElbV2Test {
.isInstanceOf(LoadBalancerNotFoundException.class);
}
+ @Test
+ @Order(9)
+ @DisplayName("SetSubnets - an Application Load Balancer moved onto one subnet is a ValidationError")
+ void setApplicationLoadBalancerOntoOneSubnet() {
+ List<String> subnets = TestFixtures.defaultVpcSubnets();
+ String arn = elb.createLoadBalancer(r -> r.name(TestFixtures.uniqueName("sdk-set-one"))
+ .type(LoadBalancerTypeEnum.APPLICATION).subnets(subnets))
+ .loadBalancers().get(0).loadBalancerArn();
+ try {
+ assertThatThrownBy(() -> elb.setSubnets(r -> r.loadBalancerArn(arn).subnets(subnets.get(0))))
+ .isInstanceOfSatisfying(ElasticLoadBalancingV2Exception.class, e -> {
+ assertThat(e.statusCode()).isEqualTo(400);
+ assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationError");
+ assertThat(e.awsErrorDetails().errorMessage())
+ .isEqualTo("At least two subnets in two different Availability Zones must be specified");
+ });
+ assertThat(elb.describeLoadBalancers(r -> r.loadBalancerArns(arn)).loadBalancers().get(0).availabilityZones())
+ .extracting(zone -> zone.subnetId())
+ .containsExactlyInAnyOrderElementsOf(subnets);
+ } finally {
+ elb.deleteLoadBalancer(r -> r.loadBalancerArn(arn));
+ }
+ }
+
// ─── Target Groups ───────────────────────────────────────────────────────
@Test
diff --git a/docs/services/elb.md b/docs/services/elb.md
index ea3ad62b96..34b4c05f5b 100644
--- a/docs/services/elb.md
+++ b/docs/services/elb.md
@@ -93,8 +93,8 @@ HTTPS listeners require a default certificate. Supply one when creating a listen
- Load balancer, target group, listener, rule, and tag state is persisted through Floci storage and rebuilt on service startup.
- Load balancers are created in `active` state.
- `CreateLoadBalancer` takes `Subnets` or `SubnetMappings` for every load balancer type, and both together are refused with `ValidationError`. An Application Load Balancer takes at least two: with one or none it returns `ValidationError` `At least two subnets in two different Availability Zones must be specified` and creates nothing. The count comes before any subnet is looked up, as on AWS, so one subnet that does not exist gets that error too. A Network or Gateway Load Balancer with neither returns `ValidationError` `At least one subnet must be specified`. CloudFormation refuses such an `AWS::ElasticLoadBalancingV2::LoadBalancer` the same way when it creates or replaces the balancer; an update that keeps the balancer and names no subnets leaves it on its subnets.
+- `SetSubnets`, like `CreateLoadBalancer`, takes `Subnets` or `SubnetMappings`, and both together are refused with `ValidationError`. With neither it returns the same `ValidationError` as `CreateLoadBalancer` for the balancer's type, `At least two subnets in two different Availability Zones must be specified` for an Application Load Balancer and `At least one subnet must be specified` for a Network or Gateway Load Balancer, and leaves the balancer on its subnets. A `SetSubnets` that names subnets is counted as `CreateLoadBalancer` counts them, following the two-zone rule its API reference states: one subnet for an Application Load Balancer, in `Subnets` or `SubnetMappings`, returns `ValidationError` `At least two subnets in two different Availability Zones must be specified` before any subnet is looked up, and leaves the balancer on its subnets. AWS does not document the error for this case, so Floci gives `CreateLoadBalancer`'s error, in the same order. A CloudFormation update that keeps an Application Load Balancer and names one subnet fails with that error and rolls back. A Network Load Balancer can be set onto one subnet. The `SetSubnets` API reference requires a Gateway Load Balancer's `Subnets` to include every subnet it is already on; Floci does not enforce that.
- EC2 refuses deletion of subnets and VPCs still referenced by load balancers with `DependencyViolation`. These account- and region-scoped dependencies follow persisted load balancer state; changing subnets or deleting the load balancer releases its old references. A CloudFormation update that names other subnets in `Subnets` or `SubnetMappings` moves the load balancer the way `SetSubnets` does, and a rolled-back update moves it back. An independent target group does not prevent subnet or VPC deletion.
-- `SetSubnets`, like `CreateLoadBalancer`, takes `Subnets` or `SubnetMappings`, and both together are refused with `ValidationError`. With neither it returns the same `ValidationError` as `CreateLoadBalancer` for the balancer's type, `At least two subnets in two different Availability Zones must be specified` for an Application Load Balancer and `At least one subnet must be specified` for a Network or Gateway Load Balancer, and leaves the balancer on its subnets.
- HTTP listener sockets are preserved when listener actions change and are restarted only when socket-level settings such as port change.
- Instance targets are resolved through EC2 instance private addresses so local load balancer traffic can reach containers.
- Target health starts in `initial` state with reason `Elb.RegistrationInProgress` and is updated by Floci's health checker when monitoring is active.
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 6974c20097..72df469e49 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
@@ -284,12 +284,17 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
/**
* Every load balancer type takes {@code Subnets} or {@code SubnetMappings}, and an Application Load
- * Balancer takes at least two, so a request with fewer is refused before anything is created, with
- * the message AWS gives an Application or a Network Load Balancer. A Gateway Load Balancer, which
- * takes subnets the way a Network Load Balancer does, gets the Network one. AWS counts before it
- * looks a subnet up, so one subnet that does not exist gets this error too, not SubnetNotFound.
- * This runs after the duplicate-name check, because a CloudFormation stack update finds the
- * balancer it keeps through DuplicateLoadBalancerName, whatever subnets its template names.
+ * Balancer takes at least two, so a CreateLoadBalancer with fewer is refused before anything is
+ * created, with the message AWS gives an Application or a Network Load Balancer. A Gateway Load
+ * Balancer, which takes subnets the way a Network Load Balancer does, gets the Network one. AWS
+ * counts before it looks a subnet up, so one subnet that does not exist gets this error too, not
+ * SubnetNotFound. On create this runs after the duplicate-name check, because a CloudFormation stack
+ * update finds the balancer it keeps through DuplicateLoadBalancerName, whatever subnets its
+ * template names. SetSubnets takes the same subnets, so {@link #setSubnetsFromRequest} runs this on
+ * a SetSubnets that names none, and {@link #setSubnets} on a list that names some, once it has the
+ * balancer's type; whether the subnets span two Availability Zones is checked after they are looked
+ * up. No public report shows what AWS answers a SetSubnets with one subnet, so it gets the create
+ * message and order.
*/
private static void requireSubnets(String lbType, List<String> subnets) {
int count = subnets == null ? 0 : subnets.size();
@@ -435,6 +440,10 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
public void setSubnets(String region, String arn, List<String> subnets) {
ec2Service.runWithSubnetReferencesHeld(region, () -> {
LoadBalancer lb = requireLoadBalancer(region, arn);
+ // Counted as on create, before any subnet is looked up; an empty list is taken, as above.
+ if (subnets != null && !subnets.isEmpty()) {
+ requireSubnets(lb.getType(), subnets);
+ }
String vpcId = resolveSubnetVpcId(region, lb.getType(), subnets);
if (vpcId != null && lb.getVpcId() != null && !lb.getVpcId().equals(vpcId)) {
throw new AwsException("InvalidConfigurationRequest",
@@ -1423,11 +1432,6 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
Map<String, Subnet> subnetsById = resolveSubnetsById(region, subnetIds);
if ("application".equals(lbType)) {
- if (subnetIds.size() < 2) {
- throw new AwsException("InvalidConfigurationRequest",
- "Application Load Balancers must be attached to subnets in at least two Availability Zones.", 400);
- }
-
long distinctAvailabilityZones = subnetIds.stream()
.map(subnetsById::get)
.map(Subnet::getAvailabilityZone)
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2SubnetUpdateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2SubnetUpdateIntegrationTest.java
index a217f69c95..7a83ff83f5 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2SubnetUpdateIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2SubnetUpdateIntegrationTest.java
@@ -219,6 +219,34 @@ class CloudFormationElbV2SubnetUpdateIntegrationTest {
}
}
+ /**
+ * An update that keeps the Application Load Balancer and names one subnet moves it with SetSubnets,
+ * so the update fails with the ValidationError SetSubnets gives an Application Load Balancer on one
+ * subnet, and the balancer stays on both of its subnets.
+ */
+ @Test
+ void anUpdateThatMovesTheApplicationLoadBalancerOntoOneSubnetRollsBack() {
+ String stack = "alb-one-subnet-update-" + Long.toString(System.nanoTime(), 36);
+ try {
+ Map<String, String> created = createStack(stack,
+ template(CIDR_B, false, List.of("SubnetA", "SubnetB"), ""));
+
+ Map<String, String> rolledBack = updateStack(stack,
+ template(CIDR_B, false, List.of("SubnetA"), ""), "UPDATE_ROLLBACK_COMPLETE");
+
+ String events = request(CFN_AUTH, "DescribeStackEvents", "StackName", stack).statusCode(200)
+ .extract().asString();
+ List<String> reasons = XmlParser.extractAll(events, "ResourceStatusReason");
+ assertTrue(reasons.stream().anyMatch(
+ r -> r.contains("At least two subnets in two different Availability Zones must be specified")),
+ String.join(" | ", reasons));
+ assertEquals(Set.of(created.get("SubnetA"), created.get("SubnetB")),
+ Set.copyOf(loadBalancerSubnets(rolledBack.get("Alb"))));
+ } finally {
+ deleteStack(stack);
+ }
+ }
+
/**
* The first rollback's move back fails, which leaves the load balancer on the subnet the update
* added, so that subnet cannot be deleted either and the stack ends UPDATE_ROLLBACK_FAILED with
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisionerTest.java
index 51ab7d36a4..7516bdd8ee 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisionerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisionerTest.java
@@ -488,8 +488,8 @@ class ElbV2CfnProvisionerTest {
assertEquals(Set.of("subnet-1", "subnet-2"), usedSubnets(created));
StackResource moved = keptLoadBalancerUpdatedTo(loadBalancerOn("web", "subnet-1", "subnet-2"),
- "subnet-3");
- assertEquals(Set.of("subnet-3"), usedSubnets(moved));
+ "subnet-3", "subnet-4");
+ assertEquals(Set.of("subnet-3", "subnet-4"), usedSubnets(moved));
assertTrue(provisioner.rollbackUpdate(moved));
assertEquals(Set.of("subnet-1", "subnet-2"), usedSubnets(moved));
@@ -672,18 +672,22 @@ class ElbV2CfnProvisionerTest {
assertEquals("SubnetNotFound", e.getErrorCode());
}
- /** On an update of a kept load balancer, a blank {@code SubnetId} reaches SetSubnets for ELBv2 to refuse. */
+ /**
+ * On an update of a kept Network Load Balancer, a blank {@code SubnetId} reaches SetSubnets for ELBv2
+ * to refuse as an unknown subnet. An Application Load Balancer would get the subnet count error first.
+ */
@Test
void anUpdateWithABlankSubnetIdIsRefusedByTheMoveAndKeepsNoSnapshot() {
- when(elb.createLoadBalancer(eq(REGION), eq("web"), isNull(), isNull(), isNull(), anyList(), anyList(), any()))
- .thenThrow(new AwsException("DuplicateLoadBalancerName", "exists", 400));
- when(elb.describeLoadBalancers(REGION, null, List.of("web"), null, null))
- .thenReturn(List.of(loadBalancerOn("web", "subnet-1", "subnet-2")));
+ when(elb.createLoadBalancer(eq(REGION), eq("web"), isNull(), eq("network"), isNull(), anyList(), anyList(),
+ any())).thenThrow(new AwsException("DuplicateLoadBalancerName", "exists", 400));
+ LoadBalancer kept = loadBalancerOn("web", "subnet-1", "subnet-2");
+ kept.setType("network");
+ when(elb.describeLoadBalancers(REGION, null, List.of("web"), null, null)).thenReturn(List.of(kept));
doThrow(new AwsException("SubnetNotFound", "The subnet ID ' ' does not exist", 400))
.when(elb).setSubnets(REGION, LB_ARN, List.of(" "));
- ObjectNode props = mapper.createObjectNode().put("Name", "web");
+ ObjectNode props = mapper.createObjectNode().put("Name", "web").put("Type", "network");
props.putArray("SubnetMappings").addObject().put("SubnetId", " ");
- StackResource lb = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");
+ StackResource lb = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Nlb");
lb.getAttributes().put("LoadBalancerName", "web");
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(lb, props, ctx(LB_ARN)));
diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2IntegrationTest.java
index b69a98dcba..4aca9f5f53 100644
--- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2IntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2IntegrationTest.java
@@ -1363,10 +1363,12 @@ class ElbV2IntegrationTest {
.extract()
.path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn");
+ // Two subnets, so the Application Load Balancer's subnet count passes and the lookup is reached.
given()
.formParam("Action", "SetSubnets")
.formParam("LoadBalancerArn", setSubnetsLbArn)
- .formParam("Subnets.member.1", "subnet-does-not-exist")
+ .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a"))
+ .formParam("Subnets.member.2", "subnet-does-not-exist")
.header("Authorization", AUTH)
.when()
.post("/")
@@ -1375,6 +1377,132 @@ class ElbV2IntegrationTest {
.body("ErrorResponse.Error.Code", equalTo("SubnetNotFound"));
}
+ /**
+ * SetSubnets counts the subnets the way CreateLoadBalancer does, so one subnet for an Application
+ * Load Balancer, in Subnets or in SubnetMappings, is the ValidationError CreateLoadBalancer gives,
+ * and the balancer stays on its subnets and in its VPC. The count comes before the subnet is
+ * looked up, so one that does not exist gets it too.
+ */
+ @ParameterizedTest
+ @CsvSource(delimiter = '|', nullValues = "NONE", value = {
+ "set-one-subnet|Subnets.member.1|a",
+ "set-one-mapping|SubnetMappings.member.1.SubnetId|a",
+ "set-one-missing-subnet|Subnets.member.1|NONE"
+ })
+ @Order(68)
+ void setSubnetsOntoOneSubnetIsAValidationErrorForAnApplicationLoadBalancer(String name, String parameter,
+ String zone) {
+ String subnetA = Ec2Service.defaultSubnetId("us-east-1", "a");
+ String subnetB = Ec2Service.defaultSubnetId("us-east-1", "b");
+ String subnet = zone == null ? "subnet-does-not-exist" : Ec2Service.defaultSubnetId("us-east-1", zone);
+ String arn = given()
+ .formParam("Action", "CreateLoadBalancer")
+ .formParam("Name", name)
+ .formParam("Type", "application")
+ .formParam("Subnets.member.1", subnetA)
+ .formParam("Subnets.member.2", subnetB)
+ .header("Authorization", AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn");
+
+ given()
+ .formParam("Action", "SetSubnets")
+ .formParam("LoadBalancerArn", arn)
+ .formParam(parameter, subnet)
+ .header("Authorization", AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))
+ .body("ErrorResponse.Error.Message",
+ equalTo("At least two subnets in two different Availability Zones must be specified"));
+
+ given()
+ .formParam("Action", "DescribeLoadBalancers")
+ .formParam("LoadBalancerArns.member.1", arn)
+ .header("Authorization", AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.AvailabilityZones.member.SubnetId",
+ contains(subnetA, subnetB))
+ .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.VpcId",
+ equalTo(Ec2Service.defaultVpcId("us-east-1")));
+
+ given()
+ .formParam("Action", "DeleteLoadBalancer")
+ .formParam("LoadBalancerArn", arn)
+ .header("Authorization", AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ /**
+ * A Network or Gateway Load Balancer can be in a single Availability Zone, so SetSubnets onto one
+ * subnet is taken: the Network Load Balancer leaves one of its two subnets, and the Gateway Load
+ * Balancer, which AWS lets add subnets but not drop them, is set onto the one it is on.
+ */
+ @ParameterizedTest
+ @CsvSource({"network,true", "gateway,false"})
+ @Order(69)
+ void setSubnetsOntoOneSubnetIsAllowedForNetworkAndGatewayLoadBalancers(String type, boolean onTwoSubnets) {
+ String subnetA = Ec2Service.defaultSubnetId("us-east-1", "a");
+ RequestSpecification create = given()
+ .formParam("Action", "CreateLoadBalancer")
+ .formParam("Name", "set-one-subnet-" + type)
+ .formParam("Type", type)
+ .formParam("Subnets.member.1", subnetA)
+ .header("Authorization", AUTH);
+ if (onTwoSubnets) {
+ create.formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b"));
+ }
+ String arn = create
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn");
+
+ given()
+ .formParam("Action", "SetSubnets")
+ .formParam("LoadBalancerArn", arn)
+ .formParam("Subnets.member.1", subnetA)
+ .header("Authorization", AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .formParam("Action", "DescribeLoadBalancers")
+ .formParam("LoadBalancerArns.member.1", arn)
+ .header("Authorization", AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.AvailabilityZones.member.SubnetId",
+ equalTo(subnetA));
+
+ given()
+ .formParam("Action", "DeleteLoadBalancer")
+ .formParam("LoadBalancerArn", arn)
+ .header("Authorization", AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
/**
* Every type takes Subnets or SubnetMappings, so CreateLoadBalancer with neither is a
* ValidationError and no load balancer is created. The messages are the ones AWS gives an
diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java
index 45209d2360..5f8c7ca7bf 100644
--- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java
@@ -214,7 +214,10 @@ class ElbV2ServiceTest {
verify(ec2Service, never()).describeSubnets(anyString(), anyList(), any());
}
- /** The message depends on the balancer's type, so a balancer that does not exist is reported first. */
+ /**
+ * Through the SetSubnets action with neither form: the message depends on the balancer's type, so a
+ * balancer that does not exist is reported first.
+ */
@Test
void setSubnetsForAMissingBalancerReportsItBeforeMissingSubnets() {
MultivaluedHashMap<String, String> params = new MultivaluedHashMap<>();
@@ -228,22 +231,6 @@ class ElbV2ServiceTest {
assertTrue(xml.contains("<Code>LoadBalancerNotFound</Code>"), xml);
}
- /**
- * Only the SetSubnets action refuses an empty list. A CloudFormation rollback moves a kept
- * balancer back onto the subnets it had before the update, and for a balancer an earlier Floci
- * version saved without subnets that is none.
- */
- @Test
- void aMoveBackOntoNoSubnetsIsStillTaken() {
- LoadBalancer lb = service.createLoadBalancer(REGION, "moved-back", "internal", "application", "ipv4",
- ALB_SUBNETS, List.of(), Map.of());
-
- service.setSubnets(REGION, lb.getLoadBalancerArn(), List.of());
-
- assertTrue(service.describeLoadBalancers(REGION, List.of(lb.getLoadBalancerArn()), null, null, null)
- .getFirst().getAvailabilityZones().isEmpty());
- }
-
/**
* A taken name is reported before missing subnets: a CloudFormation stack update finds the
* balancer it keeps through DuplicateLoadBalancerName, whatever subnets its template names.
@@ -1021,4 +1008,84 @@ class ElbV2ServiceTest {
assertEquals(List.of("subnet-c", "subnet-d"),
moved.getAvailabilityZones().stream().map(AvailabilityZone::getSubnetId).toList());
}
+
+ /**
+ * SetSubnets counts the subnets the way CreateLoadBalancer does: one subnet for an Application Load
+ * Balancer gets the refusal CreateLoadBalancer gives it, before the subnet is looked up, and the
+ * balancer keeps its zones and its VPC.
+ */
+ @Test
+ void anApplicationLoadBalancerMovedOntoOneSubnetIsRefusedBeforeTheSubnetIsLookedUp() {
+ LoadBalancer lb = service.createLoadBalancer(REGION, "set-one-subnet", "internal", "application", "ipv4",
+ ALB_SUBNETS, List.of(), Map.of());
+ // Stubbed so that a lookup before the count would reach the zone check, not a SubnetNotFound from the mock.
+ lenient().when(ec2Service.describeSubnets(REGION, List.of("subnet-a"), Map.of()))
+ .thenReturn(List.of(subnet("subnet-a", REGION + "a")));
+ clearInvocations(ec2Service);
+
+ AwsException refusal = assertThrows(AwsException.class,
+ () -> service.setSubnets(REGION, lb.getLoadBalancerArn(), List.of("subnet-a")));
+
+ assertEquals("ValidationError", refusal.getErrorCode());
+ assertEquals("At least two subnets in two different Availability Zones must be specified",
+ refusal.getMessage());
+ assertEquals(400, refusal.getHttpStatus());
+ LoadBalancer kept = service.describeLoadBalancers(REGION, List.of(lb.getLoadBalancerArn()), null, null,
+ null).getFirst();
+ assertEquals(ALB_SUBNETS, kept.getAvailabilityZones().stream().map(AvailabilityZone::getSubnetId).toList());
+ assertEquals("vpc-a", kept.getVpcId());
+ verify(ec2Service, never()).describeSubnets(anyString(), anyList(), any());
+ }
+
+ /**
+ * A Network or Gateway Load Balancer can be in a single Availability Zone, so SetSubnets onto one
+ * subnet is taken: the Network Load Balancer leaves one of its two subnets, and the Gateway Load
+ * Balancer, which AWS lets add subnets but not drop them, is set onto the one it is on.
+ */
+ @ParameterizedTest
+ @CsvSource(delimiter = '|', value = {"network|subnet-a,subnet-b", "gateway|subnet-a"})
+ void aNetworkOrGatewayLoadBalancerCanBeSetOntoOneSubnet(String type, String createdOn) {
+ when(ec2Service.describeSubnets(REGION, List.of("subnet-a"), Map.of()))
+ .thenReturn(List.of(subnet("subnet-a", REGION + "a")));
+ LoadBalancer lb = service.createLoadBalancer(REGION, "set-one-" + type, "internal", type, "ipv4",
+ List.of(createdOn.split(",")), List.of(), Map.of());
+
+ service.setSubnets(REGION, lb.getLoadBalancerArn(), List.of("subnet-a"));
+
+ assertEquals(List.of("subnet-a"), service.describeLoadBalancers(REGION, List.of(lb.getLoadBalancerArn()),
+ null, null, null).getFirst().getAvailabilityZones().stream().map(AvailabilityZone::getSubnetId).toList());
+ }
+
+ /**
+ * setSubnets counts only a list that names subnets; the SetSubnets action refuses an empty one before
+ * it gets here. A CloudFormation update moves a balancer an earlier Floci version saved without
+ * subnets onto the template's subnets, and when the update rolls back, the move back onto none is taken.
+ */
+ @Test
+ void aRollbackOntoNoSubnetsIsNotCounted() {
+ LoadBalancer saved = service.createLoadBalancer(REGION, "saved-without-subnets", "internal", "application",
+ "ipv4", ALB_SUBNETS, List.of(), Map.of());
+ saved.setAvailabilityZones(new ArrayList<>());
+ saved.setVpcId(null);
+ service.setSubnets(REGION, saved.getLoadBalancerArn(), ALB_SUBNETS);
+
+ service.setSubnets(REGION, saved.getLoadBalancerArn(), List.of());
+
+ assertTrue(service.describeLoadBalancers(REGION, List.of(saved.getLoadBalancerArn()), null, null, null)
+ .getFirst().getAvailabilityZones().isEmpty());
+ }
+
+ /**
+ * Through setSubnets with one subnet: the count depends on the balancer's type, so a balancer that
+ * does not exist is reported first.
+ */
+ @Test
+ void setSubnetsOntoOneSubnetReportsAMissingBalancerFirst() {
+ AwsException refusal = assertThrows(AwsException.class, () -> service.setSubnets(REGION,
+ "arn:aws:elasticloadbalancing:" + REGION + ":000000000000:loadbalancer/app/missing/0123456789abcdef",
+ List.of("subnet-a")));
+
+ assertEquals("LoadBalancerNotFound", refusal.getErrorCode());
+ verify(ec2Service, never()).describeSubnets(anyString(), anyList(), any());
+ }
}