fix(elb): route Classic (v1) requests to a dedicated handler instead of ELBv2 (#2619)

* feat(elb): implement Classic (v1) Elastic Load Balancing

Classic ELB (2012-06-01) and ELBv2 (2015-12-01) share an endpoint host and
an `elasticloadbalancing` credential scope, but they are different APIs. Every
Classic request was reaching the ELBv2 handler, which rejected a well-formed
one with `ValidationError: Name is required for load balancer.` — because the
name arrived as `LoadBalancerName`, the Classic parameter — and answered a
request that guessed `Name` with an ALB object in the 2015-12-01 namespace, a
shape Classic has no concept of.

Route on the API version. Every Query-protocol request carries the version it
speaks as the `Version` form parameter, and both service models declare it, so
that is the discriminator: 2012-06-01 to the new Classic handler, 2015-12-01 to
ELBv2. This is the same in-case split the `rds` scope already uses to separate
RDS, Neptune and DocumentDB. Requests that omit `Version` fall back to their
parameter shape — an action unique to one API, else `LoadBalancerName` /
`LoadBalancerNames` selecting Classic, else ELBv2 as before.

Classic state is its own model, not the v2 one: keyed by name, no ARN, listeners
inline, and one structured attribute record. Responses follow the 2012-06-01
model's wrapper and element names — `CreateLoadBalancerResult` carries `DNSName`
and nothing else.

Scope is what the AWS provider drives for `aws_elb` and for an Auto Scaling
group attached to one: Create/Delete/DescribeLoadBalancers, the listener
operations, ConfigureHealthCheck, Register/DeregisterInstances,
DescribeInstanceHealth, Modify/DescribeLoadBalancerAttributes, the subnet,
availability-zone and security-group operations, and tagging. The stickiness
and backend-server policy operations, and SetLoadBalancerListenerSSLCertificate,
answer `UnsupportedOperation` in the 2012-06-01 namespace rather than a
fabricated result. There is no Classic data plane: listener ports are recorded
but no socket is opened.

Health is checked per instance from the single `HealthCheck.Target` string —
`HTTP:`/`HTTPS:` probed with a request, `TCP:`/`SSL:` by connecting — with the
same counters and thresholds ElbV2HealthChecker uses. An ASG naming Classic load
balancers in `LoadBalancerNames` now registers and deregisters its instances
with them, so a `min_elb_capacity` wait can be satisfied.

* docs(elb): register ElbClassicQueryHandler in services.yaml

Unblocks 'make docs-check', which fails on rebase without this — the
handler was never registered when the Classic ELB feature landed.

* fix(elb): register ElbClassicService for native init, deregister stale ASG instances from Classic ELBs

ElbClassicService's SecureRandom field wasn't declared under
--initialize-at-run-time, which fails GraalVM native image builds
(image-heap Random instances have cached seeds). Registers it
alongside the other services/*.Service entries in application.yml.

Also closes a gap Greptile flagged: removeStaleInstances() pruned an
ASG's dead instance references without deregistering them from target
groups or named Classic load balancers first, unlike the terminating-
and scale-in paths, leaving orphaned registrations visible through
DescribeLoadBalancers/DescribeInstanceHealth.

* fix(elb): return the documented 409 for a Classic multi-VPC subnet set

CreateLoadBalancer's own Errors table puts InvalidConfigurationRequest at HTTP
409; the Classic path raised it at 400. The error code was already right, so a
client that retries on 409 but fails hard on 400 got the wrong signal from the
one place the two can be told apart. Covered by a unit test that asserts the
status, not just the code.

Also from review: the empty-Listeners ValidationError carried a message copied
from an unrelated subnet/AZ check, and the new cross-reference to the Classic
docs page split elb.md's opening sentence mid-paragraph instead of following it.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-08-31 19:05:07 -04:00
1 parent a7b2b79492
commit afe26c6ad1
24 files changed
+2838 -6

No files matched your search

@@ -60,6 +60,7 @@ class EmulatorLifecycleTest {
@Mock private EmulatorConfig.ServicesConfig servicesConfig;
@Mock private EmulatorConfig.Ec2ServiceConfig ec2ServiceConfig;
@Mock private EmulatorConfig.ElbV2ServiceConfig elbv2ServiceConfig;
@Mock private EmulatorConfig.ElbServiceConfig elbServiceConfig;
@Mock private IamService iamService;
@Mock private EmulatorConfig.ElastiCacheServiceConfig elastiCacheServiceConfig;
@Mock private ElastiCacheService elastiCacheService;
@@ -77,6 +78,7 @@ class EmulatorLifecycleTest {
@Mock private io.github.hectorvent.floci.services.kinesisanalytics.container.FlinkContainerManager flinkContainerManager;
@Mock private RdsService rdsService;
@Mock private io.github.hectorvent.floci.services.elbv2.ElbV2Service elbV2Service;
@Mock private io.github.hectorvent.floci.services.elb.ElbClassicService elbClassicService;
@Mock private InitializationHooksRunner initializationHooksRunner;
@Mock private SqsEventSourcePoller sqsPoller;
@Mock private KinesisEventSourcePoller kinesisPoller;
@@ -102,6 +104,8 @@ class EmulatorLifecycleTest {
Mockito.lenient().when(elbv2ServiceConfig.enabled()).thenReturn(false);
Mockito.lenient().when(servicesConfig.elasticache()).thenReturn(elastiCacheServiceConfig);
Mockito.lenient().when(elastiCacheServiceConfig.enabled()).thenReturn(false);
Mockito.lenient().when(servicesConfig.elb()).thenReturn(elbServiceConfig);
Mockito.lenient().when(elbServiceConfig.enabled()).thenReturn(false);
Mockito.lenient().when(config.tls()).thenReturn(tlsConfig);
Mockito.lenient().when(tlsConfig.enabled()).thenReturn(false);
Mockito.lenient().when(config.port()).thenReturn(4566);
@@ -113,7 +117,7 @@ class EmulatorLifecycleTest {
elastiCacheProxyManager, rdsContainerManager, rdsProxyManager,
memoryDbContainerManager, memoryDbProxyManager,
docDbContainerManager, neptuneContainerManager, neptuneProxyManager,
rabbitMqManager, flinkContainerManager, rdsService, elbV2Service,
rabbitMqManager, flinkContainerManager, rdsService, elbV2Service, elbClassicService,
initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller,
pipesService, ec2MetadataServer, ecrRegistryManager, flociUiManager, initLifecycleState,
schemaCreationWorker, containerTeardowns, persistentPathValidator);
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
import io.github.hectorvent.floci.services.ec2.model.Reservation;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import io.github.hectorvent.floci.services.elb.ElbClassicService;
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
import io.github.hectorvent.floci.services.elbv2.model.TargetDescription;
import io.github.hectorvent.floci.services.elbv2.model.TargetHealth;
@@ -386,7 +387,7 @@ class AutoScalingReconcilerTest {
ElbV2Service elbV2Service = mock(ElbV2Service.class);
SsmCommandService ssmCommandService = mock(SsmCommandService.class);
AutoScalingReconciler reconciler = new AutoScalingReconciler(
asgService, ec2Service, elbV2Service, ssmCommandService);
asgService, ec2Service, elbV2Service, null, ssmCommandService);
AutoScalingGroup asg = new AutoScalingGroup();
asg.setRegion("us-east-1");
asg.setAutoScalingGroupName("app-asg");
@@ -409,6 +410,29 @@ class AutoScalingReconcilerTest {
verify(ssmCommandService).failActiveInvocationsForInstances("us-east-1", Set.of("i-dead"), "Undeliverable");
}
@Test
void reconcileDeregistersStaleInstanceFromClassicLoadBalancerBeforePruning() {
AutoScalingService asgService = mock(AutoScalingService.class);
Ec2Service ec2Service = mock(Ec2Service.class);
ElbV2Service elbV2Service = mock(ElbV2Service.class);
ElbClassicService elbClassicService = mock(ElbClassicService.class);
AutoScalingReconciler reconciler = new AutoScalingReconciler(
asgService, ec2Service, elbV2Service, elbClassicService, null);
AutoScalingGroup asg = new AutoScalingGroup();
asg.setRegion("us-east-1");
asg.setAutoScalingGroupName("app-asg");
asg.setDesiredCapacity(0);
asg.setLoadBalancerNames(List.of("classic-lb"));
asg.getInstances().add(instance("i-dead", "InService"));
when(ec2Service.isInstanceContainerRunning("i-dead")).thenReturn(false);
reconciler.reconcile(asg);
assertEquals(0, asg.getInstances().size());
verify(elbClassicService).deregisterInstances(
eq(asg.getRegion()), eq("classic-lb"), eq(List.of("i-dead")));
}
@Test
void reconcilePromotesPendingAsgInstanceWhenEc2InstanceIsRunning() {
AutoScalingService asgService = mock(AutoScalingService.class);
@@ -0,0 +1,50 @@
package io.github.hectorvent.floci.services.elb;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* The Classic {@code HealthCheck.Target} grammar — one string carrying protocol, port and, for the
* HTTP protocols, a path. ELBv2 splits these across three members, which is why this parsing
* exists at all.
*/
class ElbClassicHealthCheckTargetTest {
@Test
void httpTargetCarriesItsPath() {
ElbClassicHealthChecker.Target target = ElbClassicHealthChecker.Target.parse("HTTP:8080/health");
assertEquals("http", target.scheme());
assertEquals(8080, target.port());
assertEquals("/health", target.path());
}
@Test
void httpTargetWithNoPathDefaultsToRoot() {
ElbClassicHealthChecker.Target target = ElbClassicHealthChecker.Target.parse("HTTP:80");
assertEquals("/", target.path());
}
@Test
void tcpTargetHasNoPathAndSoIsProbedByConnection() {
ElbClassicHealthChecker.Target target = ElbClassicHealthChecker.Target.parse("TCP:8080");
assertNull(target.path());
assertNull(target.scheme());
assertEquals(8080, target.port());
}
@Test
void sslTargetIsAConnectionProbeToo() {
assertNull(ElbClassicHealthChecker.Target.parse("SSL:443").path());
}
@Test
void malformedTargetsAreRejectedRatherThanGuessed() {
assertNull(ElbClassicHealthChecker.Target.parse(null));
assertNull(ElbClassicHealthChecker.Target.parse(""));
assertNull(ElbClassicHealthChecker.Target.parse("HTTP"));
assertNull(ElbClassicHealthChecker.Target.parse("HTTP:notaport/"));
assertNull(ElbClassicHealthChecker.Target.parse("GOPHER:70/"));
}
}
@@ -0,0 +1,571 @@
package io.github.hectorvent.floci.services.elb;
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;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Classic (2012-06-01) Elastic Load Balancing over the Query protocol.
*
* <p>Classic ELB and ELBv2 share one endpoint host and one credential scope, so these tests also
* pin the routing: a request declaring {@code Version=2012-06-01} must be answered by the Classic
* implementation, in the 2012-06-01 namespace, and one declaring {@code Version=2015-12-01} must
* still reach ELBv2.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ElbClassicIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260427/us-east-1/elasticloadbalancing/aws4_request";
private static final String V1 = "2012-06-01";
private static final String V2 = "2015-12-01";
private static final String CLASSIC_XMLNS =
"http://elasticloadbalancing.amazonaws.com/doc/2012-06-01/";
private static final String V2_XMLNS =
"https://elasticloadbalancing.amazonaws.com/doc/2015-12-01/";
private static final String LB = "classic-elb-1";
private static String subnetA() { return Ec2Service.defaultSubnetId("us-east-1", "a"); }
@Test
@Order(1)
void createLoadBalancerAnswersTheClassicApiNotTheV2One() {
String body = given()
.formParam("Action", "CreateLoadBalancer")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.formParam("Scheme", "internet-facing")
.formParam("Subnets.member.1", subnetA())
.formParam("SecurityGroups.member.1", "sg-classic")
.formParam("Listeners.member.1.Protocol", "HTTP")
.formParam("Listeners.member.1.LoadBalancerPort", "80")
.formParam("Listeners.member.1.InstanceProtocol", "HTTP")
.formParam("Listeners.member.1.InstancePort", "8080")
.formParam("Tags.member.1.Key", "gw:example")
.formParam("Tags.member.1.Value", "with-elb")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body("CreateLoadBalancerResponse.CreateLoadBalancerResult.DNSName",
containsString(LB + "-"))
.extract().asString();
// The two defects this fixes: wrong namespace, and an ELBv2 object in a Classic reply.
assertTrue(body.contains("xmlns=\"" + CLASSIC_XMLNS + "\""),
"Classic response must declare the 2012-06-01 namespace: " + body);
assertFalse(body.contains(V2_XMLNS),
"Classic response must not be in the 2015-12-01 namespace: " + body);
assertFalse(body.contains("LoadBalancerArn"),
"Classic load balancers have no ARN: " + body);
assertFalse(body.contains("<LoadBalancers>"),
"CreateLoadBalancerResult carries DNSName only, never a LoadBalancers list: " + body);
}
@Test
@Order(2)
void loadBalancerNameIsAcceptedRatherThanRejectedAsMissing() {
// The reported symptom: 'Name is required for load balancer.' for a well-formed v1 request.
given()
.formParam("Action", "CreateLoadBalancer")
.formParam("Version", V1)
.formParam("LoadBalancerName", "classic-elb-name-ok")
.formParam("Listeners.member.1.Protocol", "TCP")
.formParam("Listeners.member.1.LoadBalancerPort", "443")
.formParam("Listeners.member.1.InstancePort", "443")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateLoadBalancerResponse.CreateLoadBalancerResult.DNSName",
containsString("classic-elb-name-ok-"));
given()
.formParam("Action", "DeleteLoadBalancer")
.formParam("Version", V1)
.formParam("LoadBalancerName", "classic-elb-name-ok")
.header("Authorization", AUTH)
.when().post("/").then().statusCode(200);
}
@Test
@Order(3)
void createRejectsARequestWithNoListeners() {
given()
.formParam("Action", "CreateLoadBalancer")
.formParam("Version", V1)
.formParam("LoadBalancerName", "classic-no-listeners")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
// Not "Name is required for load balancer." — that is the v2 handler's message,
// and seeing it here means a v1 request reached the wrong API again.
.body("ErrorResponse.Error.Message", containsString("listener"));
}
@Test
@Order(4)
void duplicateNameIsRejected() {
given()
.formParam("Action", "CreateLoadBalancer")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.formParam("Listeners.member.1.Protocol", "HTTP")
.formParam("Listeners.member.1.LoadBalancerPort", "80")
.formParam("Listeners.member.1.InstancePort", "8080")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("DuplicateLoadBalancerName"));
}
@Test
@Order(5)
void describeLoadBalancersReturnsTheClassicDescriptionShape() {
String body = given()
.formParam("Action", "DescribeLoadBalancers")
.formParam("Version", V1)
.formParam("LoadBalancerNames.member.1", LB)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult"
+ ".LoadBalancerDescriptions.member.LoadBalancerName", equalTo(LB))
.body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult"
+ ".LoadBalancerDescriptions.member.Scheme", equalTo("internet-facing"))
.body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult"
+ ".LoadBalancerDescriptions.member.Subnets.member", equalTo(subnetA()))
.body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult"
+ ".LoadBalancerDescriptions.member.SecurityGroups.member",
equalTo("sg-classic"))
.body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult"
+ ".LoadBalancerDescriptions.member.ListenerDescriptions.member"
+ ".Listener.InstancePort", equalTo("8080"))
.body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult"
+ ".LoadBalancerDescriptions.member.HealthCheck.Target", equalTo("TCP:80"))
.extract().asString();
assertTrue(body.contains("xmlns=\"" + CLASSIC_XMLNS + "\""), body);
assertFalse(body.contains("LoadBalancerArn"), body);
}
@Test
@Order(6)
void describeUnknownLoadBalancerIsNotFound() {
given()
.formParam("Action", "DescribeLoadBalancers")
.formParam("Version", V1)
.formParam("LoadBalancerNames.member.1", "no-such-elb")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("LoadBalancerNotFound"));
}
@Test
@Order(7)
void configureHealthCheckStoresAndEchoesTheCheck() {
given()
.formParam("Action", "ConfigureHealthCheck")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.formParam("HealthCheck.Target", "HTTP:8080/")
.formParam("HealthCheck.Interval", "10")
.formParam("HealthCheck.Timeout", "3")
.formParam("HealthCheck.HealthyThreshold", "2")
.formParam("HealthCheck.UnhealthyThreshold", "2")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("ConfigureHealthCheckResponse.ConfigureHealthCheckResult.HealthCheck.Target",
equalTo("HTTP:8080/"))
.body("ConfigureHealthCheckResponse.ConfigureHealthCheckResult.HealthCheck.Interval",
equalTo("10"));
}
@Test
@Order(8)
void configureHealthCheckRejectsAnIntervalOutsideTheModelRange() {
given()
.formParam("Action", "ConfigureHealthCheck")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.formParam("HealthCheck.Target", "HTTP:8080/")
.formParam("HealthCheck.Interval", "1")
.formParam("HealthCheck.Timeout", "3")
.formParam("HealthCheck.HealthyThreshold", "2")
.formParam("HealthCheck.UnhealthyThreshold", "2")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
}
@Test
@Order(9)
void registerDescribeAndDeregisterInstances() {
given()
.formParam("Action", "RegisterInstancesWithLoadBalancer")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.formParam("Instances.member.1.InstanceId", "i-1111111111111111a")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("RegisterInstancesWithLoadBalancerResponse"
+ ".RegisterInstancesWithLoadBalancerResult.Instances.member.InstanceId",
equalTo("i-1111111111111111a"));
given()
.formParam("Action", "DescribeInstanceHealth")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeInstanceHealthResponse.DescribeInstanceHealthResult"
+ ".InstanceStates.member.InstanceId", equalTo("i-1111111111111111a"))
.body("DescribeInstanceHealthResponse.DescribeInstanceHealthResult"
+ ".InstanceStates.member.State", equalTo("InService"));
given()
.formParam("Action", "DeregisterInstancesFromLoadBalancer")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.formParam("Instances.member.1.InstanceId", "i-1111111111111111a")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("DeregisterInstancesFromLoadBalancerResponse"
+ ".DeregisterInstancesFromLoadBalancerResult.Instances", equalTo(""));
}
@Test
@Order(10)
void describeInstanceHealthRejectsAnUnregisteredInstance() {
given()
.formParam("Action", "DescribeInstanceHealth")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.formParam("Instances.member.1.InstanceId", "i-not-registered")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInstance"));
}
@Test
@Order(11)
void modifyAndDescribeAttributesRoundTrip() {
given()
.formParam("Action", "ModifyLoadBalancerAttributes")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.formParam("LoadBalancerAttributes.CrossZoneLoadBalancing.Enabled", "true")
.formParam("LoadBalancerAttributes.ConnectionDraining.Enabled", "true")
.formParam("LoadBalancerAttributes.ConnectionDraining.Timeout", "300")
.formParam("LoadBalancerAttributes.ConnectionSettings.IdleTimeout", "90")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("ModifyLoadBalancerAttributesResponse.ModifyLoadBalancerAttributesResult"
+ ".LoadBalancerName", equalTo(LB));
given()
.formParam("Action", "DescribeLoadBalancerAttributes")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeLoadBalancerAttributesResponse"
+ ".DescribeLoadBalancerAttributesResult.LoadBalancerAttributes"
+ ".CrossZoneLoadBalancing.Enabled", equalTo("true"))
.body("DescribeLoadBalancerAttributesResponse"
+ ".DescribeLoadBalancerAttributesResult.LoadBalancerAttributes"
+ ".ConnectionDraining.Timeout", equalTo("300"))
.body("DescribeLoadBalancerAttributesResponse"
+ ".DescribeLoadBalancerAttributesResult.LoadBalancerAttributes"
+ ".ConnectionSettings.IdleTimeout", equalTo("90"))
// Untouched members keep their AWS defaults rather than disappearing.
.body("DescribeLoadBalancerAttributesResponse"
+ ".DescribeLoadBalancerAttributesResult.LoadBalancerAttributes"
+ ".AccessLog.Enabled", equalTo("false"));
}
@Test
@Order(12)
void listenersCanBeAddedAndRemoved() {
given()
.formParam("Action", "CreateLoadBalancerListeners")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.formParam("Listeners.member.1.Protocol", "TCP")
.formParam("Listeners.member.1.LoadBalancerPort", "8443")
.formParam("Listeners.member.1.InstancePort", "8443")
.header("Authorization", AUTH)
.when().post("/").then().statusCode(200);
given()
.formParam("Action", "DescribeLoadBalancers")
.formParam("Version", V1)
.formParam("LoadBalancerNames.member.1", LB)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult"
+ ".LoadBalancerDescriptions.member.ListenerDescriptions.member"
+ ".Listener.LoadBalancerPort", hasItems("80", "8443"));
given()
.formParam("Action", "DeleteLoadBalancerListeners")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.formParam("LoadBalancerPorts.member.1", "8443")
.header("Authorization", AUTH)
.when().post("/").then().statusCode(200);
given()
.formParam("Action", "DescribeLoadBalancers")
.formParam("Version", V1)
.formParam("LoadBalancerNames.member.1", LB)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult"
+ ".LoadBalancerDescriptions.member.ListenerDescriptions.member"
+ ".Listener.LoadBalancerPort", equalTo("80"));
}
@Test
@Order(13)
void tagsRoundTripByLoadBalancerName() {
given()
.formParam("Action", "DescribeTags")
.formParam("Version", V1)
.formParam("LoadBalancerNames.member.1", LB)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeTagsResponse.DescribeTagsResult.TagDescriptions.member"
+ ".LoadBalancerName", equalTo(LB))
.body("DescribeTagsResponse.DescribeTagsResult.TagDescriptions.member"
+ ".Tags.member.Key", equalTo("gw:example"));
given()
.formParam("Action", "AddTags")
.formParam("Version", V1)
.formParam("LoadBalancerNames.member.1", LB)
.formParam("Tags.member.1.Key", "owner")
.formParam("Tags.member.1.Value", "harness")
.header("Authorization", AUTH)
.when().post("/").then().statusCode(200);
given()
.formParam("Action", "RemoveTags")
.formParam("Version", V1)
.formParam("LoadBalancerNames.member.1", LB)
.formParam("Tags.member.1.Key", "gw:example")
.header("Authorization", AUTH)
.when().post("/").then().statusCode(200);
given()
.formParam("Action", "DescribeTags")
.formParam("Version", V1)
.formParam("LoadBalancerNames.member.1", LB)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeTagsResponse.DescribeTagsResult.TagDescriptions.member"
+ ".Tags.member.Key", equalTo("owner"));
}
@Test
@Order(14)
void subnetAndSecurityGroupChangesRoundTrip() {
given()
.formParam("Action", "AttachLoadBalancerToSubnets")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "b"))
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("AttachLoadBalancerToSubnetsResponse.AttachLoadBalancerToSubnetsResult"
+ ".Subnets.member", hasItems(subnetA(),
Ec2Service.defaultSubnetId("us-east-1", "b")));
given()
.formParam("Action", "DetachLoadBalancerFromSubnets")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "b"))
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("DetachLoadBalancerFromSubnetsResponse.DetachLoadBalancerFromSubnetsResult"
+ ".Subnets.member", equalTo(subnetA()));
given()
.formParam("Action", "ApplySecurityGroupsToLoadBalancer")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.formParam("SecurityGroups.member.1", "sg-replaced")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("ApplySecurityGroupsToLoadBalancerResponse"
+ ".ApplySecurityGroupsToLoadBalancerResult.SecurityGroups.member",
equalTo("sg-replaced"));
}
@Test
@Order(15)
void unimplementedClassicPolicyOperationsSaySoInTheClassicNamespace() {
String body = given()
.formParam("Action", "CreateLBCookieStickinessPolicy")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.formParam("PolicyName", "stickiness")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("UnsupportedOperation"))
.extract().asString();
assertTrue(body.contains(CLASSIC_XMLNS), body);
}
@Test
@Order(16)
void aRequestWithoutAVersionRoutesOnItsParameterShape() {
// A hand-rolled client that omitted Version but named a load balancer is Classic.
given()
.formParam("Action", "DescribeLoadBalancers")
.formParam("LoadBalancerNames.member.1", LB)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult"
+ ".LoadBalancerDescriptions.member.LoadBalancerName", equalTo(LB));
}
@Test
@Order(17)
void elbV2RequestsStillReachTheV2Handler() {
String body = given()
.formParam("Action", "CreateLoadBalancer")
.formParam("Version", V2)
.formParam("Name", "v2-still-works")
.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)
.body("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member"
+ ".LoadBalancerName", equalTo("v2-still-works"))
.extract().asString();
assertTrue(body.contains(V2_XMLNS), body);
given()
.formParam("Action", "DescribeLoadBalancers")
.formParam("Version", V2)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers"
+ ".member.LoadBalancerName", not(hasItems(LB)));
}
@Test
@Order(18)
void deleteRemovesTheClassicLoadBalancerAndIsIdempotent() {
given()
.formParam("Action", "DeleteLoadBalancer")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.header("Authorization", AUTH)
.when().post("/").then().statusCode(200);
// AWS answers a delete of something already gone with success.
given()
.formParam("Action", "DeleteLoadBalancer")
.formParam("Version", V1)
.formParam("LoadBalancerName", LB)
.header("Authorization", AUTH)
.when().post("/").then().statusCode(200);
given()
.formParam("Action", "DescribeLoadBalancers")
.formParam("Version", V1)
.formParam("LoadBalancerNames.member.1", LB)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("LoadBalancerNotFound"));
}
}
@@ -0,0 +1,243 @@
package io.github.hectorvent.floci.services.elb;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
import io.github.hectorvent.floci.services.elb.model.ClassicHealthCheck;
import io.github.hectorvent.floci.services.elb.model.ClassicListener;
import io.github.hectorvent.floci.services.elb.model.ClassicLoadBalancer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class ElbClassicServiceTest {
private static final String REGION = "us-west-2";
@Mock
Ec2Service ec2Service;
@Mock
ElbClassicHealthChecker healthChecker;
private ElbClassicService service;
@BeforeEach
void setUp() {
service = new ElbClassicService(ec2Service, healthChecker, null, null);
lenient().when(ec2Service.describeSubnets(anyString(), anyList(), any()))
.thenAnswer(invocation -> {
List<String> ids = invocation.getArgument(1);
return ids.stream().map(id -> {
Subnet subnet = new Subnet();
subnet.setSubnetId(id);
subnet.setVpcId("vpc-1");
subnet.setAvailabilityZone(REGION + id.substring(id.length() - 1));
return subnet;
}).toList();
});
}
private static ClassicListener httpListener() {
ClassicListener listener = new ClassicListener();
listener.setProtocol("HTTP");
listener.setLoadBalancerPort(80);
listener.setInstanceProtocol("HTTP");
listener.setInstancePort(8080);
return listener;
}
private ClassicLoadBalancer create(String name) {
return service.createLoadBalancer(REGION, name, List.of(httpListener()),
List.of(), List.of("subnet-a"), List.of("sg-1"), null, Map.of());
}
@Test
void createGivesADnsNameAndTheAwsDefaultHealthCheck() {
ClassicLoadBalancer lb = create("my-elb");
assertTrue(lb.getDnsName().startsWith("my-elb-"));
assertEquals("internet-facing", lb.getScheme());
assertEquals("vpc-1", lb.getVpcId());
assertEquals(List.of(REGION + "a"), lb.getAvailabilityZones());
// AWS's documented defaults for a load balancer that has never been configured.
assertEquals("TCP:80", lb.getHealthCheck().getTarget());
assertEquals(30, lb.getHealthCheck().getInterval());
assertEquals(10, lb.getHealthCheck().getHealthyThreshold());
verify(healthChecker).startMonitoring(lb);
}
@Test
void createRejectsAMissingNameWithTheClassicParameterName() {
AwsException e = assertThrows(AwsException.class, () ->
service.createLoadBalancer(REGION, null, List.of(httpListener()),
List.of(), List.of(), List.of(), null, Map.of()));
assertEquals("ValidationError", e.getErrorCode());
assertTrue(e.getMessage().contains("LoadBalancerName"), e.getMessage());
}
@Test
void createRejectsAListenerMissingARequiredMember() {
ClassicListener incomplete = new ClassicListener();
incomplete.setProtocol("HTTP");
incomplete.setLoadBalancerPort(80);
AwsException e = assertThrows(AwsException.class, () ->
service.createLoadBalancer(REGION, "my-elb", List.of(incomplete),
List.of(), List.of(), List.of(), null, Map.of()));
assertEquals("ValidationError", e.getErrorCode());
}
@Test
void createRejectsAnEmptyListenerListNamingTheMissingMember() {
AwsException e = assertThrows(AwsException.class, () ->
service.createLoadBalancer(REGION, "my-elb", List.of(),
List.of(), List.of("subnet-a"), List.of("sg-1"), null, Map.of()));
assertEquals("ValidationError", e.getErrorCode());
assertTrue(e.getMessage().contains("listener"), e.getMessage());
}
/**
* CreateLoadBalancer's Errors table documents InvalidConfigurationRequest at HTTP 409, not
* 400 — a client that retries on 409 but fails hard on 400 depends on the difference.
*/
@Test
void subnetsSpanningTwoVpcsAreRejectedWithTheDocumentedStatus() {
when(ec2Service.describeSubnets(anyString(), anyList(), any()))
.thenAnswer(invocation -> {
List<String> ids = invocation.getArgument(1);
return ids.stream().map(id -> {
Subnet subnet = new Subnet();
subnet.setSubnetId(id);
subnet.setVpcId("vpc-" + id.charAt(id.length() - 1));
subnet.setAvailabilityZone(REGION + id.charAt(id.length() - 1));
return subnet;
}).toList();
});
AwsException e = assertThrows(AwsException.class, () ->
service.createLoadBalancer(REGION, "my-elb", List.of(httpListener()),
List.of(), List.of("subnet-a", "subnet-b"), List.of("sg-1"), null, Map.of()));
assertEquals("InvalidConfigurationRequest", e.getErrorCode());
assertEquals(409, e.getHttpStatus());
}
@Test
void createRejectsADuplicateName() {
create("my-elb");
AwsException e = assertThrows(AwsException.class, () -> create("my-elb"));
assertEquals("DuplicateLoadBalancerName", e.getErrorCode());
}
@Test
void loadBalancersAreScopedByRegion() {
create("my-elb");
assertTrue(service.hasLoadBalancer(REGION, "my-elb"));
assertTrue(service.describeLoadBalancers("eu-west-1", null).isEmpty());
}
@Test
void configureHealthCheckStoresAndRearmsTheChecker() {
ClassicLoadBalancer lb = create("my-elb");
ClassicHealthCheck hc = new ClassicHealthCheck();
hc.setTarget("HTTP:8080/health");
hc.setInterval(10);
hc.setTimeout(3);
hc.setHealthyThreshold(2);
hc.setUnhealthyThreshold(2);
service.configureHealthCheck(REGION, "my-elb", hc);
assertEquals("HTTP:8080/health", lb.getHealthCheck().getTarget());
verify(healthChecker).healthCheckChanged(lb);
}
@Test
void configureHealthCheckEnforcesTheRangesTheModelDeclares() {
create("my-elb");
ClassicHealthCheck hc = new ClassicHealthCheck();
hc.setTarget("HTTP:8080/");
hc.setInterval(301);
hc.setTimeout(3);
hc.setHealthyThreshold(2);
hc.setUnhealthyThreshold(2);
AwsException e = assertThrows(AwsException.class,
() -> service.configureHealthCheck(REGION, "my-elb", hc));
assertEquals("ValidationError", e.getErrorCode());
}
@Test
void registerAndDeregisterInstancesAreIdempotent() {
create("my-elb");
service.registerInstances(REGION, "my-elb", List.of("i-1"));
assertEquals(List.of("i-1"), service.registerInstances(REGION, "my-elb", List.of("i-1")));
assertEquals(List.of(), service.deregisterInstances(REGION, "my-elb", List.of("i-1")));
verify(healthChecker).deregisterInstances(REGION, "my-elb", List.of("i-1"));
}
@Test
void describeInstanceHealthRejectsAnInstanceThatIsNotRegistered() {
create("my-elb");
AwsException e = assertThrows(AwsException.class,
() -> service.describeInstanceHealth(REGION, "my-elb", List.of("i-unknown")));
assertEquals("InvalidInstance", e.getErrorCode());
}
@Test
void modifyAttributesLeavesUnsentMembersAtTheirDefaults() {
create("my-elb");
service.modifyLoadBalancerAttributes(REGION, "my-elb",
new ElbClassicService.AttributeUpdate(true, null, null, null, null,
true, 300, null, Map.of()));
ClassicLoadBalancer lb = service.requireLoadBalancer(REGION, "my-elb");
assertTrue(lb.getAttributes().isCrossZoneLoadBalancingEnabled());
assertTrue(lb.getAttributes().isConnectionDrainingEnabled());
assertEquals(300, lb.getAttributes().getConnectionDrainingTimeout());
assertEquals(60, lb.getAttributes().getIdleTimeout());
assertNull(lb.getAttributes().getAccessLogS3BucketName());
}
@Test
void deleteIsSilentForALoadBalancerThatDoesNotExist() {
service.deleteLoadBalancer(REGION, "never-existed");
assertThrows(AwsException.class, () -> service.requireLoadBalancer(REGION, "never-existed"));
}
@Test
void addingAConflictingListenerOnAPortInUseIsRejected() {
create("my-elb");
ClassicListener conflicting = new ClassicListener();
conflicting.setProtocol("TCP");
conflicting.setLoadBalancerPort(80);
conflicting.setInstancePort(9999);
AwsException e = assertThrows(AwsException.class, () ->
service.createLoadBalancerListeners(REGION, "my-elb", List.of(conflicting)));
assertEquals("DuplicateListener", e.getErrorCode());
}
@Test
void repeatingAnIdenticalListenerIsAccepted() {
ClassicLoadBalancer lb = create("my-elb");
service.createLoadBalancerListeners(REGION, "my-elb", List.of(httpListener()));
assertEquals(1, lb.getListeners().size());
}
}