fix(elb): assign the VPC default security group to a Classic load balancer created without one (#7100)

This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-11-02 14:50:12 -04:00
1 parent fccc81b61d
commit cb093f87cb
9 files changed
+223 -27

No files matched your search

+4
View File
@@ -68,6 +68,10 @@ opened and no traffic is forwarded. Only the control plane and health checking a
`TCP` for TCP/SSL listeners. Explicit backend protocols remain unchanged.
Creation, listener additions, persisted readback and identical listener retries
use the same effective value.
- A load balancer created in subnets without `SecurityGroups` gets the VPC's `default` security
group, reported in `SecurityGroups` and `SourceSecurityGroup`. Floci uses the VPC's `default`
group in the default VPC too, rather than a dedicated `default_elb_<id>` group. A load balancer
created with only `AvailabilityZones` gets no security group.
- Load balancer state is persisted through Floci storage, and on startup health checking is
restarted for the load balancers of every account.
- A new load balancer gets AWS's default health check (`TCP:80`, interval 30, timeout 5,
@@ -7791,6 +7791,17 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
.collect(Collectors.toList());
}
/**
* The VPC's {@code default} security group, the one EC2 creates with the VPC. A VPC holds at most
* one, since a second group of the same name is rejected as a duplicate. Empty if it was deleted;
* an unknown VPC fails the way {@link #getSecurityGroupsForVpc} does.
*/
public Optional<SecurityGroup> defaultSecurityGroupOf(String region, String vpcId) {
return getSecurityGroupsForVpc(region, vpcId, List.of()).stream()
.filter(sg -> "default".equals(sg.getGroupName()))
.findFirst();
}
public void deleteSecurityGroup(String region, String groupId) {
ensureDefaultResources(region);
if (securityGroups.get(key(region, groupId)).isEmpty()) {
@@ -14538,13 +14549,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
sgIdentifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName()));
}
} else {
SecurityGroup defaultSg = securityGroups.scan(k -> k.startsWith(region + "::")).stream()
.filter(group -> subnet.getVpcId().equals(group.getVpcId())
&& "default".equals(group.getGroupName()))
.findFirst().orElse(null);
if (defaultSg != null) {
sgIdentifiers.add(new GroupIdentifier(defaultSg.getGroupId(), defaultSg.getGroupName()));
}
defaultSecurityGroupOf(region, subnet.getVpcId()).ifPresent(defaultSg ->
sgIdentifiers.add(new GroupIdentifier(defaultSg.getGroupId(), defaultSg.getGroupName())));
}
// An explicit address is checked the way RunInstances checks its PrivateIpAddress: it must be
@@ -423,12 +423,14 @@ public class ElbClassicQueryHandler {
xml.start("member").elem("InstanceId", instanceId).end("member");
}
xml.end("Instances")
.raw(healthCheckXml(lb.getHealthCheck()))
.start("SourceSecurityGroup")
.elem("OwnerAlias", lb.getSourceSecurityGroupOwnerAlias())
.elem("GroupName", lb.getSourceSecurityGroupName())
.end("SourceSecurityGroup")
.start("SecurityGroups");
.raw(healthCheckXml(lb.getHealthCheck()));
if (lb.getSourceSecurityGroupName() != null) {
xml.start("SourceSecurityGroup")
.elem("OwnerAlias", lb.getSourceSecurityGroupOwnerAlias())
.elem("GroupName", lb.getSourceSecurityGroupName())
.end("SourceSecurityGroup");
}
xml.start("SecurityGroups");
for (String sg : lb.getSecurityGroups()) {
xml.elem("member", sg);
}
@@ -229,7 +229,6 @@ public class ElbClassicService implements ServerCertificateReferenceProvider {
lb.setCreatedTime(Instant.now());
lb.setListeners(new ArrayList<>(listeners));
lb.setSecurityGroups(securityGroups != null ? new ArrayList<>(securityGroups) : new ArrayList<>());
populateSourceSecurityGroup(region, lb);
lb.setHealthCheck(ClassicHealthCheck.defaults());
if (tags != null && !tags.isEmpty()) {
lb.setTags(new LinkedHashMap<>(tags));
@@ -246,6 +245,14 @@ public class ElbClassicService implements ServerCertificateReferenceProvider {
} else if (availabilityZones != null) {
lb.setAvailabilityZones(new ArrayList<>(availabilityZones));
}
if (lb.getVpcId() != null && lb.getSecurityGroups().isEmpty()) {
// AWS associates a security group with a VPC load balancer created without one; for a
// non-default VPC that is the VPC's default group. (In a default VPC AWS creates a
// default_elb_<id> group instead; not modelled, see docs/services/elb-classic.md.)
ec2Service.defaultSecurityGroupOf(region, lb.getVpcId())
.ifPresent(sg -> lb.getSecurityGroups().add(sg.getGroupId()));
}
populateSourceSecurityGroup(region, lb);
whileCertificatesHeld(listeners, () -> {
// The certificate check again, and this is the one that counts. The one above it
@@ -7402,7 +7402,9 @@ public class RdsService implements Resettable, ResourceProvider {
endpoint.setVpcId(vpcId);
endpoint.setVpcSubnetIds(vpcSubnetIds);
endpoint.setVpcSecurityGroupIds(vpcSecurityGroupIds == null || vpcSecurityGroupIds.isEmpty()
? defaultSecurityGroupOf(vpcId, effectiveRegion) : vpcSecurityGroupIds);
? ec2Service.defaultSecurityGroupOf(effectiveRegion, vpcId).map(sg -> List.of(sg.getGroupId()))
.orElse(List.of())
: vpcSecurityGroupIds);
endpoint.setCreatedDate(Instant.now());
endpoint.setTargetRole(role);
endpoint.setEndpointNetworkType(networkType);
@@ -7528,13 +7530,6 @@ public class RdsService implements Resettable, ResourceProvider {
return endpoint;
}
private List<String> defaultSecurityGroupOf(String vpcId, String region) {
return ec2Service.getSecurityGroupsForVpc(region, vpcId, Map.of()).stream()
.filter(group -> "default".equals(group.getGroupName()))
.map(group -> group.getGroupId())
.toList();
}
private List<DbProxyEndpoint> proxyEndpointsOf(String region, String dbProxyName) {
String prefix = effectiveRegion(region) + "::";
return proxyEndpoints.scan(key -> key.startsWith(prefix)).stream()
@@ -234,6 +234,58 @@ class Ec2ServiceTest {
}
@Test
void defaultSecurityGroupOfReturnsTheGroupNamedDefaultInThatVpc() {
Ec2Service service = mockModeService();
String region = "us-east-1";
String vpcId = service.createVpc(region, "10.94.0.0/16", false).getVpcId();
service.createSecurityGroup(region, "web", "not the default", vpcId);
SecurityGroup expected = service.describeSecurityGroups(region, List.of(), List.of(),
Map.of("vpc-id", List.of(vpcId), "group-name", List.of("default"))).getFirst();
SecurityGroup found = service.defaultSecurityGroupOf(region, vpcId).orElseThrow();
assertEquals(expected.getGroupId(), found.getGroupId());
assertEquals(vpcId, found.getVpcId());
assertEquals("default", found.getGroupName());
assertNotEquals(service.defaultSecurityGroupOf(region, service.resolveDefaultVpcId(region))
.orElseThrow().getGroupId(), found.getGroupId());
}
@Test
void createNetworkInterfaceWithoutGroupsGetsItsVpcsDefaultGroup() {
Ec2Service service = mockModeService();
String region = "us-east-1";
String vpcId = service.createVpc(region, "10.94.0.0/16", false).getVpcId();
Subnet subnet = service.createSubnet(region, vpcId, "10.94.1.0/24", region + "a");
NetworkInterface eni = service.createNetworkInterface(region, subnet.getSubnetId(), null, null,
List.of(), List.of(), List.of());
assertEquals(List.of(service.defaultSecurityGroupOf(region, vpcId).orElseThrow().getGroupId()),
eni.getGroups().stream().map(GroupIdentifier::getGroupId).toList());
}
@Test
void defaultSecurityGroupOfIsEmptyOnceTheDefaultGroupIsGone() {
Ec2Service service = mockModeService();
String region = "us-east-1";
String vpcId = service.createVpc(region, "10.94.0.0/16", false).getVpcId();
service.deleteSecurityGroup(region, service.defaultSecurityGroupOf(region, vpcId).orElseThrow().getGroupId());
assertTrue(service.defaultSecurityGroupOf(region, vpcId).isEmpty());
}
@Test
void defaultSecurityGroupOfRejectsAnUnknownVpc() {
Ec2Service service = mockModeService();
AwsException error = assertThrows(AwsException.class,
() -> service.defaultSecurityGroupOf("us-east-1", "vpc-0123456789abcdef0"));
assertEquals("InvalidVpcID.NotFound", error.getErrorCode());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void createNetworkInterfaceRejectsMissingGroupsBeforeAllocatingAddresses(boolean includeExistingGroup) {
@@ -622,4 +622,74 @@ class ElbClassicIntegrationTest {
+ ".LoadBalancerDescriptions.member.SourceSecurityGroup.GroupName",
equalTo("elb-source-sg"));
}
@Test
@Order(20)
void vpcLoadBalancerCreatedWithoutSecurityGroupsGetsTheVpcDefaultGroup() {
String account = "444444444444";
String ec2Auth = "AWS4-HMAC-SHA256 Credential=" + account
+ "/20260427/us-east-1/ec2/aws4_request";
String elbAuth = "AWS4-HMAC-SHA256 Credential=" + account
+ "/20260427/us-east-1/elasticloadbalancing/aws4_request";
String vpcId = given()
.formParam("Action", "CreateVpc").formParam("Version", "2016-11-15")
.formParam("CidrBlock", "10.77.0.0/16")
.header("Authorization", ec2Auth)
.when().post("/")
.then().statusCode(200)
.extract().xmlPath().getString("CreateVpcResponse.vpc.vpcId");
String subnetId = given()
.formParam("Action", "CreateSubnet").formParam("Version", "2016-11-15")
.formParam("VpcId", vpcId).formParam("CidrBlock", "10.77.1.0/24")
.formParam("AvailabilityZone", "us-east-1a")
.header("Authorization", ec2Auth)
.when().post("/")
.then().statusCode(200)
.extract().xmlPath().getString("CreateSubnetResponse.subnet.subnetId");
// A second, non-default group in the VPC, so an unfiltered lookup cannot pass by luck.
given()
.formParam("Action", "CreateSecurityGroup").formParam("Version", "2016-11-15")
.formParam("GroupName", "elb-other").formParam("GroupDescription", "other")
.formParam("VpcId", vpcId)
.header("Authorization", ec2Auth)
.when().post("/")
.then().statusCode(200);
String defaultGroupId = given()
.formParam("Action", "DescribeSecurityGroups").formParam("Version", "2016-11-15")
.formParam("Filter.1.Name", "vpc-id").formParam("Filter.1.Value.1", vpcId)
.formParam("Filter.2.Name", "group-name").formParam("Filter.2.Value.1", "default")
.header("Authorization", ec2Auth)
.when().post("/")
.then().statusCode(200)
.extract().xmlPath().getString(
"DescribeSecurityGroupsResponse.securityGroupInfo.item.groupId");
assertTrue(defaultGroupId != null && defaultGroupId.startsWith("sg-"), defaultGroupId);
String name = "classic-elb-vpc-default-sg";
given()
.formParam("Action", "CreateLoadBalancer").formParam("Version", V1)
.formParam("LoadBalancerName", name)
.formParam("Subnets.member.1", subnetId)
.formParam("Listeners.member.1.Protocol", "HTTP")
.formParam("Listeners.member.1.LoadBalancerPort", "80")
.formParam("Listeners.member.1.InstanceProtocol", "HTTP")
.formParam("Listeners.member.1.InstancePort", "8080")
.header("Authorization", elbAuth)
.when().post("/")
.then().statusCode(200);
String described = "DescribeLoadBalancersResponse.DescribeLoadBalancersResult"
+ ".LoadBalancerDescriptions.member.";
given()
.formParam("Action", "DescribeLoadBalancers").formParam("Version", V1)
.formParam("LoadBalancerNames.member.1", name)
.header("Authorization", elbAuth)
.when().post("/")
.then().statusCode(200)
.body(described + "VPCId", equalTo(vpcId))
.body(described + "SecurityGroups.member.size()", equalTo(1))
.body(described + "SecurityGroups.member", equalTo(defaultGroupId))
.body(described + "SourceSecurityGroup.OwnerAlias", equalTo(account))
.body(described + "SourceSecurityGroup.GroupName", equalTo("default"));
}
}
@@ -214,4 +214,66 @@ class RdsProxyEndpointIntegrationTest {
query("DescribeDBProxyEndpoints").when().post("/").then().statusCode(200)
.body(not(containsString("<member>")));
}
@Test
@Order(7)
void anEndpointCreatedWithoutSecurityGroupsGetsItsVpcsDefaultGroup() {
String vpcId = ec2("CreateVpc").formParam("CidrBlock", "10.78.0.0/16")
.when().post("/").then().statusCode(200)
.extract().xmlPath().getString("CreateVpcResponse.vpc.vpcId");
String subnetA = subnet(vpcId, "10.78.1.0/24", "a");
String subnetB = subnet(vpcId, "10.78.2.0/24", "b");
// A second, non-default group in the VPC, so an unfiltered lookup cannot pass by luck.
ec2("CreateSecurityGroup").formParam("GroupName", "proxy-other")
.formParam("GroupDescription", "other").formParam("VpcId", vpcId)
.when().post("/").then().statusCode(200);
String defaultGroupId = ec2("DescribeSecurityGroups")
.formParam("Filter.1.Name", "vpc-id").formParam("Filter.1.Value.1", vpcId)
.formParam("Filter.2.Name", "group-name").formParam("Filter.2.Value.1", "default")
.when().post("/").then().statusCode(200)
.extract().xmlPath().getString("DescribeSecurityGroupsResponse.securityGroupInfo.item.groupId");
assertTrue(defaultGroupId != null && defaultGroupId.startsWith("sg-"), defaultGroupId);
String proxy = "pep-default-sg";
query("CreateDBProxy")
.formParam("DBProxyName", proxy)
.formParam("EngineFamily", "POSTGRESQL")
.formParam("RoleArn", "arn:aws:iam::000000000000:role/proxy")
.formParam("VpcSubnetIds.member.1", subnetA)
.formParam("VpcSubnetIds.member.2", subnetB)
.formParam("VpcSecurityGroupIds.member.1", "sg-proxy")
.formParam("Auth.member.1.AuthScheme", "SECRETS")
.formParam("Auth.member.1.SecretArn",
"arn:aws:secretsmanager:" + REGION + ":000000000000:secret:db-AbCdEf")
.when().post("/").then().statusCode(200);
query("CreateDBProxyEndpoint")
.formParam("DBProxyName", proxy)
.formParam("DBProxyEndpointName", "no-groups")
.formParam("VpcSubnetIds.member.1", subnetA)
.formParam("VpcSubnetIds.member.2", subnetB)
.when().post("/").then().statusCode(200);
query("DescribeDBProxyEndpoints").formParam("DBProxyEndpointName", "no-groups")
.when().post("/").then().statusCode(200)
.body(MEMBERS + ".VpcId", equalTo(vpcId))
.body(MEMBERS + ".VpcSecurityGroupIds.member.size()", equalTo(1))
.body(MEMBERS + ".VpcSecurityGroupIds.member", equalTo(defaultGroupId));
query("DeleteDBProxy").formParam("DBProxyName", proxy).when().post("/").then().statusCode(200);
}
private static RequestSpecification ec2(String action) {
return given().header("Authorization",
"AWS4-HMAC-SHA256 Credential=test/20261019/" + REGION + "/ec2/aws4_request")
.contentType(URLENC)
.formParam("Action", action)
.formParam("Version", "2016-11-15");
}
private static String subnet(String vpcId, String cidr, String azSuffix) {
return ec2("CreateSubnet").formParam("VpcId", vpcId).formParam("CidrBlock", cidr)
.formParam("AvailabilityZone", REGION + azSuffix)
.when().post("/").then().statusCode(200)
.extract().xmlPath().getString("CreateSubnetResponse.subnet.subnetId");
}
}
@@ -11514,11 +11514,9 @@ class RdsServiceTest {
SecurityGroup defaultGroup = new SecurityGroup();
defaultGroup.setGroupId("sg-vpc-default");
defaultGroup.setGroupName("default");
SecurityGroup otherGroup = new SecurityGroup();
otherGroup.setGroupId("sg-vpc-other");
otherGroup.setGroupName("other");
when(ec2Service.getSecurityGroupsForVpc("us-east-1", proxy.getVpcId(), Map.of()))
.thenReturn(List.of(otherGroup, defaultGroup));
// Picking the group out of the VPC is Ec2Service's job, covered in Ec2ServiceTest.
when(ec2Service.defaultSecurityGroupOf("us-east-1", proxy.getVpcId()))
.thenReturn(Optional.of(defaultGroup));
DbProxyEndpoint endpoint = rdsService.createDbProxyEndpoint("us-east-1", "app-proxy", "ep",
PROXY_SUBNET_IDS, List.of(), null, null, Map.of("env", "dev"));