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>
This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-20 13:08:31 -04:00
1 parent 484255871e
commit a434e52892
23 files changed
+413 -76

No files matched your search

@@ -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("/")
@@ -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<String> 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() {
@@ -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")
@@ -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<String> 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);
@@ -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()
@@ -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("/")
@@ -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")));
}
}
@@ -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("/")
@@ -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()
@@ -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("/")
@@ -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()
@@ -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<String> subnets : Arrays.<List<String>>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<String> 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());
}
}
@@ -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",
@@ -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("/")