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 7f033a30b2..12472d53f8 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 @@ -11,6 +11,7 @@ import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalanci import software.amazon.awssdk.services.elasticloadbalancingv2.model.Action; import software.amazon.awssdk.services.elasticloadbalancingv2.model.ActionTypeEnum; import software.amazon.awssdk.services.elasticloadbalancingv2.model.AddTagsRequest; +import software.amazon.awssdk.services.elasticloadbalancingv2.model.AvailabilityZone; import software.amazon.awssdk.services.elasticloadbalancingv2.model.CreateListenerRequest; import software.amazon.awssdk.services.elasticloadbalancingv2.model.CreateListenerResponse; import software.amazon.awssdk.services.elasticloadbalancingv2.model.CreateLoadBalancerRequest; @@ -227,6 +228,29 @@ class ElbV2Test { assertThat(found).isTrue(); } + @Test + @Order(8) + @DisplayName("SetSubnets - neither Subnets nor SubnetMappings is a ValidationError") + void setSubnetsWithoutSubnets() { + List subnets = TestFixtures.defaultVpcSubnets(); + String arn = elb.createLoadBalancer(r -> r.name(TestFixtures.uniqueName("sdk-set-none")) + .type(LoadBalancerTypeEnum.NETWORK).subnets(subnets)) + .loadBalancers().get(0).loadBalancerArn(); + try { + assertThatThrownBy(() -> elb.setSubnets(r -> r.loadBalancerArn(arn))) + .isInstanceOfSatisfying(ElasticLoadBalancingV2Exception.class, e -> { + assertThat(e.statusCode()).isEqualTo(400); + assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationError"); + assertThat(e.awsErrorDetails().errorMessage()).isEqualTo("At least one subnet must be specified"); + }); + assertThat(elb.describeLoadBalancers(r -> r.loadBalancerArns(arn)).loadBalancers().get(0).availabilityZones()) + .extracting(AvailabilityZone::subnetId) + .containsExactlyInAnyOrderElementsOf(subnets); + } finally { + elb.deleteLoadBalancer(r -> r.loadBalancerArn(arn)); + } + } + @Test @Order(6) @DisplayName("CreateLoadBalancer - neither Subnets nor SubnetMappings is a ValidationError") diff --git a/docs/services/elb.md b/docs/services/elb.md index d12be215cc..ea3ad62b96 100644 --- a/docs/services/elb.md +++ b/docs/services/elb.md @@ -94,6 +94,7 @@ HTTPS listeners require a default certificate. Supply one when creating a listen - 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. - 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/ElbV2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2QueryHandler.java index e2f665663d..86028ea4a9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2QueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2QueryHandler.java @@ -256,7 +256,7 @@ public class ElbV2QueryHandler { private Response handleSetSubnets(MultivaluedMap p, String region) { String arn = p.getFirst("LoadBalancerArn"); List subnets = ElbV2Service.requestedSubnets(memberList(p, "Subnets"), subnetMappingSubnetIds(p)); - service.setSubnets(region, arn, subnets); + service.setSubnetsFromRequest(region, arn, subnets); return voidResponse("SetSubnetsResponse"); } 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 6b85dae9c1..6974c20097 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 @@ -411,7 +411,27 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc persistRegion(loadBalancers, region); } - /** Under EC2's subnet lock for the same reason as {@link #createLoadBalancer}. */ + /** + * The SetSubnets action, for the Query handler. A request with neither {@code Subnets} nor + * {@code SubnetMappings} is refused and the balancer stays on its subnets, with the error + * CreateLoadBalancer gives a balancer of its type with neither; AWS gives a Network Load Balancer + * that error for SetSubnets too. The balancer is looked up first, as the message depends on its + * type. Only an empty list is refused here; a request that names subnets is checked by + * {@link #setSubnets}. + */ + void setSubnetsFromRequest(String region, String arn, List subnets) { + LoadBalancer lb = requireLoadBalancer(region, arn); + if (subnets.isEmpty()) { + requireSubnets(lb.getType(), subnets); + } + setSubnets(region, arn, subnets); + } + + /** + * Under EC2's subnet lock for the same reason as {@link #createLoadBalancer}. Unlike the SetSubnets + * action, this takes an empty list: CloudFormation moves balancers through it, and its rollback + * moves a balancer an earlier Floci version saved without subnets back onto none. + */ public void setSubnets(String region, String arn, List subnets) { ec2Service.runWithSubnetReferencesHeld(region, () -> { LoadBalancer lb = requireLoadBalancer(region, arn); 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 dd7ddefd24..51ab7d36a4 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 @@ -495,6 +495,43 @@ class ElbV2CfnProvisionerTest { assertEquals(Set.of("subnet-1", "subnet-2"), usedSubnets(moved)); } + /** + * An update whose template names neither {@code Subnets} nor {@code SubnetMappings} leaves the kept + * load balancer on its subnets: it does not call ElbV2Service.setSubnets, which would move the + * balancer onto none. + */ + @Test + void anUpdateThatNamesNoSubnetsLeavesTheKeptLoadBalancerOnItsSubnets() { + 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"))); + StackResource lb = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb"); + lb.getAttributes().put("LoadBalancerName", "web"); + + provisioner.provision(lb, mapper.createObjectNode().put("Name", "web"), ctx(LB_ARN)); + + assertEquals(Set.of("subnet-1", "subnet-2"), usedSubnets(lb)); + assertTrue(provisioner.rollbackUpdate(lb)); + verify(elb, never()).setSubnets(anyString(), anyString(), anyList()); + } + + /** + * A load balancer an earlier Floci version saved without subnets is moved back onto none when an + * update that gave it subnets rolls back: the move back goes through ElbV2Service.setSubnets, which + * takes an empty list, where the SetSubnets action refuses one. + */ + @Test + void aRollbackMovesALoadBalancerSavedWithoutSubnetsBackOntoNone() { + StackResource lb = keptLoadBalancerUpdatedTo(loadBalancerOn("web"), "subnet-1", "subnet-2"); + verify(elb).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2")); + + assertTrue(provisioner.rollbackUpdate(lb)); + + verify(elb).setSubnets(REGION, LB_ARN, List.of()); + assertEquals(Set.of(), usedSubnets(lb)); + } + @Test void theSameSubnetsInAnotherOrderLeaveTheKeptLoadBalancerAlone() { StackResource lb = keptLoadBalancerUpdatedTo(loadBalancerOn("web", "subnet-1", "subnet-2"), 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 43ac8ab6c6..b69a98dcba 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 @@ -1459,4 +1459,75 @@ class ElbV2IntegrationTest { .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.AvailabilityZones.member.SubnetId", contains(Ec2Service.defaultSubnetId("us-east-1", "a"), Ec2Service.defaultSubnetId("us-east-1", "b"))); } + + /** + * SetSubnets with neither Subnets nor SubnetMappings, left out or sent as empty lists, is a + * ValidationError, and the balancer stays on its subnets and in its VPC. A Network Load Balancer + * gets the message AWS gives it; an Application Load Balancer gets the one CreateLoadBalancer gives + * it, and a Gateway Load Balancer the Network one. + */ + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "application|false|At least two subnets in two different Availability Zones must be specified", + "application|true|At least two subnets in two different Availability Zones must be specified", + "network|false|At least one subnet must be specified", + "network|true|At least one subnet must be specified", + "gateway|false|At least one subnet must be specified", + "gateway|true|At least one subnet must be specified" + }) + @Order(80) + void setSubnetsWithNeitherSubnetsNorSubnetMappingsIsRefused(String type, boolean emptyLists, String message) { + String subnetA = Ec2Service.defaultSubnetId("us-east-1", "a"); + String subnetB = Ec2Service.defaultSubnetId("us-east-1", "b"); + String arn = given() + .formParam("Action", "CreateLoadBalancer") + .formParam("Name", "set-none-" + type + (emptyLists ? "-empty" : "")) + .formParam("Type", type) + .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"); + + RequestSpecification setSubnets = given() + .formParam("Action", "SetSubnets") + .formParam("LoadBalancerArn", arn) + .header("Authorization", AUTH); + if (emptyLists) { + setSubnets.formParam("Subnets", "").formParam("SubnetMappings", ""); + } + setSubnets + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", equalTo(message)); + + 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); + } } 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 0f529c6e6d..45209d2360 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 @@ -21,6 +21,8 @@ import io.github.hectorvent.floci.services.elbv2.model.RuleCondition; import io.github.hectorvent.floci.services.elbv2.model.TargetDescription; import io.github.hectorvent.floci.services.elbv2.model.TargetGroup; import io.github.hectorvent.floci.services.elbv2.model.TargetHealth; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.Response; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -175,6 +177,73 @@ class ElbV2ServiceTest { assertEquals(400, both.getHttpStatus()); } + /** + * SetSubnets with neither Subnets nor SubnetMappings, left out or sent as empty lists, is refused + * before any subnet is looked up, and the balancer keeps its zones and its VPC. A Network Load + * Balancer gets the message AWS gives it; an Application Load Balancer gets the one + * CreateLoadBalancer gives it, and a Gateway Load Balancer the Network one. + */ + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "application|At least two subnets in two different Availability Zones must be specified", + "network|At least one subnet must be specified", + "gateway|At least one subnet must be specified" + }) + void setSubnetsWithNeitherSubnetsNorSubnetMappingsIsRefused(String type, String message) { + LoadBalancer lb = service.createLoadBalancer(REGION, "set-none-" + type, "internal", type, "ipv4", + ALB_SUBNETS, List.of(), Map.of()); + ElbV2QueryHandler handler = new ElbV2QueryHandler(service); + clearInvocations(ec2Service); + for (boolean emptyLists : new boolean[] {false, true}) { + MultivaluedHashMap params = new MultivaluedHashMap<>(); + params.add("LoadBalancerArn", lb.getLoadBalancerArn()); + if (emptyLists) { + params.add("Subnets", ""); + params.add("SubnetMappings", ""); + } + Response response = handler.handle("SetSubnets", params, REGION); + String xml = (String) response.getEntity(); + assertEquals(400, response.getStatus(), xml); + assertTrue(xml.contains("ValidationError"), xml); + assertTrue(xml.contains("" + message + ""), xml); + } + 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()); + } + + /** The message depends on the balancer's type, so a balancer that does not exist is reported first. */ + @Test + void setSubnetsForAMissingBalancerReportsItBeforeMissingSubnets() { + MultivaluedHashMap params = new MultivaluedHashMap<>(); + params.add("LoadBalancerArn", + "arn:aws:elasticloadbalancing:" + REGION + ":000000000000:loadbalancer/net/missing/0123456789abcdef"); + + Response response = new ElbV2QueryHandler(service).handle("SetSubnets", params, REGION); + + String xml = (String) response.getEntity(); + assertEquals(400, response.getStatus(), xml); + assertTrue(xml.contains("LoadBalancerNotFound"), 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.