From a434e5289280c81dca46f53add8f11d036d791cb Mon Sep 17 00:00:00 2001 From: Jackson Price <59149601+jprice8@users.noreply.github.com> Date: Tue, 20 Oct 2026 12:08:31 -0500 Subject: [PATCH] fix(elbv2): refuse CreateLoadBalancer with neither Subnets nor SubnetMappings (#6087) * test(elbv2): give the tests' subnetless load balancers subnets CreateLoadBalancer takes Subnets or SubnetMappings for every load balancer type, and AWS refuses a request with neither. Tests that created a balancer with neither, to exercise listeners, the data plane, CodeDeploy, API Gateway or CloudFormation, now give it two default subnets: the src/test classes through Ec2Service.defaultSubnetId, the Java compatibility suite through a new TestFixtures.defaultVpcSubnets. setSubnetsAfterSubnetlessCreateCanAdoptCustomVpc becomes setSubnetsInAnotherVpcIsRefused, since a balancer created with subnets keeps its VPC. The adoption it covered still applies to a balancer an earlier version saved without subnets, and ElbV2ServiceTest now covers that. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(elbv2): refuse CreateLoadBalancer with neither Subnets nor SubnetMappings A CreateLoadBalancer that named neither Subnets nor SubnetMappings made a load balancer with no Availability Zone and no VPC, where the API reference says every type takes one or the other. It now answers ValidationError and creates nothing, with the message AWS gives for the type: "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. A CloudFormation load balancer with neither fails its stack the same way. The check runs after the duplicate-name check, because a stack update finds the balancer it keeps through DuplicateLoadBalancerName whatever subnets its template names. A balancer an earlier version saved without subnets still works, and its first SetSubnets still gives it a VPC. Follow-up to the review of #5881. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * refactor(elbv2): take a request's Subnets or SubnetMappings from ElbV2Service The rule that Subnets and SubnetMappings are alternatives, and its ValidationError, was written out three times: in the Query handler's CreateLoadBalancer and SetSubnets, and in the CloudFormation provisioner. ElbV2Service.requestedSubnets now holds it, and all three take the request's subnets from there. Valid requests resolve the same subnets as before, and both together are still refused with the same error. A new test pins the SetSubnets path, which had none. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(elbv2): say when CloudFormation refuses a load balancer without subnets The behaviour note said a CloudFormation load balancer with neither Subnets nor SubnetMappings fails its stack the same way as the API does. That holds when the stack creates or replaces the balancer. An update that keeps the balancer finds it by its taken name before the subnet check, so it leaves the balancer on its subnets, as before. The note now says so. The requireSubnets Javadoc no longer presents the Gateway Load Balancer message as AWS's own. No public record of it was found; it is the Network Load Balancer one, since a Gateway Load Balancer takes subnets the same way. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(elbv2): give the remaining subnetless test requests subnets Review follow-ups: - The two duplicate-name tests, ElbV2IntegrationTest and the compatibility suite's ElbV2Test, sent a create with no subnets, so they passed only because the name is checked first. They now name subnets. The compatibility one also changes the scheme, because AWS answers a create that repeats a balancer's settings with success. - ElbV2CfnProvisionerTest's successful creates and replacements now provision templates with two subnets and match them, rather than a subnetless create the real service refuses. The kept-balancer updates keep their subnetless templates. - The CloudFormation case that leaves both properties out checks that its template really has no SubnetMappings, so a reformatted template cannot quietly turn it into the empty-list case. - TestFixtures.defaultVpcSubnets() fails with a message when the region has no default VPC or fewer than two default subnets. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(elbv2): say which subnet messages are AWS's in the test docs Second-round review follow-ups, wording only: - The ELBv2 unit and Query-protocol tests of a create with neither Subnets nor SubnetMappings now say the messages are the ones AWS gives an Application or a Network Load Balancer, and that a Gateway Load Balancer gets the Network one, as the service's Javadoc does. - The provisioner test's onTwoSubnets builds its list from TWO_SUBNETS, the list its stubs match, and its Javadoc no longer reads as two subnets for every type. - TestFixtures.defaultVpcSubnets() says an Application Load Balancer needs two zones, not every load balancer. - The ELBv2 docs say a CloudFormation update moves a balancer when it names other subnets, since one that names none leaves it in place. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> --------- Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> --- .../java/com/floci/test/TestFixtures.java | 31 +++++ .../com/floci/test/CodeDeployEcsTest.java | 3 +- .../test/ElbV2DefaultCertificateTest.java | 6 +- .../floci/test/ElbV2HttpsDataPlaneTest.java | 3 +- .../test/java/com/floci/test/ElbV2Test.java | 22 +++ docs/services/elb.md | 8 +- .../provisioners/ElbV2CfnProvisioner.java | 18 +-- .../services/elbv2/ElbV2QueryHandler.java | 19 +-- .../floci/services/elbv2/ElbV2Service.java | 32 ++++- .../ApiGatewayV2AlbIntegrationTest.java | 3 + ...ionElbV2SubnetMappingsIntegrationTest.java | 37 +++++- .../CloudFormationIntegrationTest.java | 12 +- .../provisioners/ElbV2CfnProvisionerTest.java | 55 ++++---- .../CodeDeployEcsIntegrationTest.java | 3 + .../ElbV2HttpsDataPlaneIntegrationTest.java | 8 +- .../services/elbv2/ElbV2IntegrationTest.java | 125 ++++++++++++++++-- ...2LambdaTargetDataPlaneIntegrationTest.java | 3 + .../ElbV2LambdaTargetIntegrationTest.java | 3 + ...lbV2PreserveHostHeaderIntegrationTest.java | 3 + ...V2SamePortHostDispatchIntegrationTest.java | 5 + .../services/elbv2/ElbV2ServiceTest.java | 83 ++++++++++++ .../elbv2/ElbV2StickinessIntegrationTest.java | 5 +- .../elbv2/ElbV2WebSocketIntegrationTest.java | 2 + 23 files changed, 413 insertions(+), 76 deletions(-) diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java index 255b2f30f2..2229a16c6d 100644 --- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java +++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java @@ -53,6 +53,8 @@ import software.amazon.awssdk.services.dlm.DlmClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.streams.DynamoDbStreamsClient; import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.Subnet; +import software.amazon.awssdk.services.ec2.model.Vpc; import software.amazon.awssdk.services.ecr.EcrClient; import software.amazon.awssdk.services.ecs.EcsClient; import software.amazon.awssdk.services.efs.EfsClient; @@ -178,6 +180,8 @@ import java.security.cert.X509Certificate; import java.time.Duration; import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.TreeMap; import java.util.UUID; import java.util.function.BooleanSupplier; import java.util.function.Supplier; @@ -277,6 +281,33 @@ public final class TestFixtures { return REGION.id() + "a"; } + /** + * A default subnet in each of the first two availability zones of {@link #region()}'s default VPC, + * for tests that create a load balancer: CreateLoadBalancer needs subnets for every type, and an + * Application Load Balancer needs them in two zones. + */ + public static List defaultVpcSubnets() { + try (Ec2Client ec2 = ec2Client()) { + List defaults = ec2.describeVpcs(r -> r.filters(f -> f.name("is-default").values("true"))).vpcs(); + if (defaults.isEmpty()) { + throw new IllegalStateException("no default VPC in " + REGION.id() + " to put a load balancer in"); + } + String vpcId = defaults.get(0).vpcId(); + Map byZone = new TreeMap<>(); + for (Subnet subnet : ec2.describeSubnets(r -> r.filters(f -> f.name("vpc-id").values(vpcId))) + .subnets()) { + if (Boolean.TRUE.equals(subnet.defaultForAz())) { + byZone.putIfAbsent(subnet.availabilityZone(), subnet.subnetId()); + } + } + if (byZone.size() < 2) { + throw new IllegalStateException("default VPC " + vpcId + " has default subnets in " + + byZone.keySet() + ", and an Application Load Balancer needs two availability zones"); + } + return byZone.values().stream().limit(2).toList(); + } + } + /** * The partition of {@link #region()} ({@code aws}, {@code aws-cn}, {@code aws-us-gov}, ...), from * the SDK's own region metadata, so a test pins the partition its clients actually sign in. A region diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployEcsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployEcsTest.java index 61398c45d7..8665956833 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployEcsTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CodeDeployEcsTest.java @@ -112,7 +112,8 @@ class CodeDeployEcsTest { CreateLoadBalancerResponse resp = elb.createLoadBalancer(r -> r .name(LB_NAME) .type(LoadBalancerTypeEnum.APPLICATION) - .ipAddressType(IpAddressType.IPV4)); + .ipAddressType(IpAddressType.IPV4) + .subnets(TestFixtures.defaultVpcSubnets())); assertThat(resp.loadBalancers()).hasSize(1); lbArn = resp.loadBalancers().get(0).loadBalancerArn(); diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ElbV2DefaultCertificateTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ElbV2DefaultCertificateTest.java index 787eac329a..aad53fe7ac 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ElbV2DefaultCertificateTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ElbV2DefaultCertificateTest.java @@ -31,7 +31,8 @@ class ElbV2DefaultCertificateTest { String loadBalancer = null; try { loadBalancer = elb.createLoadBalancer(b -> b.name(TestFixtures.uniqueName("sdk-https-default")) - .type("application")).loadBalancers().get(0).loadBalancerArn(); + .type("application").subnets(TestFixtures.defaultVpcSubnets())) + .loadBalancers().get(0).loadBalancerArn(); String lbArn = loadBalancer; InvalidConfigurationRequestException creation = assertThrows(InvalidConfigurationRequestException.class, () -> createListener(elb, lbArn, "HTTPS", 443, null)); @@ -88,7 +89,8 @@ class ElbV2DefaultCertificateTest { String firstArn = first; String additionalArn = additional; loadBalancer = elb.createLoadBalancer(b -> b.name(TestFixtures.uniqueName("sdk-default-cert")) - .type("application")).loadBalancers().get(0).loadBalancerArn(); + .type("application").subnets(TestFixtures.defaultVpcSubnets())) + .loadBalancers().get(0).loadBalancerArn(); String lbArn = loadBalancer; String listener = elb.createListener(b -> b.loadBalancerArn(lbArn).port(443).protocol("HTTPS") .certificates(Certificate.builder().certificateArn(firstArn).build()) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ElbV2HttpsDataPlaneTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ElbV2HttpsDataPlaneTest.java index 726b5b163c..caf21c3c33 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ElbV2HttpsDataPlaneTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ElbV2HttpsDataPlaneTest.java @@ -90,7 +90,8 @@ class ElbV2HttpsDataPlaneTest { void officialClientsConfigureAcmBackedHttpsListenerThatTerminatesTls() throws Exception { LoadBalancer loadBalancer = elb.createLoadBalancer(request -> request .name(TestFixtures.uniqueName("tls")) - .type(LoadBalancerTypeEnum.APPLICATION)) + .type(LoadBalancerTypeEnum.APPLICATION) + .subnets(TestFixtures.defaultVpcSubnets())) .loadBalancers().get(0); loadBalancerArn = loadBalancer.loadBalancerArn(); String dnsName = loadBalancer.dnsName(); 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 1286454ca6..df2f98c5df 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 @@ -51,6 +51,7 @@ import software.amazon.awssdk.services.elasticloadbalancingv2.model.IpAddressTyp import software.amazon.awssdk.services.elasticloadbalancingv2.model.Listener; import software.amazon.awssdk.services.elasticloadbalancingv2.model.LoadBalancer; import software.amazon.awssdk.services.elasticloadbalancingv2.model.LoadBalancerAttribute; +import software.amazon.awssdk.services.elasticloadbalancingv2.model.LoadBalancerNotFoundException; import software.amazon.awssdk.services.elasticloadbalancingv2.model.LoadBalancerSchemeEnum; import software.amazon.awssdk.services.elasticloadbalancingv2.model.LoadBalancerStateEnum; import software.amazon.awssdk.services.elasticloadbalancingv2.model.LoadBalancerTypeEnum; @@ -137,6 +138,7 @@ class ElbV2Test { .type(LoadBalancerTypeEnum.APPLICATION) .scheme(LoadBalancerSchemeEnum.INTERNET_FACING) .ipAddressType(IpAddressType.IPV4) + .subnets(TestFixtures.defaultVpcSubnets()) .build()); assertThat(resp.loadBalancers()).hasSize(1); @@ -194,9 +196,13 @@ class ElbV2Test { @Order(4) @DisplayName("CreateLoadBalancer - duplicate name throws DuplicateLoadBalancerNameException") void createLoadBalancerDuplicateName() { + // A create that repeats the existing balancer's settings succeeds on AWS, so this one differs in + // its scheme; it names subnets so the taken name is the only thing wrong with it. assertThatThrownBy(() -> elb.createLoadBalancer(CreateLoadBalancerRequest.builder() .name(LB_NAME) .type(LoadBalancerTypeEnum.APPLICATION) + .scheme(LoadBalancerSchemeEnum.INTERNAL) + .subnets(TestFixtures.defaultVpcSubnets()) .build())) .isInstanceOf(DuplicateLoadBalancerNameException.class); } @@ -221,6 +227,21 @@ class ElbV2Test { assertThat(found).isTrue(); } + @Test + @Order(6) + @DisplayName("CreateLoadBalancer - neither Subnets nor SubnetMappings is a ValidationError") + void createLoadBalancerWithoutSubnets() { + String name = TestFixtures.uniqueName("sdk-no-subnets"); + assertThatThrownBy(() -> elb.createLoadBalancer(r -> r.name(name).type(LoadBalancerTypeEnum.NETWORK))) + .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"); + }); + assertThatThrownBy(() -> elb.describeLoadBalancers(r -> r.names(name))) + .isInstanceOf(LoadBalancerNotFoundException.class); + } + // ─── Target Groups ─────────────────────────────────────────────────────── @Test @@ -510,6 +531,7 @@ class ElbV2Test { .type(LoadBalancerTypeEnum.APPLICATION) .scheme(LoadBalancerSchemeEnum.INTERNAL) .ipAddressType(IpAddressType.IPV4) + .subnets(TestFixtures.defaultVpcSubnets()) .build()).loadBalancers().get(0).loadBalancerArn(); String otherListenerArn = null; String otherRuleArn = null; diff --git a/docs/services/elb.md b/docs/services/elb.md index 5c800bc513..58e1232f14 100644 --- a/docs/services/elb.md +++ b/docs/services/elb.md @@ -92,7 +92,8 @@ 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. -- 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 changes `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. +- `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. +- 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. - Target health starts in `initial` state with reason `Elb.RegistrationInProgress` and is updated by Floci's health checker when monitoring is active. @@ -137,11 +138,12 @@ arn:aws:elasticloadbalancing:{region}:{account-id}:listener-rule/app/{lb-name}/{ ```bash export AWS_ENDPOINT_URL=http://localhost:4566 -# Create a load balancer +# Create a load balancer on two of the default VPC's subnets aws elbv2 create-load-balancer \ --name my-alb \ --type application \ - --scheme internet-facing + --scheme internet-facing \ + --subnets subnet-default-us-east-1-a subnet-default-us-east-1-b # Create a target group aws elbv2 create-target-group \ 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.java index 37295343b1..1932f52519 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 @@ -211,12 +211,12 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner { /** * The template's subnets: {@code Subnets}, or else the {@code SubnetId} of each * {@code SubnetMappings} entry, the form a Network Load Balancer uses to give a zone an Elastic IP. - * Both non-empty fails the resource with the error CreateLoadBalancer gives, as the resource allows - * one or the other; an empty side, such 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. + * Both non-empty fails the resource with the error CreateLoadBalancer gives, through + * {@link ElbV2Service#requestedSubnets}, as the resource allows one or the other; an empty side, such + * 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. */ private static List templateSubnets(JsonNode props, ProvisionContext ctx) { List subnets = ctx.resolveStringList(props, "Subnets"); @@ -236,11 +236,7 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner { mapped.add(subnetId); } } - if (!subnets.isEmpty() && !mapped.isEmpty()) { - throw new AwsException("ValidationError", - "You can specify either subnets or subnet mappings, not both", 400); - } - return subnets.isEmpty() ? mapped : subnets; + return ElbV2Service.requestedSubnets(subnets, mapped); } /** 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 f44a7a117a..e2f665663d 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 @@ -123,18 +123,12 @@ public class ElbV2QueryHandler { String scheme = p.getFirst("Scheme"); String type = p.getFirst("Type"); String ipAddressType = p.getFirst("IpAddressType"); - List subnets = memberList(p, "Subnets"); - List subnetMappings = subnetMappingSubnetIds(p); - if (!subnets.isEmpty() && !subnetMappings.isEmpty()) { - throw new AwsException("ValidationError", - "You can specify either subnets or subnet mappings, not both", 400); - } - List effectiveSubnets = subnetMappings.isEmpty() ? subnets : subnetMappings; + List subnets = ElbV2Service.requestedSubnets(memberList(p, "Subnets"), subnetMappingSubnetIds(p)); List securityGroups = memberList(p, "SecurityGroups"); Map tags = parseTags(p); LoadBalancer lb = service.createLoadBalancer(region, name, scheme, type, ipAddressType, - effectiveSubnets, securityGroups, tags); + subnets, securityGroups, tags); // return provisioning state in create response only LoadBalancer provisioning = shallowCopy(lb); @@ -261,13 +255,8 @@ public class ElbV2QueryHandler { private Response handleSetSubnets(MultivaluedMap p, String region) { String arn = p.getFirst("LoadBalancerArn"); - List subnets = memberList(p, "Subnets"); - List subnetMappings = subnetMappingSubnetIds(p); - if (!subnets.isEmpty() && !subnetMappings.isEmpty()) { - throw new AwsException("ValidationError", - "You can specify either subnets or subnet mappings, not both", 400); - } - service.setSubnets(region, arn, subnetMappings.isEmpty() ? subnets : subnetMappings); + List subnets = ElbV2Service.requestedSubnets(memberList(p, "Subnets"), subnetMappingSubnetIds(p)); + service.setSubnets(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 2a0fe66983..7a0c2f12bc 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 @@ -209,6 +209,19 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc // ── Load Balancers ──────────────────────────────────────────────────────── + /** + * The subnets a CreateLoadBalancer or SetSubnets request names: {@code Subnets}, or else the subnet + * of each {@code SubnetMappings} entry. The two are alternatives, so a request that names subnets + * both ways is refused with the error AWS gives; an empty one does not count. + */ + public static List requestedSubnets(List subnets, List mappingSubnetIds) { + if (!subnets.isEmpty() && !mappingSubnetIds.isEmpty()) { + throw new AwsException("ValidationError", + "You can specify either subnets or subnet mappings, not both", 400); + } + return mappingSubnetIds.isEmpty() ? subnets : mappingSubnetIds; + } + /** * Resolving the subnets and publishing the balancer happen under EC2's subnet lock, so a * DeleteSubnet cannot pass its dependency check in between and leave the balancer on a subnet @@ -242,6 +255,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc String id = randomHex16(); String arn = AwsArnUtils.Arn.of("elasticloadbalancing", region, regionResolver.getAccountId(), "loadbalancer/" + typePrefix + "/" + name + "/" + id).toString(); String dnsName = name + "-" + id + ".elb." + loadBalancerDnsSuffix(); + requireSubnets(lbType, subnets); String vpcId = resolveSubnetVpcId(region, lbType, subnets); LoadBalancer lb = new LoadBalancer(); @@ -256,7 +270,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc lb.setType(lbType); lb.setIpAddressType(ipType); lb.setRegion(region); - if (subnets != null) lb.setAvailabilityZones(resolveAvailabilityZones(region, subnets)); + lb.setAvailabilityZones(resolveAvailabilityZones(region, subnets)); if (securityGroups != null) lb.setSecurityGroups(new ArrayList<>(securityGroups)); regionLbs.put(arn, lb); @@ -268,6 +282,22 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc return lb; } + /** + * 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. + */ + private static void requireSubnets(String lbType, List 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); + } + } + /** * A subnet is in use while a load balancer is configured with it. Account-scoped through the * request-scoped storage, and a target group does not count: it pins nothing in AWS either. diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2AlbIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2AlbIntegrationTest.java index dd5437582d..8cda98fa20 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2AlbIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2AlbIntegrationTest.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.apigatewayv2; import com.sun.net.httpserver.HttpServer; +import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.testing.RealElbV2DataPlaneProfile; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; @@ -81,6 +82,8 @@ class ApiGatewayV2AlbIntegrationTest { .formParam("Name", "apigw-alb-test") .formParam("Type", "application") .formParam("Scheme", "internet-facing") + .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a")) + .formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b")) .header("Authorization", AUTH) .when() .post("/") 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.java index 3c64c875db..c28a9d58a5 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 @@ -22,7 +22,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * {@code SubnetId} is required in a load balancer's {@code SubnetMappings}. A mapping that names no * 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. + * {@code SubnetMappings} together fail it too, as ELBv2 takes one or the other, and so does a + * balancer with neither. */ @QuarkusTest class CloudFormationElbV2SubnetMappingsIntegrationTest { @@ -89,6 +90,40 @@ class CloudFormationElbV2SubnetMappingsIntegrationTest { } } + /** + * A balancer with neither {@code Subnets} nor {@code SubnetMappings}, left out or with the only + * mapping an {@code Fn::If} drops, fails the stack with CreateLoadBalancer's error for its type. + */ + @ParameterizedTest + @CsvSource(delimiter = '|', nullValues = "NONE", value = { + "network|NONE|At least one subnet must be specified", + "network|{\"Fn::If\": [\"Never\", {\"SubnetId\": {\"Ref\": \"SubnetA\"}}, {\"Ref\": \"AWS::NoValue\"}]}|At least one subnet must be specified", + "application|NONE|At least two subnets in two different Availability Zones must be specified" + }) + void aLoadBalancerWithNeitherSubnetsNorSubnetMappingsFailsTheStack(String type, String mappings, String reason) { + String suffix = Long.toString(System.nanoTime(), 36); + String stack = "lb-no-subnets-" + suffix; + String name = "lb-none-" + suffix; + String template = (mappings == null + ? template(name, "").replace(", \"SubnetMappings\": []", "") + : template(name, mappings)) + .replace("\"Type\": \"network\"", "\"Type\": \"" + type + "\""); + assertEquals(mappings != null, template.contains("SubnetMappings"), template); + assertTrue(template.contains("\"Type\": \"" + type + "\""), 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 reasons = XmlParser.extractAll(events, "ResourceStatusReason"); + assertTrue(reasons.stream().anyMatch(r -> r.contains(reason)), 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. */ @Test void aMappingAnFnIfDropsIsLeftOut() { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java index b1f3691d58..9603606d50 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java @@ -8096,12 +8096,14 @@ class CloudFormationIntegrationTest { @Test void updateStack_elbV2Listener_modifiesPort() { String stackName = "cfn-elbv2-update-stack"; + String subnetA = Ec2Service.defaultSubnetId("us-east-1", "a"); + String subnetB = Ec2Service.defaultSubnetId("us-east-1", "b"); String template = """ { "Resources": { "Alb": { "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer", - "Properties": { "Name": "cfn-upd-alb", "Type": "application" } + "Properties": { "Name": "cfn-upd-alb", "Type": "application", "Subnets": ["%s", "%s"] } }, "Listener": { "Type": "AWS::ElasticLoadBalancingV2::Listener", @@ -8132,7 +8134,7 @@ class CloudFormationIntegrationTest { .contentType("application/x-www-form-urlencoded") .formParam("Action", "CreateStack") .formParam("StackName", stackName) - .formParam("TemplateBody", template.formatted(80)) + .formParam("TemplateBody", template.formatted(subnetA, subnetB, 80)) .when() .post("/") .then() @@ -8164,7 +8166,7 @@ class CloudFormationIntegrationTest { .contentType("application/x-www-form-urlencoded") .formParam("Action", "UpdateStack") .formParam("StackName", stackName) - .formParam("TemplateBody", template.formatted(8080)) + .formParam("TemplateBody", template.formatted(subnetA, subnetB, 8080)) .when() .post("/") .then() @@ -8192,7 +8194,7 @@ class CloudFormationIntegrationTest { "Resources": { "Alb": { "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer", - "Properties": { "Name": "cfn-del-alb", "Type": "application" } + "Properties": { "Name": "cfn-del-alb", "Type": "application", "Subnets": ["%s", "%s"] } }, "Tg": { "Type": "AWS::ElasticLoadBalancingV2::TargetGroup", @@ -8217,7 +8219,7 @@ class CloudFormationIntegrationTest { } } } - """; + """.formatted(Ec2Service.defaultSubnetId("us-east-1", "a"), Ec2Service.defaultSubnetId("us-east-1", "b")); given() .contentType("application/x-www-form-urlencoded") 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 e08d1eac3e..dd7ddefd24 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 @@ -62,6 +62,8 @@ class ElbV2CfnProvisionerTest { "arn:aws:elasticloadbalancing:us-east-1:000000000000:listener/app/web/50dc6c495c0c9188/f2f7dc8efc522ab2"; private static final String RULE_ARN = LISTENER_ARN.replace(":listener/", ":listener-rule/") + "/9683b2d02a6cabee"; + private static final List TWO_SUBNETS = List.of("subnet-1", "subnet-2"); + private final ElbV2Service elb = mock(ElbV2Service.class); private final ElbV2CfnProvisioner provisioner = new ElbV2CfnProvisioner(elb); private final ObjectMapper mapper = new ObjectMapper(); @@ -84,6 +86,13 @@ class ElbV2CfnProvisionerTest { return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId); } + /** Load balancer properties given Subnets, which CreateLoadBalancer requires of every type. */ + private static ObjectNode onTwoSubnets(ObjectNode props) { + ArrayNode subnets = props.putArray("Subnets"); + TWO_SUBNETS.forEach(subnets::add); + return props; + } + private StackResource resource(String type, String logicalId) { StackResource r = new StackResource(); r.setLogicalId(logicalId); @@ -157,10 +166,10 @@ class ElbV2CfnProvisionerTest { @Test void anUnnamedLoadBalancerGetsAnElbSafeNameAndKeepsItOnUpdate() { - when(elb.createLoadBalancer(eq(REGION), anyString(), isNull(), isNull(), isNull(), anyList(), anyList(), any())) + when(elb.createLoadBalancer(eq(REGION), anyString(), isNull(), isNull(), isNull(), eq(TWO_SUBNETS), anyList(), any())) .thenAnswer(inv -> loadBalancer(inv.getArgument(1))); StackResource created = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb_With_Underscores"); - provisioner.provision(created, mapper.createObjectNode(), ctx()); + provisioner.provision(created, onTwoSubnets(mapper.createObjectNode()), ctx()); String generated = created.getAttributes().get("LoadBalancerName"); // 32 characters at most, [A-Za-z0-9-] only, so the underscores are stripped and the // descriptive part is cut to make room for the 8-character suffix. @@ -169,10 +178,10 @@ class ElbV2CfnProvisionerTest { StackResource updated = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb_With_Underscores"); updated.getAttributes().put("LoadBalancerName", generated); - provisioner.provision(updated, mapper.createObjectNode(), ctx(LB_ARN)); + provisioner.provision(updated, onTwoSubnets(mapper.createObjectNode()), ctx(LB_ARN)); verify(elb, org.mockito.Mockito.times(2)).createLoadBalancer(eq(REGION), eq(generated), isNull(), isNull(), - isNull(), anyList(), anyList(), any()); + isNull(), eq(TWO_SUBNETS), anyList(), any()); } @Test @@ -342,12 +351,12 @@ class ElbV2CfnProvisionerTest { void aRenamedLoadBalancerIsReplacedAndTheOldOneCleanedUpUnlessRetained() { LoadBalancer renamed = loadBalancer("web-v2"); renamed.setLoadBalancerArn(LB_ARN.replace("/web/", "/web-v2/")); - when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), anyList(), anyList(), any())) + when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), eq(TWO_SUBNETS), anyList(), any())) .thenReturn(renamed); StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb"); r.getAttributes().put("LoadBalancerName", "web"); - provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v2"), ctx(LB_ARN)); + provisioner.provision(r, onTwoSubnets(mapper.createObjectNode().put("Name", "web-v2")), ctx(LB_ARN)); assertEquals(renamed.getLoadBalancerArn(), r.getPhysicalId()); assertEquals(LB_ARN, provisioner.updateCleanupPhysicalId(r)); assertEquals(new UpdateCleanupResult(true, true, LB_ARN, 0, null), provisioner.completeUpdate(r)); @@ -356,7 +365,7 @@ class ElbV2CfnProvisionerTest { StackResource retained = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb"); retained.setUpdateReplacePolicy("Retain"); retained.getAttributes().put("LoadBalancerName", "web"); - provisioner.provision(retained, mapper.createObjectNode().put("Name", "web-v2"), ctx(LB_ARN)); + provisioner.provision(retained, onTwoSubnets(mapper.createObjectNode().put("Name", "web-v2")), ctx(LB_ARN)); assertNull(provisioner.updateCleanupPhysicalId(retained)); assertEquals(new UpdateCleanupResult(true, true, LB_ARN, 0, null), provisioner.completeUpdate(retained)); verify(elb, org.mockito.Mockito.times(1)).deleteLoadBalancer(REGION, LB_ARN); @@ -711,14 +720,14 @@ class ElbV2CfnProvisionerTest { void aRollbackWhoseDeleteFailsStillPointsTheResourceAtThePriorAndPropagates() { LoadBalancer renamed = loadBalancer("web-v2"); renamed.setLoadBalancerArn(LB_ARN.replace("/web/", "/web-v2/")); - when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), anyList(), anyList(), any())) + when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), eq(TWO_SUBNETS), anyList(), any())) .thenReturn(renamed); doThrow(new AwsException("ResourceInUse", "listeners attached", 400)) .when(elb).deleteLoadBalancer(REGION, renamed.getLoadBalancerArn()); StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb"); r.getAttributes().put("LoadBalancerName", "web"); r.getAttributes().put("DNSName", "web-123.us-east-1.elb.amazonaws.com"); - provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v2"), ctx(LB_ARN)); + provisioner.provision(r, onTwoSubnets(mapper.createObjectNode().put("Name", "web-v2")), ctx(LB_ARN)); AwsException e = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r)); assertEquals("ResourceInUse", e.getErrorCode()); @@ -743,12 +752,12 @@ class ElbV2CfnProvisionerTest { String orphanArn = LB_ARN.replace("/web/", "/web-v2/"); LoadBalancer renamed = loadBalancer("web-v2"); renamed.setLoadBalancerArn(orphanArn); - when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), anyList(), anyList(), any())) + when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), eq(TWO_SUBNETS), anyList(), any())) .thenReturn(renamed); doThrow(new AwsException("ResourceInUse", "listeners attached", 400)).when(elb).deleteLoadBalancer(REGION, orphanArn); StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb"); r.getAttributes().put("LoadBalancerName", "web"); - provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v2"), ctx(LB_ARN)); + provisioner.provision(r, onTwoSubnets(mapper.createObjectNode().put("Name", "web-v2")), ctx(LB_ARN)); assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r)); assertEquals(LB_ARN, r.getPhysicalId()); @@ -766,9 +775,9 @@ class ElbV2CfnProvisionerTest { // A later replacement adds the prior to the same list; the committed cleanup deletes both. LoadBalancer third = loadBalancer("web-v3"); third.setLoadBalancerArn(LB_ARN.replace("/web/", "/web-v3/")); - when(elb.createLoadBalancer(eq(REGION), eq("web-v3"), isNull(), isNull(), isNull(), anyList(), anyList(), any())) + when(elb.createLoadBalancer(eq(REGION), eq("web-v3"), isNull(), isNull(), isNull(), eq(TWO_SUBNETS), anyList(), any())) .thenReturn(third); - provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v3"), ctx(LB_ARN)); + provisioner.provision(r, onTwoSubnets(mapper.createObjectNode().put("Name", "web-v3")), ctx(LB_ARN)); org.mockito.Mockito.reset(elb); UpdateCleanupResult cleanup = provisioner.completeUpdate(r); assertTrue(cleanup.complete(), cleanup.toString()); @@ -783,18 +792,18 @@ class ElbV2CfnProvisionerTest { String orphanArn = LB_ARN.replace("/web/", "/web-v2/"); LoadBalancer renamed = loadBalancer("web-v2"); renamed.setLoadBalancerArn(orphanArn); - when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), anyList(), anyList(), any())) + when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), eq(TWO_SUBNETS), anyList(), any())) .thenReturn(renamed); doThrow(new AwsException("ResourceInUse", "listeners attached", 400)).when(elb).deleteLoadBalancer(REGION, orphanArn); StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb"); r.getAttributes().put("LoadBalancerName", "web"); - provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v2"), ctx(LB_ARN)); + provisioner.provision(r, onTwoSubnets(mapper.createObjectNode().put("Name", "web-v2")), ctx(LB_ARN)); assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r)); LoadBalancer third = loadBalancer("web-v3"); third.setLoadBalancerArn(LB_ARN.replace("/web/", "/web-v3/")); - when(elb.createLoadBalancer(eq(REGION), eq("web-v3"), isNull(), isNull(), isNull(), anyList(), anyList(), any())) + when(elb.createLoadBalancer(eq(REGION), eq("web-v3"), isNull(), isNull(), isNull(), eq(TWO_SUBNETS), anyList(), any())) .thenReturn(third); - provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v3"), ctx(LB_ARN)); + provisioner.provision(r, onTwoSubnets(mapper.createObjectNode().put("Name", "web-v3")), ctx(LB_ARN)); // The orphan keeps failing; the prior is deleted on the first pass all the same, and the // failing entry is reported with its own attempt count until the engine gives up. @@ -816,12 +825,12 @@ class ElbV2CfnProvisionerTest { String orphanArn = LB_ARN.replace("/web/", "/web-v2/"); LoadBalancer renamed = loadBalancer("web-v2"); renamed.setLoadBalancerArn(orphanArn); - when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), anyList(), anyList(), any())) + when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), eq(TWO_SUBNETS), anyList(), any())) .thenReturn(renamed); doThrow(new AwsException("ResourceInUse", "listeners attached", 400)).when(elb).deleteLoadBalancer(REGION, orphanArn); StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb"); r.getAttributes().put("LoadBalancerName", "web"); - provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v2"), ctx(LB_ARN)); + provisioner.provision(r, onTwoSubnets(mapper.createObjectNode().put("Name", "web-v2")), ctx(LB_ARN)); assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r)); // The orphan uses up its three attempts in a cleanup where it is the only entry. for (int i = 0; i < 3; i++) { @@ -832,9 +841,9 @@ class ElbV2CfnProvisionerTest { // A later replacement lists the prior beside the exhausted orphan; its delete fails once. LoadBalancer third = loadBalancer("web-v3"); third.setLoadBalancerArn(LB_ARN.replace("/web/", "/web-v3/")); - when(elb.createLoadBalancer(eq(REGION), eq("web-v3"), isNull(), isNull(), isNull(), anyList(), anyList(), any())) + when(elb.createLoadBalancer(eq(REGION), eq("web-v3"), isNull(), isNull(), isNull(), eq(TWO_SUBNETS), anyList(), any())) .thenReturn(third); - provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v3"), ctx(LB_ARN)); + provisioner.provision(r, onTwoSubnets(mapper.createObjectNode().put("Name", "web-v3")), ctx(LB_ARN)); doThrow(new AwsException("ResourceInUse", "listeners attached", 400)).when(elb).deleteLoadBalancer(REGION, LB_ARN); UpdateCleanupResult first = provisioner.completeUpdate(r); assertFalse(first.complete()); @@ -857,12 +866,12 @@ class ElbV2CfnProvisionerTest { String orphanArn = LB_ARN.replace("/web/", "/web-v2/"); LoadBalancer renamed = loadBalancer("web-v2"); renamed.setLoadBalancerArn(orphanArn); - when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), anyList(), anyList(), any())) + when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), eq(TWO_SUBNETS), anyList(), any())) .thenReturn(renamed); doThrow(new AwsException("ResourceInUse", "listeners attached", 400)).when(elb).deleteLoadBalancer(REGION, orphanArn); StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb"); r.getAttributes().put("LoadBalancerName", "web"); - provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v2"), ctx(LB_ARN)); + provisioner.provision(r, onTwoSubnets(mapper.createObjectNode().put("Name", "web-v2")), ctx(LB_ARN)); assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r)); provisioner.completeUpdate(r); diff --git a/src/test/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployEcsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployEcsIntegrationTest.java index bdba45b7bb..d947ade8d2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployEcsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/codedeploy/CodeDeployEcsIntegrationTest.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.codedeploy; +import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.*; @@ -38,6 +39,8 @@ class CodeDeployEcsIntegrationTest { .formParam("Version", "2015-12-01") .formParam("Name", "ecs-alb") .formParam("Type", "application") + .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a")) + .formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b")) .when() .post("/") .then() diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HttpsDataPlaneIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HttpsDataPlaneIntegrationTest.java index 9a7453f779..1ea4dc78b5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HttpsDataPlaneIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HttpsDataPlaneIntegrationTest.java @@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.acm.model.CertificateOptions; import io.github.hectorvent.floci.services.acm.model.CertificateStatus; import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm; import io.github.hectorvent.floci.services.acm.model.ValidationMethod; +import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.arc.ClientProxy; import io.quarkus.test.junit.QuarkusTest; @@ -1192,7 +1193,10 @@ class ElbV2HttpsDataPlaneIntegrationTest { try { Response created = given().header("Authorization", accountAuthorization(owner, "elasticloadbalancing")) .formParam("Action", "CreateLoadBalancer").formParam("Name", "https-scoped-iam") - .formParam("Type", "application").when().post("/").then().statusCode(200).extract().response(); + .formParam("Type", "application") + .formParam("Subnets.member.1", Ec2Service.defaultSubnetId(REGION, "a")) + .formParam("Subnets.member.2", Ec2Service.defaultSubnetId(REGION, "b")) + .when().post("/").then().statusCode(200).extract().response(); loadBalancer = new LoadBalancerRef( created.xmlPath().getString("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn"), created.xmlPath().getString("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.DNSName")); @@ -1533,6 +1537,8 @@ class ElbV2HttpsDataPlaneIntegrationTest { .formParam("Action", "CreateLoadBalancer") .formParam("Name", name) .formParam("Type", "application") + .formParam("Subnets.member.1", Ec2Service.defaultSubnetId(REGION, "a")) + .formParam("Subnets.member.2", Ec2Service.defaultSubnetId(REGION, "b")) .header("Authorization", AUTH) .when() .post("/") 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 463d0b9572..8864171720 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 @@ -2,10 +2,13 @@ package io.github.hectorvent.floci.services.elbv2; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.*; @@ -105,6 +108,8 @@ class ElbV2IntegrationTest { given() .formParam("Action", "CreateLoadBalancer") .formParam("Name", "my-test-lb") + .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a")) + .formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b")) .header("Authorization", AUTH) .when() .post("/") @@ -504,10 +509,12 @@ class ElbV2IntegrationTest { .extract() .path("CreateSubnetResponse.subnet.subnetId"); - String subnetlessLbArn = given() + String duplicateAzLbArn = given() .formParam("Action", "CreateLoadBalancer") .formParam("Name", "set-duplicate-az-lb") .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) .when() .post("/") @@ -518,7 +525,7 @@ class ElbV2IntegrationTest { given() .formParam("Action", "SetSubnets") - .formParam("LoadBalancerArn", subnetlessLbArn) + .formParam("LoadBalancerArn", duplicateAzLbArn) .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a")) .formParam("Subnets.member.2", secondSubnetId) .header("Authorization", AUTH) @@ -529,9 +536,14 @@ class ElbV2IntegrationTest { .body("ErrorResponse.Error.Code", equalTo("InvalidConfigurationRequest")); } + /** + * A load balancer stays in the VPC it was created in. A balancer saved without one, before + * CreateLoadBalancer required subnets, takes the VPC of its first SetSubnets instead + * ({@code ElbV2ServiceTest}). + */ @Test @Order(15) - void setSubnetsAfterSubnetlessCreateCanAdoptCustomVpc() { + void setSubnetsInAnotherVpcIsRefused() { String customVpcId = given() .formParam("Action", "CreateVpc") .formParam("CidrBlock", "10.2.0.0/16") @@ -569,10 +581,12 @@ class ElbV2IntegrationTest { .extract() .path("CreateSubnetResponse.subnet.subnetId"); - String subnetlessLbArn = given() + String otherVpcLbArn = given() .formParam("Action", "CreateLoadBalancer") - .formParam("Name", "subnetless-adopt-vpc-lb") + .formParam("Name", "other-vpc-subnets-lb") .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) .when() .post("/") @@ -583,27 +597,29 @@ class ElbV2IntegrationTest { given() .formParam("Action", "SetSubnets") - .formParam("LoadBalancerArn", subnetlessLbArn) + .formParam("LoadBalancerArn", otherVpcLbArn) .formParam("Subnets.member.1", customSubnetAId) .formParam("Subnets.member.2", customSubnetBId) .header("Authorization", AUTH) .when() .post("/") .then() - .statusCode(200); + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidConfigurationRequest")) + .body("ErrorResponse.Error.Message", equalTo("All subnets must belong to the load balancer VPC.")); given() .formParam("Action", "DescribeLoadBalancers") - .formParam("LoadBalancerArns.member.1", subnetlessLbArn) + .formParam("LoadBalancerArns.member.1", otherVpcLbArn) .header("Authorization", AUTH) .when() .post("/") .then() .statusCode(200) .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.VpcId", - equalTo(customVpcId)) - .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.AvailabilityZones.member.size()", - equalTo(2)); + equalTo(Ec2Service.defaultVpcId("us-east-1"))) + .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.AvailabilityZones.member.SubnetId", + contains(Ec2Service.defaultSubnetId("us-east-1", "a"), Ec2Service.defaultSubnetId("us-east-1", "b"))); } @Test @@ -1279,6 +1295,8 @@ class ElbV2IntegrationTest { .formParam("Action", "CreateLoadBalancer") .formParam("Name", "lb-set-subnets") .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) .when() .post("/") @@ -1298,4 +1316,89 @@ class ElbV2IntegrationTest { .statusCode(400) .body("ErrorResponse.Error.Code", equalTo("SubnetNotFound")); } + + /** + * 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 + * Application or a Network Load Balancer; a Gateway Load Balancer gets the Network one. + */ + @ParameterizedTest + @CsvSource(delimiter = '|', nullValues = "NONE", value = { + "NONE|At least two subnets in two different Availability Zones must be specified", + "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" + }) + @Order(76) + void createLoadBalancerWithNeitherSubnetsNorSubnetMappingsIsRefused(String type, String message) { + String name = "no-subnets-" + (type == null ? "default" : type); + RequestSpecification request = given() + .formParam("Action", "CreateLoadBalancer") + .formParam("Name", name) + .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(message)); + + given() + .formParam("Action", "DescribeLoadBalancers") + .formParam("Names.member.1", name) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("LoadBalancerNotFound")); + } + + /** SetSubnets takes one or the other as well: both are refused and the balancer keeps its subnets. */ + @Test + @Order(77) + void setSubnetsRejectsBothSubnetsAndSubnetMappings() { + String bothFormsLbArn = given() + .formParam("Action", "CreateLoadBalancer") + .formParam("Name", "set-both-subnet-forms") + .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) + .when() + .post("/") + .then() + .statusCode(200) + .extract() + .path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn"); + + given() + .formParam("Action", "SetSubnets") + .formParam("LoadBalancerArn", bothFormsLbArn) + .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "b")) + .formParam("SubnetMappings.member.1.SubnetId", Ec2Service.defaultSubnetId("us-east-1", "c")) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", + equalTo("You can specify either subnets or subnet mappings, not both")); + + given() + .formParam("Action", "DescribeLoadBalancers") + .formParam("LoadBalancerArns.member.1", bothFormsLbArn) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.AvailabilityZones.member.SubnetId", + contains(Ec2Service.defaultSubnetId("us-east-1", "a"), Ec2Service.defaultSubnetId("us-east-1", "b"))); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2LambdaTargetDataPlaneIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2LambdaTargetDataPlaneIntegrationTest.java index bccf2fdef2..b4c1f64f68 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2LambdaTargetDataPlaneIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2LambdaTargetDataPlaneIntegrationTest.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.elbv2; +import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.testing.RealElbV2DataPlaneProfile; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; @@ -105,6 +106,8 @@ class ElbV2LambdaTargetDataPlaneIntegrationTest { .formParam("Action", "CreateLoadBalancer") .formParam("Name", "alb-dataplane-lb") .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) .when() .post("/") diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2LambdaTargetIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2LambdaTargetIntegrationTest.java index 6bb1aaf01c..860cd0a4d3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2LambdaTargetIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2LambdaTargetIntegrationTest.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.elbv2; +import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; @@ -53,6 +54,8 @@ class ElbV2LambdaTargetIntegrationTest { .formParam("Action", "CreateLoadBalancer") .formParam("Name", "lambda-target-lb") .formParam("Type", "application") + .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a")) + .formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b")) .formParam("Scheme", "internet-facing") .header("Authorization", AUTH) .when() diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2PreserveHostHeaderIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2PreserveHostHeaderIntegrationTest.java index 043d87aef0..4afcccb7f0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2PreserveHostHeaderIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2PreserveHostHeaderIntegrationTest.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.elbv2; +import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.testing.RealElbV2DataPlaneProfile; import io.github.hectorvent.floci.testutil.FreePorts; import io.quarkus.test.junit.QuarkusTest; @@ -238,6 +239,8 @@ class ElbV2PreserveHostHeaderIntegrationTest { .formParam("Action", "CreateLoadBalancer") .formParam("Name", "preserve-host-header-lb") .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) .when() .post("/") diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2SamePortHostDispatchIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2SamePortHostDispatchIntegrationTest.java index 3b2dc01ac8..5c201ab112 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2SamePortHostDispatchIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2SamePortHostDispatchIntegrationTest.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.elbv2; +import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.testing.RealElbV2DataPlaneProfile; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; @@ -40,6 +41,8 @@ class ElbV2SamePortHostDispatchIntegrationTest { .formParam("Action", "CreateLoadBalancer") .formParam("Name", "same-port-first") .formParam("Type", "application") + .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a")) + .formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b")) .formParam("Scheme", "internet-facing") .header("Authorization", AUTH) .when() @@ -76,6 +79,8 @@ class ElbV2SamePortHostDispatchIntegrationTest { .formParam("Action", "CreateLoadBalancer") .formParam("Name", "same-port-second") .formParam("Type", "application") + .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a")) + .formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b")) .formParam("Scheme", "internet-facing") .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.java index e71c0340f7..868e98446a 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 @@ -13,7 +13,9 @@ import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ec2.model.Subnet; import io.github.hectorvent.floci.services.elbv2.model.Action; +import io.github.hectorvent.floci.services.elbv2.model.AvailabilityZone; import io.github.hectorvent.floci.services.elbv2.model.Listener; +import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer; import io.github.hectorvent.floci.services.elbv2.model.Rule; import io.github.hectorvent.floci.services.elbv2.model.RuleCondition; import io.github.hectorvent.floci.services.elbv2.model.TargetDescription; @@ -24,6 +26,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.NullAndEmptySource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; @@ -32,6 +35,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import java.nio.file.Path; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -97,6 +101,59 @@ class ElbV2ServiceTest { stubAlbSubnets(ec2Service); } + /** + * Every type takes Subnets or SubnetMappings, so a balancer with neither is refused before a + * subnet is looked up or anything is stored. The messages are the ones AWS gives an Application + * or a Network Load Balancer; a Gateway Load Balancer gets the Network one. + */ + @ParameterizedTest + @CsvSource(delimiter = '|', nullValues = "NONE", value = { + "NONE|At least two subnets in two different Availability Zones must be specified", + "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 createLoadBalancerWithoutSubnetsIsRefused(String type, String message) { + for (List subnets : Arrays.>asList(null, List.of())) { + AwsException refusal = assertThrows(AwsException.class, () -> service.createLoadBalancer(REGION, + "no-subnets", null, type, null, subnets, List.of(), Map.of())); + assertEquals("ValidationError", refusal.getErrorCode()); + assertEquals(message, refusal.getMessage()); + assertEquals(400, refusal.getHttpStatus()); + } + assertTrue(service.describeLoadBalancers(REGION, null, null, null, null).isEmpty()); + verify(ec2Service, never()).describeSubnets(anyString(), anyList(), any()); + } + + /** + * 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. + */ + @Test + void requestedSubnetsAreTheSubnetsOrTheMappingsNotBoth() { + assertEquals(List.of("subnet-a"), ElbV2Service.requestedSubnets(List.of("subnet-a"), List.of())); + assertEquals(List.of("subnet-b"), ElbV2Service.requestedSubnets(List.of(), List.of("subnet-b"))); + assertEquals(List.of(), ElbV2Service.requestedSubnets(List.of(), List.of())); + AwsException both = assertThrows(AwsException.class, + () -> ElbV2Service.requestedSubnets(List.of("subnet-a"), List.of("subnet-b"))); + assertEquals("ValidationError", both.getErrorCode()); + assertEquals("You can specify either subnets or subnet mappings, not both", both.getMessage()); + assertEquals(400, both.getHttpStatus()); + } + + /** + * A taken name is reported before missing subnets: a CloudFormation stack update finds the + * balancer it keeps through DuplicateLoadBalancerName, whatever subnets its template names. + */ + @Test + void aTakenNameIsReportedBeforeMissingSubnets() { + service.createLoadBalancer(REGION, "taken", "internal", "application", "ipv4", ALB_SUBNETS, List.of(), + Map.of()); + AwsException refusal = assertThrows(AwsException.class, () -> service.createLoadBalancer(REGION, + "taken", "internal", "application", "ipv4", List.of(), List.of(), Map.of())); + assertEquals("DuplicateLoadBalancerName", refusal.getErrorCode()); + } + @ParameterizedTest @NullAndEmptySource void httpsCreateNeedsADefaultBeforeAllocatingAListener(List certificates) { @@ -835,4 +892,30 @@ class ElbV2ServiceTest { assertEquals(targetGroup, afterDelete.describeTargetGroups(REGION, null, List.of(targetGroup), null).getFirst().getTargetGroupArn()); } + + /** + * A balancer saved before CreateLoadBalancer required subnets has no zones and no VPC. Its first + * SetSubnets gives it both, taking the VPC of those subnets, since it has none of its own to keep. + */ + @Test + void aBalancerSavedWithoutSubnetsTakesTheVpcOfItsFirstSetSubnets() { + LoadBalancer saved = service.createLoadBalancer(REGION, "saved-subnetless", "internal", "application", + "ipv4", ALB_SUBNETS, List.of(), Map.of()); + saved.setAvailabilityZones(new ArrayList<>()); + saved.setVpcId(null); + Subnet subnetC = subnet("subnet-c", REGION + "a"); + subnetC.setVpcId("vpc-b"); + Subnet subnetD = subnet("subnet-d", REGION + "b"); + subnetD.setVpcId("vpc-b"); + when(ec2Service.describeSubnets(REGION, List.of("subnet-c", "subnet-d"), Map.of())) + .thenReturn(List.of(subnetC, subnetD)); + + service.setSubnets(REGION, saved.getLoadBalancerArn(), List.of("subnet-c", "subnet-d")); + + LoadBalancer moved = service.describeLoadBalancers(REGION, List.of(saved.getLoadBalancerArn()), null, + null, null).getFirst(); + assertEquals("vpc-b", moved.getVpcId()); + assertEquals(List.of("subnet-c", "subnet-d"), + moved.getAvailabilityZones().stream().map(AvailabilityZone::getSubnetId).toList()); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2StickinessIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2StickinessIntegrationTest.java index a2b69c6ddc..afc7264c71 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2StickinessIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2StickinessIntegrationTest.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.elbv2; +import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.testing.RealElbV2DataPlaneProfile; import io.github.hectorvent.floci.testutil.FreePorts; import io.quarkus.test.junit.QuarkusTest; @@ -47,7 +48,9 @@ class ElbV2StickinessIntegrationTest { first = backend("first"); second = backend("second"); listenerPort = FreePorts.anyInterfacePort(); - loadBalancerArn = query("CreateLoadBalancer", "Name", "sticky-lb", "Type", "application") + loadBalancerArn = query("CreateLoadBalancer", "Name", "sticky-lb", "Type", "application", + "Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a"), + "Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b")) .xmlPath().getString("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn"); targetGroupArn = query("CreateTargetGroup", "Name", "sticky-tg", "Protocol", "HTTP", "Port", first.actualPort(), "TargetType", "ip", "HealthCheckPath", "/health", diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2WebSocketIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2WebSocketIntegrationTest.java index 32a1884a76..11cffe29e0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2WebSocketIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2WebSocketIntegrationTest.java @@ -276,6 +276,8 @@ class ElbV2WebSocketIntegrationTest { .formParam("Action", "CreateLoadBalancer") .formParam("Name", "websocket-lb") .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) .when() .post("/")