Light, fluffy, and always free - The AWS Local Emulator alternative
fix(ec2): derive default vpc/subnet/sg ids per region (#2384)
lex00337dead734f2
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.javaindex 7782044340..1e6ee8804d 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java@@ -232,8 +232,10 @@ class RdsControlPlaneTest {String regionalProxyName = TestFixtures.uniqueName("rds-proxy-regional");try (RdsClient east = rdsClient(Region.US_EAST_1);RdsClient west = rdsClient(Region.US_WEST_2)) {- var eastProxy = createIamProxy(east, regionalProxyName);- var westProxy = createIamProxy(west, regionalProxyName);+ // Subnet ids are region-scoped on real AWS (and on floci, since #21), so each proxy+ // needs subnets from its own signed region rather than the shared us-east-1 subnetIds.+ var eastProxy = createIamProxy(east, regionalProxyName, subnetIdsFor(Region.US_EAST_1));+ var westProxy = createIamProxy(west, regionalProxyName, subnetIdsFor(Region.US_WEST_2));assertThat(eastProxy.dbProxy().dbProxyArn()).contains(":rds:us-east-1:");assertThat(westProxy.dbProxy().dbProxyArn()).contains(":rds:us-west-2:");@@ -344,15 +346,34 @@ class RdsControlPlaneTest {}}- private static CreateDbProxyResponse createIamProxy(RdsClient client, String name) {+ private static CreateDbProxyResponse createIamProxy(RdsClient client, String name, List<String> vpcSubnetIds) {return client.createDBProxy(b -> b.dbProxyName(name).engineFamily("POSTGRESQL").roleArn("arn:aws:iam::000000000000:role/rds-proxy-regional")- .vpcSubnetIds(subnetIds)+ .vpcSubnetIds(vpcSubnetIds).defaultAuthScheme("IAM_AUTH"));}+ private static List<String> subnetIdsFor(Region region) {+ try (Ec2Client ec2 = ec2Client(region)) {+ return ec2.describeSubnets().subnets().stream()+ .map(subnet -> subnet.subnetId())+ .sorted()+ .limit(2)+ .toList();+ }+ }++ private static Ec2Client ec2Client(Region region) {+ return Ec2Client.builder()+ .endpointOverride(TestFixtures.endpoint())+ .region(region)+ .credentialsProvider(StaticCredentialsProvider.create(+ AwsBasicCredentials.create("test", "test")))+ .build();+ }+private static software.amazon.awssdk.services.rds.model.CreateDbInstanceResponse createDbInstance(RdsClient client, String name, String password) {return client.createDBInstance(b -> bdiff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.javaindex 6af64590da..476bf8090b 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java@@ -339,7 +339,7 @@ public class Ec2Service implements ContainerTeardown {LOG.debugv("Seeding default EC2 resources for region {0}", region);// Default VPC- String vpcId = "vpc-default";+ String vpcId = defaultVpcId(region);Vpc defaultVpc = new Vpc();defaultVpc.setVpcId(vpcId);defaultVpc.setCidrBlock("172.31.0.0/16");@@ -354,7 +354,10 @@ public class Ec2Service implements ContainerTeardown {// Default subnets (a/b/c)String[] azSuffixes = {"a", "b", "c"};String[] cidrBlocks = {"172.31.0.0/20", "172.31.16.0/20", "172.31.32.0/20"};- String[] subnetIds = {"subnet-default-a", "subnet-default-b", "subnet-default-c"};+ String[] subnetIds = {+ defaultSubnetId(region, azSuffixes[0]),+ defaultSubnetId(region, azSuffixes[1]),+ defaultSubnetId(region, azSuffixes[2])};for (int i = 0; i < 3; i++) {Subnet subnet = new Subnet();subnet.setSubnetId(subnetIds[i]);@@ -372,7 +375,7 @@ public class Ec2Service implements ContainerTeardown {subnets.put(key(region, subnetIds[i]), subnet);}- createDefaultSecurityGroup(region, vpcId, "sg-default");+ createDefaultSecurityGroup(region, vpcId, defaultSecurityGroupId(region));// Default NACL, with the default subnets associated to it.String defaultAclId = createDefaultNetworkAcl(region, vpcId, "acl-default");@@ -869,6 +872,47 @@ public class Ec2Service implements ContainerTeardown {return region + "::" + id;}+ // Default resource ids must be derived per region (lex00/floci#21): every region seeds its own+ // default VPC/subnets/security group independently, but a literal id like "vpc-default"+ // is identical text in every region's response even though storage itself is already+ // correctly keyed by region. RdsService derives the same ids from these methods so its+ // default DB subnet group resolves against the right region's default VPC.+ public static String defaultVpcId(String region) {+ return "vpc-default-" + region;+ }++ public static String defaultSubnetId(String region, String azSuffix) {+ return "subnet-default-" + region + "-" + azSuffix;+ }++ public static String defaultSecurityGroupId(String region) {+ 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.+ public String resolveDefaultVpcId(String region) {+ String scoped = defaultVpcId(region);+ if (vpcs.get(key(region, scoped)).isPresent()) {+ return scoped;+ }+ String legacy = "vpc-default";+ 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@@ -2067,7 +2111,7 @@ public class Ec2Service implements ContainerTeardown {.orElse(null);}- String vpcId = subnet != null ? subnet.getVpcId() : "vpc-default";+ String vpcId = subnet != null ? subnet.getVpcId() : resolveDefaultVpcId(region);String az = subnet != null ? subnet.getAvailabilityZone() : region + "a";String finalSubnetId = subnet != null ? subnet.getSubnetId() : null;@@ -2080,7 +2124,7 @@ public class Ec2Service implements ContainerTeardown {}} else {// Use default SG- SecurityGroup defaultSg = securityGroups.get(key(region, "sg-default")).orElse(null);+ SecurityGroup defaultSg = securityGroups.get(key(region, resolveDefaultSecurityGroupId(region))).orElse(null);if (defaultSg != null) {sgIdentifiers.add(new GroupIdentifier(defaultSg.getGroupId(), defaultSg.getGroupName()));}@@ -2848,7 +2892,7 @@ public class Ec2Service implements ContainerTeardown {if (vpcId != null && !vpcId.isEmpty()) {getRequiredVpc(region, vpcId);} else {- vpcId = "vpc-default";+ vpcId = resolveDefaultVpcId(region);}// Check duplicateString finalVpcId = vpcId;@@ -4608,7 +4652,7 @@ public class Ec2Service implements ContainerTeardown {ensureDefaultResources(region);Map<String, String> attrs = new LinkedHashMap<>();attrs.put("supported-platforms", "VPC");- attrs.put("default-vpc", "vpc-default");+ attrs.put("default-vpc", resolveDefaultVpcId(region));return attrs;}diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.javaindex 598ac8b8c5..57a86e55c2 100644--- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java@@ -4663,7 +4663,8 @@ public class RdsService implements Resettable {}private DbSubnetGroup buildDefaultSubnetGroup(String region) {- List<Subnet> subnets = ec2Service.describeSubnets(region, List.of(), Map.of("vpc-id", List.of("vpc-default")));+ List<Subnet> subnets = ec2Service.describeSubnets(region, List.of(),+ Map.of("vpc-id", List.of(ec2Service.resolveDefaultVpcId(region))));if (subnets.isEmpty()) {throw new AwsException("InvalidVPCNetworkStateFault","No subnets available for DB subnet group default.", 400);diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingIntegrationTest.javaindex 5f8bf5f43b..e2949b661f 100644--- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingIntegrationTest.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.autoscaling;+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;@@ -37,7 +38,7 @@ class AutoScalingIntegrationTest {.formParam("LaunchConfigurationName", "my-lc").formParam("ImageId", "ami-12345678").formParam("InstanceType", "t3.micro")- .formParam("SecurityGroups.member.1", "sg-default")+ .formParam("SecurityGroups.member.1", Ec2Service.defaultSecurityGroupId("us-east-1")).header("Authorization", AUTH).when().post("/")diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.javaindex 3c64e26bcc..ec4b9558d6 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.cloudformation;+import io.github.hectorvent.floci.services.ec2.Ec2Service;import io.github.hectorvent.floci.testing.MutableClock;import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;import io.quarkus.test.junit.QuarkusTest;@@ -6208,12 +6209,12 @@ class CloudFormationIntegrationTest {"Properties": {"GroupName": "%s","GroupDescription": "Security group created by CloudFormation",- "VpcId": "vpc-default"+ "VpcId": "%s"}}}}- """.formatted(groupName);+ """.formatted(groupName, Ec2Service.defaultVpcId("us-east-1"));given().formParam("Action", "CreateStack")@@ -6371,7 +6372,7 @@ class CloudFormationIntegrationTest {"Name": "cfn-alb","Type": "application","Scheme": "internet-facing",- "Subnets": ["subnet-default-a", "subnet-default-b"],+ "Subnets": ["%s", "%s"],"SecurityGroups": ["sg-123"]}},@@ -6381,7 +6382,7 @@ class CloudFormationIntegrationTest {"Name": "cfn-tg","Protocol": "HTTP","Port": 80,- "VpcId": "vpc-default",+ "VpcId": "%s","TargetType": "ip","HealthCheckPath": "/health","Matcher": { "HttpCode": "200-299" }@@ -6424,7 +6425,8 @@ class CloudFormationIntegrationTest {"RuleRef": { "Value": { "Ref": "Rule" } }}}- """;+ """.formatted(Ec2Service.defaultSubnetId("us-east-1", "a"), Ec2Service.defaultSubnetId("us-east-1", "b"),+ Ec2Service.defaultVpcId("us-east-1"));String stackName = "cfn-elbv2-stack";diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRdsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRdsIntegrationTest.javaindex 45efa287a2..768e1915b3 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRdsIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRdsIntegrationTest.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.cloudformation;import io.github.hectorvent.floci.core.common.XmlParser;+import io.github.hectorvent.floci.services.ec2.Ec2Service;import io.quarkus.test.junit.QuarkusTest;import org.junit.jupiter.api.Test;@@ -36,7 +37,7 @@ class CloudFormationRdsIntegrationTest {"Properties": {"DBSubnetGroupName": "%s","DBSubnetGroupDescription": "managed by cfn",- "SubnetIds": ["subnet-default-a", "subnet-default-b"]+ "SubnetIds": ["%s", "%s"]}}},@@ -44,7 +45,8 @@ class CloudFormationRdsIntegrationTest {"GroupName": {"Value": {"Ref": "DbSubnets"}}}}- """.formatted(groupName);+ """.formatted(groupName, Ec2Service.defaultSubnetId("us-east-1", "a"),+ Ec2Service.defaultSubnetId("us-east-1", "b"));given().contentType("application/x-www-form-urlencoded")@@ -169,7 +171,7 @@ class CloudFormationRdsIntegrationTest {"Properties": {"DBSubnetGroupName": "%s","DBSubnetGroupDescription": "managed by cfn",- "SubnetIds": ["subnet-default-a", "subnet-default-b"]+ "SubnetIds": ["%s", "%s"]}}},@@ -177,6 +179,7 @@ class CloudFormationRdsIntegrationTest {"GroupName": {"Value": {"Ref": "DbSubnets"}}}}- """.formatted(groupName);+ """.formatted(groupName, Ec2Service.defaultSubnetId("us-east-1", "a"),+ Ec2Service.defaultSubnetId("us-east-1", "b"));}}diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.javaindex 0dae56b0bd..a93aa691f9 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IntegrationTest.java@@ -85,7 +85,7 @@ class Ec2IntegrationTest {.then().statusCode(200).contentType("application/xml")- .body("DescribeVpcsResponse.vpcSet.item[0].vpcId", equalTo("vpc-default"))+ .body("DescribeVpcsResponse.vpcSet.item[0].vpcId", equalTo(Ec2Service.defaultVpcId("us-east-1"))).body("DescribeVpcsResponse.vpcSet.item[0].cidrBlock", equalTo("172.31.0.0/16")).body("DescribeVpcsResponse.vpcSet.item[0].isDefault", equalTo("true"));}@@ -99,7 +99,7 @@ class Ec2IntegrationTest {given().formParam("Action", "DescribeSubnets").formParam("Filter.1.Name", "vpc-id")- .formParam("Filter.1.Value.1", "vpc-default")+ .formParam("Filter.1.Value.1", Ec2Service.defaultVpcId("us-east-1")).header("Authorization", AUTH_HEADER).when().post("/")@@ -124,7 +124,7 @@ class Ec2IntegrationTest {.formParam("Filter.1.Name", "group-name").formParam("Filter.1.Value.1", "default").formParam("Filter.2.Name", "vpc-id")- .formParam("Filter.2.Value.1", "vpc-default")+ .formParam("Filter.2.Value.1", Ec2Service.defaultVpcId("us-east-1")).header("Authorization", AUTH_HEADER).when().post("/")@@ -134,7 +134,7 @@ class Ec2IntegrationTest {.body("DescribeSecurityGroupsResponse.securityGroupInfo.item[0].groupName", equalTo("default")).body("DescribeSecurityGroupsResponse.securityGroupInfo.item[0].groupDescription",equalTo("default VPC security group"))- .body("DescribeSecurityGroupsResponse.securityGroupInfo.item[0].vpcId", equalTo("vpc-default"));+ .body("DescribeSecurityGroupsResponse.securityGroupInfo.item[0].vpcId", equalTo(Ec2Service.defaultVpcId("us-east-1")));}// =========================================================================@@ -1312,7 +1312,7 @@ class Ec2IntegrationTest {given().formParam("Action", "DescribeSecurityGroupRules").formParam("Filter.1.Name", "group-id")- .formParam("Filter.1.Value.1", "sg-default")+ .formParam("Filter.1.Value.1", Ec2Service.defaultSecurityGroupId("us-east-1")).header("Authorization", AUTH_HEADER).when().post("/")diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.javaindex 29550af048..abfcec7ee9 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java@@ -26,6 +26,7 @@ import io.github.hectorvent.floci.services.ec2.model.NetworkInterface;import io.github.hectorvent.floci.services.ec2.model.Reservation;import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;import io.github.hectorvent.floci.services.ec2.model.Snapshot;+import io.github.hectorvent.floci.services.ec2.model.Subnet;import io.github.hectorvent.floci.services.ec2.model.Tag;import io.github.hectorvent.floci.services.ec2.model.TransitGateway;import io.github.hectorvent.floci.services.ec2.model.TransitGatewayOptions;@@ -34,7 +35,7 @@ import io.github.hectorvent.floci.services.ec2.model.TransitGatewayRouteTable;import io.github.hectorvent.floci.services.ec2.model.TransitGatewayRouteTablePropagation;import io.github.hectorvent.floci.services.ec2.model.TransitGatewayVpcAttachment;import io.github.hectorvent.floci.services.ec2.model.TransitGatewayVpcAttachmentOptions;-import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair;+import io.github.hectorvent.floci.services.ec2.model.Vpc;import io.github.hectorvent.floci.services.ec2.model.VpcEndpoint;import io.github.hectorvent.floci.services.ec2.model.Volume;import io.github.hectorvent.floci.services.ec2.model.VolumeAttachment;@@ -242,6 +243,107 @@ class Ec2ServiceTest {assertEquals(List.of("arm64"), types.getFirst().get("supportedArchitectures"));}+ @Test+ void defaultVpcSubnetAndSecurityGroupIdsAreRegionScoped() {+ // #21: the default VPC/subnets/security group were literal ids ("vpc-default",+ // "subnet-default-a/b/c", "sg-default") reused as-is in every region. Storage was+ // already correctly keyed by region, so nothing actually collided server-side, but every+ // region's DescribeVpcs/DescribeSubnets/DescribeSecurityGroups echoed identical ids back+ // to the caller, making the two regions' default resources indistinguishable from an SDK+ // or CLI client's point of view.+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),+ mock(Ec2PortForwardManager.class),+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),+ new InMemoryStorageFactory());++ Vpc usEastVpc = service.describeVpcs("us-east-1", List.of(), Map.of()).getFirst();+ Vpc euWestVpc = service.describeVpcs("eu-west-1", List.of(), Map.of()).getFirst();++ assertNotEquals(usEastVpc.getVpcId(), euWestVpc.getVpcId(),+ "default VPC id must differ per region");+ assertEquals(Ec2Service.defaultVpcId("us-east-1"), usEastVpc.getVpcId());+ assertEquals(Ec2Service.defaultVpcId("eu-west-1"), euWestVpc.getVpcId());++ List<String> usEastSubnetIds = service.describeSubnets("us-east-1", List.of(), Map.of()).stream()+ .map(Subnet::getSubnetId).sorted().toList();+ List<String> euWestSubnetIds = service.describeSubnets("eu-west-1", List.of(), Map.of()).stream()+ .map(Subnet::getSubnetId).sorted().toList();++ assertTrue(usEastSubnetIds.stream().noneMatch(euWestSubnetIds::contains),+ "default subnet ids must not collide across regions: " + usEastSubnetIds + " vs " + euWestSubnetIds);+ assertEquals(List.of(+ Ec2Service.defaultSubnetId("us-east-1", "a"),+ Ec2Service.defaultSubnetId("us-east-1", "b"),+ Ec2Service.defaultSubnetId("us-east-1", "c"))+ .stream().sorted().toList(),+ usEastSubnetIds);++ SecurityGroup usEastSg = service.describeSecurityGroups("us-east-1", List.of(), List.of("default"), Map.of())+ .getFirst();+ SecurityGroup euWestSg = service.describeSecurityGroups("eu-west-1", List.of(), List.of("default"), Map.of())+ .getFirst();++ assertNotEquals(usEastSg.getGroupId(), euWestSg.getGroupId(),+ "default security group id must differ per region");+ assertEquals(Ec2Service.defaultSecurityGroupId("us-east-1"), usEastSg.getGroupId());+ assertEquals(Ec2Service.defaultSecurityGroupId("eu-west-1"), euWestSg.getGroupId());+ }++ @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.+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),+ mock(Ec2PortForwardManager.class),+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),+ new InMemoryStorageFactory());++ Vpc legacyVpc = new Vpc();+ legacyVpc.setVpcId("vpc-default");+ legacyVpc.setCidrBlock("172.31.0.0/16");+ legacyVpc.setState("available");+ legacyVpc.setDefault(true);+ legacyVpc.setOwnerId("000000000000");+ 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+ // 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")+ private static <T> void putViaReflection(Ec2Service service, String fieldName, String key, T value)+ throws Exception {+ var field = Ec2Service.class.getDeclaredField(fieldName);+ field.setAccessible(true);+ var backend = (io.github.hectorvent.floci.core.storage.StorageBackend<String, T>) field.get(service);+ backend.put(key, value);+ }+@Testvoid endpointNetworkInterfacesSynthesizesStableEnisForInterfaceEndpoints() {Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),@@ -249,11 +351,11 @@ class Ec2ServiceTest {mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),new InMemoryStorageFactory());String subnetId = service.describeSubnets("us-east-1", List.of(),- Map.of("vpc-id", List.of("vpc-default"))).getFirst().getSubnetId();- VpcEndpoint endpoint = service.createVpcEndpoint("us-east-1", "vpc-default",+ Map.of("vpc-id", List.of(Ec2Service.defaultVpcId("us-east-1")))).getFirst().getSubnetId();+ VpcEndpoint endpoint = service.createVpcEndpoint("us-east-1", Ec2Service.defaultVpcId("us-east-1"),"com.amazonaws.us-east-1.s3", "Interface",List.of(), List.of(subnetId), List.of(), null, List.of());- service.createVpcEndpoint("us-east-1", "vpc-default",+ service.createVpcEndpoint("us-east-1", Ec2Service.defaultVpcId("us-east-1"),"com.amazonaws.us-east-1.dynamodb", "Gateway",List.of(), List.of(), List.of(), null, List.of());@@ -262,7 +364,7 @@ class Ec2ServiceTest {assertEquals(1, enis.size(), "only Interface endpoints have ENIs");NetworkInterface eni = enis.getFirst();assertEquals(subnetId, eni.getSubnetId());- assertEquals("vpc-default", eni.getVpcId());+ assertEquals(Ec2Service.defaultVpcId("us-east-1"), eni.getVpcId());assertEquals("VPC Endpoint Interface " + endpoint.getVpcEndpointId(), eni.getDescription());assertTrue(eni.getNetworkInterfaceId().startsWith("eni-"));@@ -280,7 +382,7 @@ class Ec2ServiceTest {mock(Ec2PortForwardManager.class),mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),new InMemoryStorageFactory());- SecurityGroup web = service.createSecurityGroup("us-east-1", "web", "web sg", "vpc-default");+ SecurityGroup web = service.createSecurityGroup("us-east-1", "web", "web sg", Ec2Service.defaultVpcId("us-east-1"));Reservation reservation = service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro",1, 1, null, List.of(), null, null, List.of(), null, null);String instanceId = reservation.getInstances().getFirst().getInstanceId();diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.javaindex 9bb67c36fc..e1ad966e2e 100644--- a/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksServiceTest.java@@ -351,7 +351,8 @@ class EksServiceTest {new EksOidcService(storageFactory, new ObjectMapper()));ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();- vpcConfig.setSubnetIds(List.of("subnet-default-a", "subnet-default-b"));+ vpcConfig.setSubnetIds(List.of(Ec2Service.defaultSubnetId("us-east-1", "a"),+ Ec2Service.defaultSubnetId("us-east-1", "b")));CreateClusterRequest req = new CreateClusterRequest();req.setName("real-subnet-cluster");@@ -361,7 +362,8 @@ class EksServiceTest {Cluster cluster = service.createCluster(req);assertEquals("real-subnet-cluster", cluster.getName());- assertEquals(List.of("subnet-default-a", "subnet-default-b"),+ assertEquals(List.of(Ec2Service.defaultSubnetId("us-east-1", "a"),+ Ec2Service.defaultSubnetId("us-east-1", "b")),cluster.getResourcesVpcConfig().getSubnetIds());}@@ -384,7 +386,8 @@ class EksServiceTest {realEc2Service(), new EksOidcService(storageFactory, new ObjectMapper()));ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();- vpcConfig.setSubnetIds(List.of("subnet-default-a", "subnet-default-b"));+ vpcConfig.setSubnetIds(List.of(Ec2Service.defaultSubnetId("us-east-1", "a"),+ Ec2Service.defaultSubnetId("us-east-1", "b")));CreateClusterRequest req = new CreateClusterRequest();req.setName("vpc-id-cluster");@@ -393,7 +396,7 @@ class EksServiceTest {Cluster cluster = service.createCluster(req);- assertEquals("vpc-default", cluster.getResourcesVpcConfig().getVpcId());+ assertEquals(Ec2Service.defaultVpcId("us-east-1"), cluster.getResourcesVpcConfig().getVpcId());}@Test@@ -413,7 +416,7 @@ class EksServiceTest {realEc2Service(), new EksOidcService(storageFactory, new ObjectMapper()));ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();- vpcConfig.setSubnetIds(List.of("subnet-default-a"));+ vpcConfig.setSubnetIds(List.of(Ec2Service.defaultSubnetId("eu-west-2", "a")));CreateClusterRequest req = new CreateClusterRequest();req.setName("cross-region-cluster");@@ -431,11 +434,12 @@ class EksServiceTest {// A subnet that exists in the DEFAULT region and nowhere else.//// The distinction matters: requireSubnet() calls ensureDefaultResources()- // on whatever region it is handed, which seeds subnet-default-a/b/c- // there on the spot. So a default subnet id resolves in EVERY region and- // cannot discriminate between "validated against the request region" and- // "validated against the configured default" β a test written with one- // passes with or without the fix.+ // on whatever region it is handed, which seeds that region's own default+ // subnets there on the spot. Before #21's fix, those default subnets shared+ // the same literal id in every region, so a default subnet id resolved in+ // EVERY region and could not discriminate between "validated against the+ // request region" and "validated against the configured default" β a test+ // written with one passes with or without the fix.//// An explicitly created subnet is not seeded anywhere else, so asking// for it from a different region is the only thing that pins the@@ -450,7 +454,7 @@ class EksServiceTest {Ec2Service ec2Service = realEc2Service();ec2Service.ensureDefaultResources("us-east-1");String usEastOnlySubnet = ec2Service- .createSubnet("us-east-1", "vpc-default", "172.31.200.0/24", "us-east-1a")+ .createSubnet("us-east-1", Ec2Service.defaultVpcId("us-east-1"), "172.31.200.0/24", "us-east-1a").getSubnetId();// The request is for eu-west-2, where that subnet does not exist.diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2IntegrationTest.javaindex e3b5ce301f..70c5d89a42 100644--- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2IntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2IntegrationTest.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.elbv2;+import io.github.hectorvent.floci.services.ec2.Ec2Service;import io.quarkus.test.junit.QuarkusTest;import org.junit.jupiter.api.MethodOrderer;import org.junit.jupiter.api.Order;@@ -40,8 +41,8 @@ class ElbV2IntegrationTest {.formParam("Type", "application").formParam("Scheme", "internet-facing").formParam("IpAddressType", "ipv4")- .formParam("Subnets.member.1", "subnet-default-a")- .formParam("Subnets.member.2", "subnet-default-b")+ .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("/")@@ -57,7 +58,7 @@ class ElbV2IntegrationTest {.body("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.State.Code",equalTo("provisioning")).body("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.AvailabilityZones.member.SubnetId",- hasItems("subnet-default-a", "subnet-default-b"))+ hasItems(Ec2Service.defaultSubnetId("us-east-1", "a"), Ec2Service.defaultSubnetId("us-east-1", "b"))).body("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.DNSName",containsString(".elb.localhost.floci.io")).extract()@@ -80,7 +81,7 @@ class ElbV2IntegrationTest {.body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.State.Code",equalTo("active")).body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.AvailabilityZones.member.SubnetId",- hasItems("subnet-default-a", "subnet-default-b"));+ hasItems(Ec2Service.defaultSubnetId("us-east-1", "a"), Ec2Service.defaultSubnetId("us-east-1", "b")));}@Test@@ -184,8 +185,8 @@ class ElbV2IntegrationTest {.formParam("Action", "CreateLoadBalancer").formParam("Name", "lb-with-subnets").formParam("Type", "application")- .formParam("Subnets.member.1", "subnet-default-a")- .formParam("Subnets.member.2", "subnet-default-b")+ .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("/")@@ -195,11 +196,11 @@ class ElbV2IntegrationTest {.body("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.AvailabilityZones.member.size()",equalTo(2)).body("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.AvailabilityZones.member[0].SubnetId",- equalTo("subnet-default-a"))+ equalTo(Ec2Service.defaultSubnetId("us-east-1", "a"))).body("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.AvailabilityZones.member[0].ZoneName",equalTo("us-east-1a")).body("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.AvailabilityZones.member[1].SubnetId",- equalTo("subnet-default-b"))+ equalTo(Ec2Service.defaultSubnetId("us-east-1", "b"))).body("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.AvailabilityZones.member[1].ZoneName",equalTo("us-east-1b")).extract()@@ -216,11 +217,11 @@ class ElbV2IntegrationTest {.body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.AvailabilityZones.member.size()",equalTo(2)).body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.AvailabilityZones.member[0].SubnetId",- equalTo("subnet-default-a"))+ equalTo(Ec2Service.defaultSubnetId("us-east-1", "a"))).body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.AvailabilityZones.member[0].ZoneName",equalTo("us-east-1a")).body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.AvailabilityZones.member[1].SubnetId",- equalTo("subnet-default-b"))+ equalTo(Ec2Service.defaultSubnetId("us-east-1", "b"))).body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.AvailabilityZones.member[1].ZoneName",equalTo("us-east-1b"));}@@ -231,8 +232,8 @@ class ElbV2IntegrationTest {given().formParam("Action", "SetSubnets").formParam("LoadBalancerArn", lbArn)- .formParam("Subnets.member.1", "subnet-default-b")- .formParam("Subnets.member.2", "subnet-default-c")+ .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "b"))+ .formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "c")).header("Authorization", AUTH).when().post("/")@@ -252,7 +253,7 @@ class ElbV2IntegrationTest {.then().statusCode(200).body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.AvailabilityZones.member.SubnetId",- hasItems("subnet-default-b", "subnet-default-c"));+ hasItems(Ec2Service.defaultSubnetId("us-east-1", "b"), Ec2Service.defaultSubnetId("us-east-1", "c")));}// ββ Target Groups βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -288,7 +289,7 @@ class ElbV2IntegrationTest {.formParam("Action", "CreateLoadBalancer").formParam("Name", "mixed-vpc-lb").formParam("Type", "application")- .formParam("Subnets.member.1", "subnet-default-a")+ .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a")).formParam("Subnets.member.2", otherSubnetId).header("Authorization", AUTH).when()@@ -329,8 +330,8 @@ class ElbV2IntegrationTest {.formParam("Action", "CreateLoadBalancer").formParam("Name", "set-subnets-test-lb").formParam("Type", "application")- .formParam("Subnets.member.1", "subnet-default-a")- .formParam("Subnets.member.2", "subnet-default-b")+ .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("/")@@ -342,7 +343,7 @@ class ElbV2IntegrationTest {given().formParam("Action", "SetSubnets").formParam("LoadBalancerArn", subnetLbArn)- .formParam("Subnets.member.1", "subnet-default-a")+ .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a")).formParam("Subnets.member.2", otherSubnetId).header("Authorization", AUTH).when()@@ -359,7 +360,7 @@ class ElbV2IntegrationTest {.formParam("Action", "CreateLoadBalancer").formParam("Name", "single-subnet-lb").formParam("Type", "application")- .formParam("Subnets.member.1", "subnet-default-a")+ .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a")).header("Authorization", AUTH).when().post("/")@@ -373,7 +374,7 @@ class ElbV2IntegrationTest {void createLoadBalancerWithSubnetsInSameAvailabilityZoneThrowsInvalidConfigurationRequest() {String secondSubnetId = given().formParam("Action", "CreateSubnet")- .formParam("VpcId", "vpc-default")+ .formParam("VpcId", Ec2Service.defaultVpcId("us-east-1")).formParam("CidrBlock", "172.31.64.0/24").formParam("AvailabilityZone", "us-east-1a").header("Authorization", EC2_AUTH)@@ -388,7 +389,7 @@ class ElbV2IntegrationTest {.formParam("Action", "CreateLoadBalancer").formParam("Name", "duplicate-az-lb").formParam("Type", "application")- .formParam("Subnets.member.1", "subnet-default-a")+ .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a")).formParam("Subnets.member.2", secondSubnetId).header("Authorization", AUTH).when()@@ -403,7 +404,7 @@ class ElbV2IntegrationTest {void setSubnetsWithSubnetsInSameAvailabilityZoneThrowsInvalidConfigurationRequest() {String secondSubnetId = given().formParam("Action", "CreateSubnet")- .formParam("VpcId", "vpc-default")+ .formParam("VpcId", Ec2Service.defaultVpcId("us-east-1")).formParam("CidrBlock", "172.31.65.0/24").formParam("AvailabilityZone", "us-east-1a").header("Authorization", EC2_AUTH)@@ -429,7 +430,7 @@ class ElbV2IntegrationTest {given().formParam("Action", "SetSubnets").formParam("LoadBalancerArn", subnetlessLbArn)- .formParam("Subnets.member.1", "subnet-default-a")+ .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a")).formParam("Subnets.member.2", secondSubnetId).header("Authorization", AUTH).when()diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.javaindex 3cc792e463..cdd7cdd411 100644--- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java@@ -123,6 +123,8 @@ class RdsServiceTest {when(containerManager.start(any(), any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(new RdsContainerHandle("cont-id", "id", "localhost", 5432));+ when(ec2Service.resolveDefaultVpcId(any()))+ .thenAnswer(invocation -> Ec2Service.defaultVpcId(invocation.getArgument(0)));when(ec2Service.describeSubnets(any(), anyList(), any())).thenAnswer(invocation -> {@SuppressWarnings("unchecked")