fix(elbv2): support explicit ALB zone-rule overrides (#8533)

* fix(elbv2): apply regional ALB zone defaults with overrides
* fix(elbv2): restore legacy subnet snapshots during stack rollback
* fix(elbv2): require two ALB zones for the AWS default
* fix(elbv2): simplify explicit ALB zone rules
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-16 07:42:42 -04:00
1 parent bd3431283b
commit 4a5d5fbb49
12 files changed
+369 -23

No files matched your search

@@ -644,6 +644,7 @@ See [Web Console](../ui/index.md) for running the console and swapping in a thir
| `FLOCI_SERVICES_ROUTE53_ENABLED` | `true` | Enable the Route 53 service |
| `FLOCI_SERVICES_ROUTE53_VPC_ASSOCIATION_CONTROL_PLANE_DELAY_MS` | `0` | Simulated processing window for Route 53 VPC association/auth mutations; positive values make documented overlap errors (`PriorRequestNotComplete` / `ConcurrentModification`) reproducible for retry tests |
| `FLOCI_SERVICES_ELBV2_ENABLED` | `true` | Enable the ELBv2 (ALB/NLB) service |
| `FLOCI_SERVICES_ELBV2_ALB_ZONE_RULE` | `aws` | ALB minimum-zone policy: `aws` requires two distinct ordinary Availability Zones in every region; `allow-single-zone` explicitly permits one. Per-region YAML overrides take precedence. |
| `FLOCI_SERVICES_ELBV2_MOCK` | `false` | When `true`, load balancers are registered but no containers are spawned |
| `FLOCI_SERVICES_ELBV2_BACKEND_KEEP_ALIVE` | `true` | Reuse backend HTTP/1.x connections for ordinary HTTP forwarding. Set to `false` for fresh connections per request; WebSocket and TCP transports are unaffected. See [backend connection reuse](../services/elb.md#backend-connection-reuse) |
| `FLOCI_SERVICES_ELBV2_BACKEND_KEEP_ALIVE_TIMEOUT_SECONDS` | `60` | Default idle-pool timeout for backend HTTP/1.x connections, in non-negative seconds; `0` disables expiry. A target's advertised `Keep-Alive` timeout overrides it. Does not time out active responses or WebSockets |
+33 -2
View File
@@ -140,8 +140,8 @@ Gateway Load Balancer listeners require omitted `Port` and `Protocol` fields on
- HTTP or HTTPS 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. TCP never serves a port alongside either protocol; see the TCP note above.
- Load balancer, target group, listener, rule, and tag state is persisted through Floci storage and rebuilt on service startup.
- Load balancers are created in `active` state.
- `CreateLoadBalancer` takes `Subnets` or `SubnetMappings` for every load balancer type, and both together are refused with `ValidationError`. An Application Load Balancer takes at least two: with one or none it returns `ValidationError` `At least two subnets in two different Availability Zones must be specified` and creates nothing. The count comes before any subnet is looked up, as on AWS, so one subnet that does not exist gets that error too. A Network or Gateway Load Balancer with neither returns `ValidationError` `At least one subnet must be specified`. CloudFormation refuses such an `AWS::ElasticLoadBalancingV2::LoadBalancer` the same way when it creates or replaces the balancer; an update that keeps the balancer and names no subnets leaves it on its subnets.
- `SetSubnets`, like `CreateLoadBalancer`, takes `Subnets` or `SubnetMappings`, and both together are refused with `ValidationError`. With neither it returns the same `ValidationError` as `CreateLoadBalancer` for the balancer's type, `At least two subnets in two different Availability Zones must be specified` for an Application Load Balancer and `At least one subnet must be specified` for a Network or Gateway Load Balancer, and leaves the balancer on its subnets. A `SetSubnets` that names subnets is counted as `CreateLoadBalancer` counts them, following the two-zone rule its API reference states: one subnet for an Application Load Balancer, in `Subnets` or `SubnetMappings`, returns `ValidationError` `At least two subnets in two different Availability Zones must be specified` before any subnet is looked up, and leaves the balancer on its subnets. AWS does not document the error for this case, so Floci gives `CreateLoadBalancer`'s error, in the same order. A CloudFormation update that keeps an Application Load Balancer and names one subnet fails with that error and rolls back. A Network Load Balancer can be set onto one subnet. The `SetSubnets` API reference requires a Gateway Load Balancer's `Subnets` to include every subnet it is already on; Floci does not enforce that.
- `CreateLoadBalancer` takes `Subnets` or `SubnetMappings`; specifying both is rejected with `ValidationError`. Application Load Balancers use the regional zone policy described below: by default, two distinct ordinary AZs are required in every region. Empty subnet requests remain invalid. Requests below the minimum return `ValidationError`: `At least two subnets in two different Availability Zones must be specified` (or `At least one subnet must be specified` when single-zone operation is enabled). Subnet-count checks precede lookup, and rejected requests create no load balancer. CloudFormation uses the same service validation; an update that keeps the balancer and omits subnets preserves its current subnets.
- `SetSubnets` uses the same regional policy for `Subnets` and `SubnetMappings`. Specifying both, an empty request, or a request below the effective AZ minimum is rejected before mutation. Repeated zones return `InvalidConfigurationRequest`: `A load balancer cannot be attached to multiple subnets in the same Availability Zone`. With no subnets, NLB and GWLB return `ValidationError`: `At least one subnet must be specified`. AWS does not document the one-subnet ALB update error; Floci uses the create error and order. Each selected subnet must belong to the load balancer's VPC. Network Load Balancers may use one subnet. The AWS requirement that a Gateway Load Balancer retain every existing subnet is not currently enforced.
- 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.
- Gateway listeners require `Protocol` and `Port` to be omitted on create and modify. Their control-plane response reports `GENEVE` without a port. CloudFormation preserves omitted gateway listener settings on create and update; other load balancer types retain their existing `HTTP` and port 80 defaults.
@@ -380,3 +380,34 @@ healthy and nothing else reports the collision.
Giving each load balancer a `host-header` rule for the hostname it serves is usually enough, and it
is the same configuration AWS needs. Moving one load balancer to a different listener port also
works, at the cost of a Floci-only difference from the deployed template.
## Application Load Balancer zone policy
One Floci instance serves multiple regions. The ALB policy uses each request's
region, including CloudFormation provisioning, rather than the server's default region.
By default, ordinary ALB subnets require two distinct Availability Zones in every
region, including Osaka (`ap-northeast-3`). Empty subnet lists remain invalid.
Each selected subnet must belong to a different AZ, even when a single AZ is allowed.
This applies to CreateLoadBalancer and SetSubnets; NLB and GWLB rules are unchanged.
Local Zone and Outpost-specific placement is not implemented by this setting.
To override this rule globally, set
`FLOCI_SERVICES_ELBV2_ALB_ZONE_RULE=allow-single-zone`.
The default is `aws`. Individual regions can override the global setting in YAML:
```yaml
floci:
services:
elbv2:
alb-zone-rule: allow-single-zone
alb-zone-rule-by-region:
us-east-1: aws
ap-northeast-3: aws
```
Precedence is per-region setting, global setting, then AWS behavior.
A per-region `aws` entry restores AWS behavior even when the global rule is overridden.
These explicit overrides intentionally change local compatibility; they do not
change the AWS API shape or require a separate Floci process for each region.
CloudFormation rollback can restore a saved legacy ALB subnet list with repeated Availability Zones. This internal snapshot path still checks subnet existence, the zone minimum, and VPC membership; new API and stack-update requests continue to reject repeated zones.
@@ -3890,6 +3890,18 @@ public interface EmulatorConfig {
/** Default idle-pool timeout in seconds; zero disables expiry. Target Keep-Alive may override it. */
@WithDefault("60")
int backendKeepAliveTimeoutSeconds();
/** AWS defaults unless explicitly overridden for local deployments. */
@WithDefault("aws")
AlbZoneRule albZoneRule();
/** A region entry takes precedence over the global rule, including an explicit AWS reset. */
Map<String, AlbZoneRule> albZoneRuleByRegion();
}
enum AlbZoneRule {
AWS,
ALLOW_SINGLE_ZONE
}
interface EksServiceConfig {
@@ -269,7 +269,7 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
}
String arn = resource.getPhysicalId();
List<String> priorSubnets = prior.isEmpty() ? List.of() : List.of(prior.split(","));
elbV2Service.setSubnets(AwsArnUtils.parse(arn).region(), arn, priorSubnets);
elbV2Service.restoreSubnetSnapshot(AwsArnUtils.parse(arn).region(), arn, priorSubnets);
recordUsedSubnets(resource, priorSubnets);
resource.getAttributes().remove(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR);
return true;
@@ -303,7 +303,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);
requireSubnets(region, lbType, subnets);
String vpcId = resolveSubnetVpcId(region, lbType, subnets);
LoadBalancer lb = new LoadBalancer();
@@ -332,7 +332,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
/**
* Every load balancer type takes {@code Subnets} or {@code SubnetMappings}, and an Application Load
* Balancer takes at least two, so a CreateLoadBalancer with fewer is refused before anything is
* Balancer takes at least two by default, so a CreateLoadBalancer with fewer is refused before anything is
* created, with the message AWS gives an Application or a Network Load Balancer. A Gateway Load
* Balancer, which takes subnets the way a Network Load Balancer does, gets the Network one. AWS
* counts before it looks a subnet up, so one subnet that does not exist gets this error too, not
@@ -342,11 +342,11 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
* a SetSubnets that names none, and {@link #setSubnets} on a list that names some, once it has the
* balancer's type; whether the subnets span two Availability Zones is checked after they are looked
* up. No public report shows what AWS answers a SetSubnets with one subnet, so it gets the create
* message and order.
* message and order. Explicit global or regional single-zone overrides reduce the minimum to one.
*/
private static void requireSubnets(String lbType, List<String> subnets) {
private void requireSubnets(String region, String lbType, List<String> subnets) {
int count = subnets == null ? 0 : subnets.size();
if ("application".equals(lbType) && count < 2) {
if ("application".equals(lbType) && requiresTwoAlbZones(region) && count < 2) {
throw new AwsException("ValidationError",
"At least two subnets in two different Availability Zones must be specified", 400);
}
@@ -355,6 +355,24 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
}
}
private boolean requiresTwoAlbZones(String region) {
EmulatorConfig.AlbZoneRule rule = EmulatorConfig.AlbZoneRule.AWS;
if (config != null) {
EmulatorConfig.ElbV2ServiceConfig settings = config.services().elbv2();
if (settings.albZoneRule() != null) {
rule = settings.albZoneRule();
}
Map<String, EmulatorConfig.AlbZoneRule> regions = settings.albZoneRuleByRegion();
if (regions != null) {
rule = regions.getOrDefault(region, rule);
}
}
return switch (rule) {
case AWS -> true;
case ALLOW_SINGLE_ZONE -> false;
};
}
/**
* 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.
@@ -489,7 +507,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
void setSubnetsFromRequest(String region, String arn, List<String> subnets) {
LoadBalancer lb = requireLoadBalancer(region, arn);
if (subnets.isEmpty()) {
requireSubnets(lb.getType(), subnets);
requireSubnets(region, lb.getType(), subnets);
}
setSubnets(region, arn, subnets);
}
@@ -500,13 +518,22 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
* moves a balancer an earlier Floci version saved without subnets back onto none.
*/
public void setSubnets(String region, String arn, List<String> subnets) {
setSubnets(region, arn, subnets, false);
}
/** Restores CloudFormation's saved subnet snapshot, including legacy duplicate-zone assignments. */
public void restoreSubnetSnapshot(String region, String arn, List<String> subnets) {
setSubnets(region, arn, subnets, true);
}
private void setSubnets(String region, String arn, List<String> subnets, boolean restoreSnapshot) {
ec2Service.runWithSubnetReferencesHeld(region, () -> {
LoadBalancer lb = requireLoadBalancer(region, arn);
// Counted as on create, before any subnet is looked up; an empty list is taken, as above.
if (subnets != null && !subnets.isEmpty()) {
requireSubnets(lb.getType(), subnets);
requireSubnets(region, lb.getType(), subnets);
}
String vpcId = resolveSubnetVpcId(region, lb.getType(), subnets);
String vpcId = resolveSubnetVpcId(region, lb.getType(), subnets, restoreSnapshot);
if (vpcId != null && lb.getVpcId() != null && !lb.getVpcId().equals(vpcId)) {
throw new AwsException("InvalidConfigurationRequest",
"All subnets must belong to the load balancer VPC.", 400);
@@ -1724,6 +1751,11 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
}
private String resolveSubnetVpcId(String region, String lbType, List<String> subnetIds) {
return resolveSubnetVpcId(region, lbType, subnetIds, false);
}
private String resolveSubnetVpcId(String region, String lbType, List<String> subnetIds,
boolean restoreSnapshot) {
if (subnetIds == null || subnetIds.isEmpty()) {
return null;
}
@@ -1736,10 +1768,14 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
.map(Subnet::getAvailabilityZone)
.distinct()
.count();
if (distinctAvailabilityZones < 2) {
if (requiresTwoAlbZones(region) && distinctAvailabilityZones < 2) {
throw new AwsException("InvalidConfigurationRequest",
"Application Load Balancers must be attached to subnets in at least two Availability Zones.", 400);
}
if (!restoreSnapshot && distinctAvailabilityZones < subnetIds.size()) {
throw new AwsException("InvalidConfigurationRequest",
"A load balancer cannot be attached to multiple subnets in the same Availability Zone", 400);
}
}
Set<String> vpcIds = subnetIds.stream()
+6
View File
@@ -929,6 +929,12 @@ floci:
mock: false
backend-keep-alive: true
backend-keep-alive-timeout-seconds: 60
alb-zone-rule: ${FLOCI_SERVICES_ELBV2_ALB_ZONE_RULE:aws}
# Per-region entries override this global setting, including an explicit aws reset.
# alb-zone-rule-by-region:
# ap-northeast-3: allow-single-zone
# us-east-1: allow-single-zone
codebuild:
enabled: true
# docker-network: floci-network
@@ -0,0 +1,46 @@
package io.floci.aws.config;
import io.smallrye.config.ConfigMapping;
import io.smallrye.config.PropertiesConfigSource;
import io.smallrye.config.SmallRyeConfigBuilder;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class AlbZoneRuleConfigTest {
@ConfigMapping(prefix = "floci.services.elbv2")
interface Settings extends EmulatorConfig.ElbV2ServiceConfig {}
@Test
void defaultsToAwsWithNoRegionalOverrides() {
Settings settings = settings(Map.of());
assertEquals(EmulatorConfig.AlbZoneRule.AWS, settings.albZoneRule());
assertEquals(Map.of(), settings.albZoneRuleByRegion());
}
@Test
void mapsGlobalAndRegionalRulesIndependently() {
Settings settings = settings(Map.of(
"floci.services.elbv2.alb-zone-rule", "allow-single-zone",
"floci.services.elbv2.alb-zone-rule-by-region.ap-northeast-3", "aws",
"floci.services.elbv2.alb-zone-rule-by-region.us-east-1", "allow-single-zone"));
assertEquals(EmulatorConfig.AlbZoneRule.ALLOW_SINGLE_ZONE, settings.albZoneRule());
assertEquals(Map.of("ap-northeast-3", EmulatorConfig.AlbZoneRule.AWS,
"us-east-1", EmulatorConfig.AlbZoneRule.ALLOW_SINGLE_ZONE), settings.albZoneRuleByRegion());
}
@Test
void rejectsAnUnknownRule() {
assertThrows(RuntimeException.class,
() -> settings(Map.of("floci.services.elbv2.alb-zone-rule", "anything")));
}
private static Settings settings(Map<String, String> properties) {
return new SmallRyeConfigBuilder().addDefaultInterceptors().withMapping(Settings.class)
.withSources(new PropertiesConfigSource(properties, "zone-rule-test", 400))
.build().getConfigMapping(Settings.class);
}
}
@@ -3,6 +3,8 @@ package io.floci.aws.services.cloudformation;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.XmlParser;
import io.floci.aws.services.elbv2.ElbV2Service;
import io.floci.aws.services.elbv2.model.AvailabilityZone;
import io.floci.aws.services.elbv2.model.LoadBalancer;
import io.floci.aws.testing.CfnStackWaits;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
@@ -26,7 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.reset;
/**
@@ -307,15 +309,40 @@ class CloudFormationElbV2SubnetUpdateIntegrationTest {
}
}
@Test
void failedStackUpdateRestoresLegacyDuplicateZoneSubnetSnapshot() {
String stack = "alb-legacy-rollback-" + Long.toString(System.nanoTime(), 36);
try {
Map<String, String> created = createStack(stack, branchTemplate(""), "first");
LoadBalancer legacy = elbService.describeLoadBalancers("us-east-1", List.of(created.get("Alb")),
null, null, null).getFirst();
AvailabilityZone legacyZone = new AvailabilityZone();
legacyZone.setSubnetId(created.get("SubnetC"));
legacyZone.setZoneName("us-east-1a");
// Seed the persisted shape that older versions accepted, without relaxing a new request.
legacy.getAvailabilityZones().add(legacyZone);
Set<String> prior = Set.copyOf(loadBalancerSubnets(created.get("Alb")));
request(CFN_AUTH, "UpdateStack", "StackName", stack, "TemplateBody",
branchTemplate(failingSecret(stack, "Alb")),
"Parameters.member.1.ParameterKey", "Placement",
"Parameters.member.1.ParameterValue", "second").statusCode(200);
CfnStackWaits.awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE");
assertEquals(prior, Set.copyOf(loadBalancerSubnets(created.get("Alb"))));
} finally {
deleteStack(stack);
}
}
/**
* The update's own move onto the new subnets goes through, the first move back fails as if its
* subnet had been deleted meanwhile, and any later call goes through again.
*/
private void failTheFirstMoveBack() {
doCallRealMethod()
.doThrow(new AwsException("SubnetNotFound", "The subnet ID was not found", 400))
doThrow(new AwsException("SubnetNotFound", "The subnet ID was not found", 400))
.doCallRealMethod()
.when(elbService).setSubnets(anyString(), anyString(), anyList());
.when(elbService).restoreSubnetSnapshot(anyString(), anyString(), anyList());
}
/** Moves the load balancer onto SubnetA and an added SubnetC in an update a later resource fails. */
@@ -531,7 +531,7 @@ class ElbV2CfnProvisionerTest {
assertEquals(LB_ARN, lb.getPhysicalId());
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
verify(elb).restoreSubnetSnapshot(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
}
/** The subnets a load balancer is on, as its hidden uses attributes record them. */
@@ -597,7 +597,7 @@ class ElbV2CfnProvisionerTest {
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb).setSubnets(REGION, LB_ARN, List.of());
verify(elb).restoreSubnetSnapshot(REGION, LB_ARN, List.of());
assertEquals(Set.of(), usedSubnets(lb));
}
@@ -620,7 +620,7 @@ class ElbV2CfnProvisionerTest {
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-3"));
verify(elb, never()).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
verify(elb, never()).restoreSubnetSnapshot(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
}
@Test
@@ -628,12 +628,12 @@ class ElbV2CfnProvisionerTest {
StackResource lb = keptLoadBalancerUpdatedTo(loadBalancerOn("web", "subnet-1", "subnet-2"),
"subnet-1", "subnet-3");
doThrow(new AwsException("SubnetNotFound", "The subnet ID 'subnet-2' does not exist", 400)).doNothing()
.when(elb).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
.when(elb).restoreSubnetSnapshot(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
AwsException failure = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(lb));
assertEquals("SubnetNotFound", failure.getErrorCode());
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb, times(2)).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
verify(elb, times(2)).restoreSubnetSnapshot(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
}
@Test
@@ -644,7 +644,7 @@ class ElbV2CfnProvisionerTest {
provisioner.clearUpdate(lb);
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb, never()).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
verify(elb, never()).restoreSubnetSnapshot(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
}
@Test
@@ -657,7 +657,7 @@ class ElbV2CfnProvisionerTest {
provisioner.provision(lb, props, ctx(LB_ARN));
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb, never()).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
verify(elb, never()).restoreSubnetSnapshot(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
}
@Test
@@ -0,0 +1,52 @@
package io.floci.aws.services.elbv2;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.testing.AwsTestClients;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client;
import software.amazon.awssdk.services.elasticloadbalancingv2.model.ElasticLoadBalancingV2Exception;
import software.amazon.awssdk.services.elasticloadbalancingv2.model.LoadBalancerNotFoundException;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
class ElbV2RegionalZoneIntegrationTest {
@Test
void awsDefaultRequiresTwoZonesInBothRegionsForCreateAndSetSubnets() {
try (ElasticLoadBalancingV2Client osaka = AwsTestClients.create(ElasticLoadBalancingV2Client.builder(),
"000000000000", Region.AP_NORTHEAST_3);
ElasticLoadBalancingV2Client virginia = AwsTestClients.create(ElasticLoadBalancingV2Client.builder(),
"000000000000", Region.US_EAST_1)) {
String name = "regional-" + UUID.randomUUID().toString().substring(0, 12);
ElasticLoadBalancingV2Exception rejected = assertThrows(ElasticLoadBalancingV2Exception.class,
() -> virginia.createLoadBalancer(r -> r.name(name).scheme("internal")
.type("application").subnets(Ec2Service.defaultSubnetId("us-east-1", "a"))));
assertEquals("ValidationError", rejected.awsErrorDetails().errorCode());
ElasticLoadBalancingV2Exception osakaRejected = assertThrows(ElasticLoadBalancingV2Exception.class,
() -> osaka.createLoadBalancer(r -> r.name(name).scheme("internal").type("application")
.subnets(Ec2Service.defaultSubnetId("ap-northeast-3", "a"))));
assertEquals("ValidationError", osakaRejected.awsErrorDetails().errorCode());
String arn = osaka.createLoadBalancer(r -> r.name(name).scheme("internal").type("application")
.subnets(Ec2Service.defaultSubnetId("ap-northeast-3", "a"),
Ec2Service.defaultSubnetId("ap-northeast-3", "b")))
.loadBalancers().getFirst().loadBalancerArn();
try {
ElasticLoadBalancingV2Exception updateRejected = assertThrows(
ElasticLoadBalancingV2Exception.class, () -> osaka.setSubnets(r -> r.loadBalancerArn(arn)
.subnets(Ec2Service.defaultSubnetId("ap-northeast-3", "b"))));
assertEquals("ValidationError", updateRejected.awsErrorDetails().errorCode());
assertEquals(2, osaka.describeLoadBalancers(r -> r.loadBalancerArns(arn))
.loadBalancers().getFirst().availabilityZones().size());
} finally {
osaka.deleteLoadBalancer(r -> r.loadBalancerArn(arn));
assertThrows(LoadBalancerNotFoundException.class,
() -> osaka.describeLoadBalancers(r -> r.loadBalancerArns(arn)));
}
}
}
}
@@ -10,6 +10,9 @@ import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.PersistentStorage;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.cloudformation.provisioners.CfnRollback;
import io.floci.aws.services.cloudformation.provisioners.ElbV2CfnProvisioner;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.Subnet;
import io.floci.aws.services.elbv2.model.Action;
@@ -111,6 +114,133 @@ class ElbV2ServiceTest {
stubAlbSubnets(ec2Service);
}
@Test
void rollbackRestoresLegacyDuplicateZoneSubnetsWhileNewRequestsRemainStrict() {
LoadBalancer lb = service.createLoadBalancer(REGION, "legacy-subnets", "internal", "application", "ipv4",
ALB_SUBNETS, List.of(), Map.of());
List<String> legacy = List.of("subnet-a", "subnet-b", "subnet-c");
when(ec2Service.describeSubnets(REGION, legacy, Map.of())).thenReturn(List.of(
subnet("subnet-a", REGION + "a"), subnet("subnet-b", REGION + "b"),
subnet("subnet-c", REGION + "a")));
assertThrows(AwsException.class, () -> service.setSubnetsFromRequest(REGION,
lb.getLoadBalancerArn(), legacy));
StackResource resource = subnetRollbackResource(lb, legacy);
assertTrue(new ElbV2CfnProvisioner(service).rollbackUpdate(resource));
assertEquals(legacy, lb.getAvailabilityZones().stream().map(AvailabilityZone::getSubnetId).toList());
assertFalse(resource.getAttributes().containsKey(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR));
assertThrows(AwsException.class, () -> service.setSubnetsFromRequest(REGION,
lb.getLoadBalancerArn(), legacy));
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void rollbackRetainsSnapshotAndStateWhenPriorSubnetsAreMissingOrInAnotherVpc(boolean foreignVpc) {
LoadBalancer lb = service.createLoadBalancer(REGION, "rollback-invalid-subnets", "internal", "application",
"ipv4", ALB_SUBNETS, List.of(), Map.of());
List<String> prior = List.of("subnet-a", "subnet-b", "subnet-c");
Subnet other = subnet("subnet-c", REGION + "a");
other.setVpcId("vpc-other");
when(ec2Service.describeSubnets(REGION, prior, Map.of())).thenReturn(foreignVpc
? List.of(subnet("subnet-a", REGION + "a"), subnet("subnet-b", REGION + "b"), other)
: List.of(subnet("subnet-a", REGION + "a"), subnet("subnet-b", REGION + "b")));
StackResource resource = subnetRollbackResource(lb, prior);
AwsException failure = assertThrows(AwsException.class,
() -> new ElbV2CfnProvisioner(service).rollbackUpdate(resource));
assertEquals(foreignVpc ? "InvalidConfigurationRequest" : "SubnetNotFound", failure.getErrorCode());
assertEquals(ALB_SUBNETS, lb.getAvailabilityZones().stream().map(AvailabilityZone::getSubnetId).toList());
assertEquals(String.join(",", prior), resource.getAttributes()
.get(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR));
assertEquals("vpc-a", lb.getVpcId());
}
private static StackResource subnetRollbackResource(LoadBalancer lb, List<String> subnets) {
StackResource resource = new StackResource();
resource.setResourceType("AWS::ElasticLoadBalancingV2::LoadBalancer");
resource.setPhysicalId(lb.getLoadBalancerArn());
resource.getAttributes().put(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR,
String.join(",", subnets));
return resource;
}
@ParameterizedTest
@CsvSource({
"ap-northeast-3,AWS,none,false",
"us-east-1,AWS,none,false",
"us-east-1,ALLOW_SINGLE_ZONE,none,true",
"us-east-1,AWS,ALLOW_SINGLE_ZONE,true",
"ap-northeast-3,ALLOW_SINGLE_ZONE,AWS,false",
"us-east-1,ALLOW_SINGLE_ZONE,AWS,false"
})
void albZonePolicyAppliesToCreateAndSetSubnets(String region, EmulatorConfig.AlbZoneRule global,
String regional, boolean allowed) {
Map<String, EmulatorConfig.AlbZoneRule> overrides = "none".equals(regional) ? Map.of()
: Map.of(region, EmulatorConfig.AlbZoneRule.valueOf(regional));
service.config = albZoneConfig(global, overrides);
service.regionResolver = new RegionResolver(region, "000000000000");
lenient().when(ec2Service.describeSubnets(eq(region), anyList(), eq(Map.of())))
.thenAnswer(invocation -> invocation.<List<String>>getArgument(1).stream()
.map(id -> subnet(id, region + ("subnet-a".equals(id) ? "a" : "b"))).toList());
lenient().when(ec2Service.requireSubnet(eq(region), anyString()))
.thenAnswer(invocation -> subnet(invocation.getArgument(1), region + "a"));
LoadBalancer twoZones = service.createLoadBalancer(region, "two-zones", "internal", "application",
"ipv4", ALB_SUBNETS, List.of(), Map.of());
if (allowed) {
LoadBalancer single = service.createLoadBalancer(region, "one-zone", "internal", "application",
"ipv4", List.of("subnet-a"), List.of(), Map.of());
assertEquals(1, single.getAvailabilityZones().size());
service.setSubnetsFromRequest(region, twoZones.getLoadBalancerArn(), List.of("subnet-a"));
assertEquals(1, twoZones.getAvailabilityZones().size());
} else {
assertThrows(AwsException.class, () -> service.createLoadBalancer(region, "one-zone", "internal",
"application", "ipv4", List.of("subnet-a"), List.of(), Map.of()));
assertThrows(AwsException.class, () -> service.setSubnetsFromRequest(region,
twoZones.getLoadBalancerArn(), List.of("subnet-a")));
assertEquals(2, twoZones.getAvailabilityZones().size());
}
assertThrows(AwsException.class, () -> service.createLoadBalancer(region, "no-zone", "internal",
"application", "ipv4", List.of(), List.of(), Map.of()));
assertThrows(AwsException.class, () -> service.setSubnetsFromRequest(region,
twoZones.getLoadBalancerArn(), List.of()));
}
@Test
void singleZonePolicyStillRejectsMultipleSubnetsInTheSameZone() {
String region = "ap-northeast-3";
service.config = albZoneConfig(EmulatorConfig.AlbZoneRule.ALLOW_SINGLE_ZONE, Map.of());
Subnet first = subnet("subnet-a", region + "a");
Subnet second = subnet("subnet-b", region + "a");
when(ec2Service.describeSubnets(region, ALB_SUBNETS, Map.of())).thenReturn(List.of(first, second));
when(ec2Service.describeSubnets(region, List.of("subnet-a"), Map.of())).thenReturn(List.of(first));
AwsException rejected = assertThrows(AwsException.class, () -> service.createLoadBalancer(region,
"same-zone", "internal", "application", "ipv4", ALB_SUBNETS, List.of(), Map.of()));
assertEquals("InvalidConfigurationRequest", rejected.getErrorCode());
assertEquals("A load balancer cannot be attached to multiple subnets in the same Availability Zone",
rejected.getMessage());
LoadBalancer single = service.createLoadBalancer(region, "single-zone", "internal", "application",
"ipv4", List.of("subnet-a"), List.of(), Map.of());
assertThrows(AwsException.class,
() -> service.setSubnetsFromRequest(region, single.getLoadBalancerArn(), ALB_SUBNETS));
assertEquals(List.of("subnet-a"), single.getAvailabilityZones().stream()
.map(AvailabilityZone::getSubnetId).toList());
}
private static EmulatorConfig albZoneConfig(EmulatorConfig.AlbZoneRule global,
Map<String, EmulatorConfig.AlbZoneRule> overrides) {
EmulatorConfig settings = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.ElbV2ServiceConfig elbv2 = mock(EmulatorConfig.ElbV2ServiceConfig.class);
when(settings.services()).thenReturn(services);
when(services.elbv2()).thenReturn(elbv2);
when(elbv2.albZoneRule()).thenReturn(global);
when(elbv2.albZoneRuleByRegion()).thenReturn(overrides);
lenient().when(settings.hostname()).thenReturn(Optional.empty());
return settings;
}
@Test
void describeListenersRequiresEveryExplicitArn() {
String lb = service.createLoadBalancer(REGION, "listener-lookup", "internal", "application", "ipv4",
@@ -995,6 +1125,9 @@ class ElbV2ServiceTest {
void createLoadBalancerUsesConfiguredHostnameForDnsSuffix() {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.hostname()).thenReturn(Optional.of("floci"));
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
when(config.services()).thenReturn(services);
when(services.elbv2()).thenReturn(mock(EmulatorConfig.ElbV2ServiceConfig.class));
service.config = config;
String dnsName = service.createLoadBalancer(
+2
View File
@@ -419,6 +419,8 @@ floci:
mock: true
backend-keep-alive: true
backend-keep-alive-timeout-seconds: 60
alb-zone-rule: aws
codebuild:
enabled: true
# docker-network: floci-network