fix(ec2): select the subnet VPC default security group (#7762)

Use the existing VPC-specific default-group lookup for instance launch, with
service and SDK placement regressions and documentation.

Source: AndreKurait/floci#524 (94f76eae34e46dc1e740b6349bbaed578a15e372).

Remove the obsolete regional resolver and its dedicated test assertions now
that instance launch uses the VPC-specific lookup. Keep legacy VPC resolution
coverage and remove its unused security-group fixture.

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
Co-authored-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
Jackson PriceandAndre Kurait authored and GitHub committed 2026-11-09 13:11:06 -04:00
1 parent 9f77c736e9
commit 068740794a
4 files changed
+80 -41

No files matched your search

@@ -0,0 +1,55 @@
"""Instance launch selects security groups in the subnet's VPC."""
import uuid
from contextlib import ExitStack
import pytest
def terminate(client, instance_id):
client.terminate_instances(InstanceIds=[instance_id])
client.get_waiter("instance_terminated").wait(
InstanceIds=[instance_id], WaiterConfig={"Delay": 1, "MaxAttempts": 20})
@pytest.mark.parametrize("placement", ["default", "custom", "explicit"])
def test_instance_uses_its_subnet_vpc_security_group(ec2_client, placement):
with ExitStack() as cleanup:
image = ec2_client.register_image(
Name="launch-groups-" + uuid.uuid4().hex, Architecture="x86_64",
RootDeviceName="/dev/sda1")["ImageId"]
cleanup.callback(ec2_client.deregister_image, ImageId=image)
if placement == "default":
vpc = ec2_client.describe_vpcs(
Filters=[{"Name": "is-default", "Values": ["true"]}])["Vpcs"][0]["VpcId"]
subnet = ec2_client.describe_subnets(
Filters=[{"Name": "vpc-id", "Values": [vpc]}])["Subnets"][0]["SubnetId"]
else:
vpc = ec2_client.create_vpc(CidrBlock="10.227.0.0/16")["Vpc"]["VpcId"]
cleanup.callback(ec2_client.delete_vpc, VpcId=vpc)
subnet = ec2_client.create_subnet(
VpcId=vpc, CidrBlock="10.227.1.0/24")["Subnet"]["SubnetId"]
cleanup.callback(ec2_client.delete_subnet, SubnetId=subnet)
request = {}
if placement == "explicit":
expected = ec2_client.create_security_group(
VpcId=vpc, GroupName="launch-" + uuid.uuid4().hex,
Description="Explicit launch group")["GroupId"]
cleanup.callback(ec2_client.delete_security_group, GroupId=expected)
request["SecurityGroupIds"] = [expected]
else:
expected = ec2_client.describe_security_groups(Filters=[
{"Name": "vpc-id", "Values": [vpc]},
{"Name": "group-name", "Values": ["default"]},
])["SecurityGroups"][0]["GroupId"]
instance = ec2_client.run_instances(
ImageId=image, InstanceType="t3.micro", MinCount=1, MaxCount=1,
SubnetId=subnet, **request)["Instances"][0]
cleanup.callback(terminate, ec2_client, instance["InstanceId"])
observed = ec2_client.describe_instances(
InstanceIds=[instance["InstanceId"]])["Reservations"][0]["Instances"][0]
assert observed["VpcId"] == vpc
assert [group["GroupId"] for group in observed["SecurityGroups"]] == [expected]
assert [group["GroupId"] for group in observed["NetworkInterfaces"][0]["Groups"]] == [expected]
+1 -1
View File
@@ -316,7 +316,7 @@ naming different VPCs find nothing.
| Action | Description |
|--------|-------------|
| RunInstances | Creates one or more local EC2 instances, starting Docker-backed runtime when not in mock mode. Security groups come from `SecurityGroupId.N` or, as Terraform sends them with an interface spec, from the primary interface's `NetworkInterface.1.SecurityGroupId.N`; both in one request is `InvalidParameterCombination`. |
| RunInstances | Creates one or more local EC2 instances, starting Docker-backed runtime when not in mock mode. Security groups come from `SecurityGroupId.N` or, as Terraform sends them with an interface spec, from the primary interface's `NetworkInterface.1.SecurityGroupId.N`; both in one request is `InvalidParameterCombination`. A launch without groups uses the default security group of its subnet's VPC. |
| CreateFleet | Creates an instant local fleet from launch-template configurations and on-demand or spot overrides. DryRun returns the AWS-compatible `DryRunOperation` error without launching instances. |
| DescribeInstances | Lists or returns stored EC2 instances. |
| TerminateInstances | Terminates instances and updates their stored lifecycle state. |
@@ -2181,12 +2181,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return "sg-default-" + region;
}
// Resolves the default VPC/security-group id actually on file for a region, falling back to
// the pre-lex00/floci#21 unscoped literal ("vpc-default"/"sg-default") when storage was persisted before
// ids were made region-scoped. Seeding (ensureDefaultResources) always assigns the new
// region-scoped id going forward; these resolvers only cover lookups against what may already
// be on disk. Without this, a region seeded under the old scheme would silently lose its
// default VPC/security group to every caller that resolves them by computed id.
// Persisted default VPCs may retain the unscoped id from before ids became region-scoped.
// Resolve against storage so callers still find the existing VPC instead of a computed id.
public String resolveDefaultVpcId(String region) {
String scoped = defaultVpcId(region);
if (vpcs.get(key(region, scoped)).isPresent()) {
@@ -2196,15 +2192,6 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return vpcs.get(key(region, legacy)).isPresent() ? legacy : scoped;
}
public String resolveDefaultSecurityGroupId(String region) {
String scoped = defaultSecurityGroupId(region);
if (securityGroups.get(key(region, scoped)).isPresent()) {
return scoped;
}
String legacy = "sg-default";
return securityGroups.get(key(region, legacy)).isPresent() ? legacy : scoped;
}
// Per-resource mutation locks (#1464): storage get() returns the live stored object, so
// unsynchronized list mutations race under parallel clients (Terraform runs 10-wide) and
// drop entries. Mutators take the resource's stripe and swap collections copy-on-write so
@@ -4064,11 +4051,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
sgIdentifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName()));
}
} else {
// Use default SG
SecurityGroup defaultSg = securityGroups.get(key(region, resolveDefaultSecurityGroupId(region))).orElse(null);
if (defaultSg != null) {
sgIdentifiers.add(new GroupIdentifier(defaultSg.getGroupId(), defaultSg.getGroupName()));
}
defaultSecurityGroupOf(region, vpcId).ifPresent(defaultSg ->
sgIdentifiers.add(new GroupIdentifier(defaultSg.getGroupId(), defaultSg.getGroupName())));
}
String reservationId = "r-" + randomHex(17);
@@ -270,6 +270,23 @@ class Ec2ServiceTest {
eni.getGroups().stream().map(GroupIdentifier::getGroupId).toList());
}
@Test
void runInstancesWithoutGroupsGetsItsSubnetVpcsDefaultGroup() {
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");
Instance instance = service.runInstances(region, "ami-test", "t3.micro", 1, 1, null,
List.of(), subnet.getSubnetId(), null, List.of(), null, null).getInstances().getFirst();
List<String> expected = List.of(service.defaultSecurityGroupOf(region, vpcId).orElseThrow().getGroupId());
assertEquals(vpcId, instance.getVpcId());
assertEquals(expected, instance.getSecurityGroups().stream().map(GroupIdentifier::getGroupId).toList());
assertEquals(expected, instance.getNetworkInterfaces().getFirst().getGroups().stream()
.map(GroupIdentifier::getGroupId).toList());
}
@Test
void defaultSecurityGroupOfIsEmptyOnceTheDefaultGroupIsGone() {
Ec2Service service = mockModeService();
@@ -4126,12 +4143,8 @@ class Ec2ServiceTest {
}
@Test
void resolveDefaultVpcAndSecurityGroupIdFallBackToPreRegionScopingStorage() throws Exception {
// #21 follow-up: persistent storage written before default ids were made region-scoped
// still carries the old literal "vpc-default"/"sg-default", never the new scoped form, and
// nothing re-seeds it (ensureDefaultResources skips a region that already has a VPC on
// file). Any lookup that blindly computed the new scoped id instead of resolving against
// what's actually stored would silently stop finding the region's real default VPC/SG.
void resolveDefaultVpcIdFallsBackToPreRegionScopingStorage() throws Exception {
// Existing regions are not re-seeded, so persisted VPCs can still have the old unscoped id.
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
@@ -4146,29 +4159,16 @@ class Ec2ServiceTest {
legacyVpc.setRegion("us-east-1");
putViaReflection(service, "vpcs", "us-east-1::vpc-default", legacyVpc);
SecurityGroup legacySg = new SecurityGroup();
legacySg.setGroupId("sg-default");
legacySg.setGroupName("default");
legacySg.setDescription("default VPC security group");
legacySg.setVpcId("vpc-default");
legacySg.setOwnerId("000000000000");
legacySg.setRegion("us-east-1");
putViaReflection(service, "securityGroups", "us-east-1::sg-default", legacySg);
assertEquals("vpc-default", service.resolveDefaultVpcId("us-east-1"),
"must resolve the pre-existing unscoped default VPC, not compute a fresh scoped id");
assertEquals("sg-default", service.resolveDefaultSecurityGroupId("us-east-1"),
"must resolve the pre-existing unscoped default security group, not compute a fresh scoped id");
SecurityGroup created = service.createSecurityGroup("us-east-1", "app", "app sg", null);
assertEquals("vpc-default", created.getVpcId(),
"a new security group with no explicit VpcId must attach to the real default VPC on file");
// A genuinely fresh region has neither format on file, so both resolvers fall back to the
// A genuinely fresh region has neither format on file, so the resolver falls back to the
// scoped form ensureDefaultResources would seed.
assertEquals(Ec2Service.defaultVpcId("eu-west-1"), service.resolveDefaultVpcId("eu-west-1"));
assertEquals(Ec2Service.defaultSecurityGroupId("eu-west-1"),
service.resolveDefaultSecurityGroupId("eu-west-1"));
}
@SuppressWarnings("unchecked")