Light, fluffy, and always free - The AWS Local Emulator alternative
fix(elbv2): answer a single-subnet ALB with ValidationError (#6098)
Jackson Price61a42591a96d
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2DescribeSubnetsNotFoundTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2DescribeSubnetsNotFoundTest.javaindex c47ad313d4..a2e8d36175 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2DescribeSubnetsNotFoundTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2DescribeSubnetsNotFoundTest.java@@ -50,17 +50,19 @@ class Ec2DescribeSubnetsNotFoundTest {/*** describeSubnets is shared with the services that build on it, and each reports a missing* subnet in its own words. ELBv2 owes its callers SubnetNotFound, so the EC2 error must not- * reach through.+ * reach through. An Application Load Balancer takes at least two subnets, and one alone is refused+ * before it is looked up, so the missing subnet is sent alongside an existing one.*/@Test@DisplayName("ELBv2 still reports its own SubnetNotFound for a missing subnet")void elbV2KeepsItsOwnSubnetError() {+ String existing = TestFixtures.defaultVpcSubnets().get(0);try (ElasticLoadBalancingV2Client elb = TestFixtures.elbV2Client()) {ElasticLoadBalancingV2Exception error = assertThrows(ElasticLoadBalancingV2Exception.class,() -> elb.createLoadBalancer(r -> r.name("lb-" + UUID.randomUUID().toString().substring(0, 8)).type("application")- .subnets(MISSING)));+ .subnets(existing, MISSING)));assertThat(error.awsErrorDetails().errorCode()).isEqualTo("SubnetNotFound");}}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.javaindex df2f98c5df..7f033a30b2 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@@ -242,6 +242,24 @@ class ElbV2Test {.isInstanceOf(LoadBalancerNotFoundException.class);}+ @Test+ @Order(7)+ @DisplayName("CreateLoadBalancer - an Application Load Balancer on one subnet is a ValidationError")+ void createApplicationLoadBalancerOnOneSubnet() {+ String name = TestFixtures.uniqueName("sdk-one-subnet");+ String subnet = TestFixtures.defaultVpcSubnets().get(0);+ assertThatThrownBy(() -> elb.createLoadBalancer(r -> r.name(name).type(LoadBalancerTypeEnum.APPLICATION)+ .subnets(subnet)))+ .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");+ });+ assertThatThrownBy(() -> elb.describeLoadBalancers(r -> r.names(name)))+ .isInstanceOf(LoadBalancerNotFoundException.class);+ }+// ─── Target Groups ───────────────────────────────────────────────────────@Testdiff --git a/docs/services/elb.md b/docs/services/elb.mdindex 58e1232f14..d12be215cc 100644--- a/docs/services/elb.md+++ b/docs/services/elb.md@@ -92,7 +92,7 @@ HTTPS listeners require a default certificate. Supply one when creating a listen- Listeners sharing a local port must use the same protocol. Requests select a load balancer by its DNS name, a hostname declared by its rules, or a certificate hostname; ambiguous hostnames return 502.- 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`. With neither it returns `ValidationError` and creates nothing: `At least two subnets in two different Availability Zones must be specified` for an Application Load Balancer, `At least one subnet must be specified` for a Network or Gateway Load Balancer. CloudFormation refuses an `AWS::ElasticLoadBalancingV2::LoadBalancer` with neither the same way when it creates or replaces the balancer; an update that keeps the balancer leaves it on its subnets.+- `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.- 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.diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisioner.javaindex 1932f52519..181c7b7759 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisioner.java@@ -216,7 +216,7 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {* as one an Fn::If drops, does not count. {@code SubnetId} is required in a mapping, so one without it* fails the resource before anything is created or moved, with the error the resource schema gives.* A blank one counts as a mapping and, with no {@code Subnets}, is passed on as given for ELBv2 to- * refuse as an unknown subnet; dropping it would create or move the balancer without it.+ * refuse; dropping it would create or move the balancer without it.*/private static List<String> templateSubnets(JsonNode props, ProvisionContext ctx) {List<String> subnets = ctx.resolveStringList(props, "Subnets");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.javaindex 7a0c2f12bc..6b85dae9c1 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@@ -283,18 +283,22 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc}/**- * Every load balancer type takes {@code Subnets} or {@code SubnetMappings}, so a request with- * neither 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. This runs after the duplicate-name check, because a- * CloudFormation stack update finds the balancer it keeps through DuplicateLoadBalancerName,- * whatever subnets its template names.+ * 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.*/private static void requireSubnets(String lbType, List<String> subnets) {- if (subnets == null || subnets.isEmpty()) {- throw new AwsException("ValidationError", "application".equals(lbType)- ? "At least two subnets in two different Availability Zones must be specified"- : "At least one subnet must be specified", 400);+ int count = subnets == null ? 0 : subnets.size();+ if ("application".equals(lbType) && count < 2) {+ throw new AwsException("ValidationError",+ "At least two subnets in two different Availability Zones must be specified", 400);+ }+ if (count == 0) {+ throw new AwsException("ValidationError", "At least one subnet must be specified", 400);}}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2ReplacementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2ReplacementIntegrationTest.javaindex 0a2737ae5f..bc47ca2431 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2ReplacementIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2ReplacementIntegrationTest.java@@ -141,6 +141,50 @@ class CloudFormationElbV2ReplacementIntegrationTest {deleteStack(stackName);}+ /**+ * A new name replaces the load balancer, and the replacement is created the way CreateLoadBalancer+ * creates one: an Application Load Balancer renamed onto one subnet fails the update with that+ * call's error, no balancer has the new name, and the one it was to replace keeps both subnets.+ */+ @Test+ void aReplacementOnOneSubnetFailsTheUpdateAndKeepsTheBalancer() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "elb-replace-one-" + suffix;+ String subnetA = Ec2Service.defaultSubnetId(REGION, "a");+ String subnetB = Ec2Service.defaultSubnetId(REGION, "b");+ String template = """+ {+ "Resources": {+ "Alb": {+ "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",+ "Properties": {"Name": "%s", "Type": "application", "Subnets": [%s]}+ }+ },+ "Outputs": {"AlbRef": {"Value": {"Ref": "Alb"}}}+ }+ """;+ createStack(stackName, template.formatted("alb-kept-" + suffix, "\"" + subnetA + "\", \"" + subnetB + "\""));+ String kept = output(describeStack(stackName), "AlbRef");++ updateStack(stackName, template.formatted("alb-renamed-" + suffix, "\"" + subnetA + "\""));++ CfnStackWaits.awaitStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");+ assertEquals(kept, output(describeStack(stackName), "AlbRef"));+ assertEquals(true, describeEvents(stackName)+ .contains("At least two subnets in two different Availability Zones must be specified"),+ "the replacement fails with CreateLoadBalancer's error: " + describeEvents(stackName));+ given().formParam("Action", "DescribeLoadBalancers").formParam("Version", "2015-12-01")+ .formParam("LoadBalancerArns.member.1", kept)+ .when().post("/").then().statusCode(200)+ .body(containsString("<SubnetId>" + subnetA + "</SubnetId>"))+ .body(containsString("<SubnetId>" + subnetB + "</SubnetId>"));+ given().formParam("Action", "DescribeLoadBalancers").formParam("Version", "2015-12-01")+ .formParam("Names.member.1", "alb-renamed-" + suffix)+ .when().post("/").then().statusCode(400).body(containsString("LoadBalancerNotFound"));++ deleteStack(stackName);+ }+/** The same two balancers with a listener that needs no target group. */private static String fixedResponseTemplate(String suffix) {return """diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2SubnetMappingsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2SubnetMappingsIntegrationTest.javaindex c28a9d58a5..00caace5b0 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2SubnetMappingsIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2SubnetMappingsIntegrationTest.java@@ -8,6 +8,7 @@ import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.CsvSource;+import org.junit.jupiter.params.provider.ValueSource;import java.util.LinkedHashMap;import java.util.List;@@ -23,7 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;* subnet fails its stack, as on AWS, rather than the balancer being created with no subnets, while a* mapping an {@code Fn::If} drops with {@code AWS::NoValue} is left out. {@code Subnets} and* {@code SubnetMappings} together fail it too, as ELBv2 takes one or the other, and so does a- * balancer with neither.+ * balancer with neither, or an Application Load Balancer on one subnet.*/@QuarkusTestclass CloudFormationElbV2SubnetMappingsIntegrationTest {@@ -124,6 +125,40 @@ class CloudFormationElbV2SubnetMappingsIntegrationTest {}}+ /**+ * An Application Load Balancer on one subnet, in {@code Subnets} or in {@code SubnetMappings},+ * fails the stack with CreateLoadBalancer's error and leaves no balancer.+ */+ @ParameterizedTest+ @ValueSource(strings = {"Subnets", "SubnetMappings"})+ void anApplicationLoadBalancerOnOneSubnetFailsTheStack(String property) {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stack = "alb-one-subnet-" + suffix;+ String name = "alb-one-" + suffix;+ String template = template(name, "{\"SubnetId\": {\"Ref\": \"SubnetA\"}}")+ .replace("\"Type\": \"network\"", "\"Type\": \"application\"");+ if ("Subnets".equals(property)) {+ template = template.replace("\"SubnetMappings\": [{\"SubnetId\": {\"Ref\": \"SubnetA\"}}]",+ "\"Subnets\": [{\"Ref\": \"SubnetA\"}]");+ }+ assertTrue(template.contains("\"" + property + "\": [{"), template);+ assertTrue(template.contains("\"Type\": \"application\""), template);+ try {+ request(CFN_AUTH, "CreateStack", "StackName", stack, "TemplateBody", template).statusCode(200);+ CfnStackWaits.awaitStatus(stack, "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));+ request(ELB_AUTH, "DescribeLoadBalancers", "Names.member.1", name).statusCode(400)+ .body(containsString("LoadBalancerNotFound"));+ } finally {+ request(CFN_AUTH, "DeleteStack", "StackName", stack);+ }+ }+/** A second mapping an {@code Fn::If} drops leaves the balancer on the first mapping's subnet. */@Testvoid aMappingAnFnIfDropsIsLeftOut() {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.javaindex 8864171720..43ac8ab6c6 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@@ -447,20 +447,77 @@ class ElbV2IntegrationTest {.body("ErrorResponse.Error.Code", equalTo("InvalidConfigurationRequest"));}- @Test+ /**+ * An Application Load Balancer takes subnets in at least two Availability Zones, so one subnet, in+ * Subnets or in SubnetMappings, is the ValidationError a balancer with none gets, and nothing is+ * created. AWS counts the subnets before it looks them up, so one that does not exist gets it too.+ */+ @ParameterizedTest+ @CsvSource(delimiter = '|', nullValues = "NONE", value = {+ "single-subnet-lb|application|Subnets.member.1|a",+ "single-subnet-default-lb|NONE|Subnets.member.1|a",+ "single-mapping-lb|application|SubnetMappings.member.1.SubnetId|a",+ "single-missing-subnet-lb|application|Subnets.member.1|NONE"+ })@Order(12)- void createLoadBalancerWithSingleSubnetThrowsInvalidConfigurationRequest() {+ void createLoadBalancerWithOneSubnetIsAValidationError(String name, String type, String parameter, String zone) {+ String subnet = zone == null ? "subnet-does-not-exist" : Ec2Service.defaultSubnetId("us-east-1", zone);+ RequestSpecification request = given()+ .formParam("Action", "CreateLoadBalancer")+ .formParam("Name", name)+ .formParam(parameter, subnet)+ .header("Authorization", AUTH);+ if (type != null) {+ request.formParam("Type", type);+ }+ request+ .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("Names.member.1", name)+ .header("Authorization", AUTH)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("ErrorResponse.Error.Code", equalTo("LoadBalancerNotFound"));+ }++ /** A Network or Gateway Load Balancer can be in a single Availability Zone. */+ @ParameterizedTest+ @CsvSource({"network", "gateway"})+ @Order(79)+ void createLoadBalancerOnOneSubnetIsAllowedForNetworkAndGatewayLoadBalancers(String type) {+ String arn = given().formParam("Action", "CreateLoadBalancer")- .formParam("Name", "single-subnet-lb")- .formParam("Type", "application")+ .formParam("Name", "single-subnet-" + type)+ .formParam("Type", type).formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a")).header("Authorization", AUTH).when().post("/").then()- .statusCode(400)- .body("ErrorResponse.Error.Code", equalTo("InvalidConfigurationRequest"));+ .statusCode(200)+ .body("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.AvailabilityZones.member.SubnetId",+ equalTo(Ec2Service.defaultSubnetId("us-east-1", "a")))+ .extract()+ .path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn");++ given()+ .formParam("Action", "DeleteLoadBalancer")+ .formParam("LoadBalancerArn", arn)+ .header("Authorization", AUTH)+ .when()+ .post("/")+ .then()+ .statusCode(200);}@Test@@ -629,7 +686,8 @@ class ElbV2IntegrationTest {.formParam("Action", "CreateLoadBalancer").formParam("Name", "missing-subnet-lb").formParam("Type", "application")- .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("/")@@ -1278,7 +1336,7 @@ class ElbV2IntegrationTest {given().formParam("Action", "CreateLoadBalancer").formParam("Name", "lb-missing-subnet")- .formParam("Type", "application")+ .formParam("Type", "network").formParam("Subnets.member.1", "subnet-does-not-exist").header("Authorization", AUTH).when()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.javaindex 868e98446a..0f529c6e6d 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@@ -125,6 +125,40 @@ class ElbV2ServiceTest {verify(ec2Service, never()).describeSubnets(anyString(), anyList(), any());}+ /**+ * An Application Load Balancer takes subnets in at least two Availability Zones, so one subnet gets+ * the refusal a balancer with none gets. AWS counts before it looks the subnet up, so the subnet is+ * not looked up here either, and nothing is stored.+ */+ @ParameterizedTest+ @CsvSource(nullValues = "NONE", value = {"NONE", "application"})+ void anApplicationLoadBalancerOnOneSubnetIsRefusedBeforeTheSubnetIsLookedUp(String type) {+ // 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")));+ AwsException refusal = assertThrows(AwsException.class, () -> service.createLoadBalancer(REGION,+ "one-subnet", null, type, null, List.of("subnet-a"), List.of(), Map.of()));+ assertEquals("ValidationError", refusal.getErrorCode());+ assertEquals("At least two subnets in two different Availability Zones must be specified",+ refusal.getMessage());+ assertEquals(400, refusal.getHttpStatus());+ assertTrue(service.describeLoadBalancers(REGION, null, null, null, null).isEmpty());+ verify(ec2Service, never()).describeSubnets(anyString(), anyList(), any());+ }++ /** A Network or Gateway Load Balancer can be in a single Availability Zone. */+ @ParameterizedTest+ @ValueSource(strings = {"network", "gateway"})+ void aNetworkOrGatewayLoadBalancerCanBeOnOneSubnet(String type) {+ when(ec2Service.describeSubnets(REGION, List.of("subnet-a"), Map.of()))+ .thenReturn(List.of(subnet("subnet-a", REGION + "a")));+ LoadBalancer created = service.createLoadBalancer(REGION, "one-subnet", null, type, null,+ List.of("subnet-a"), List.of(), Map.of());+ assertEquals("vpc-a", created.getVpcId());+ assertEquals(List.of("subnet-a"),+ created.getAvailabilityZones().stream().map(AvailabilityZone::getSubnetId).toList());+ }+/*** The API handler and the CloudFormation provisioner both take a request's subnets from here: one* side as given, an empty list for neither, and a refusal for both.