Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(ec2): validate DescribeVpcs ids at the query boundary (#4482)

Aniket Shukla5ace4281f33d
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java
index 30fa7dd50d..3407c9a633 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java
@@ -1,13 +1,11 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
-import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Vpc;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
-import org.jboss.logging.Logger;
import java.util.List;
import java.util.Map;
@@ -20,8 +18,6 @@ import java.util.Set;
@ApplicationScoped
public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
- private static final Logger LOG = Logger.getLogger(Ec2VpcCfnProvisioner.class);
-
private final Ec2Service ec2Service;
@Inject
@@ -69,15 +65,8 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
if (priorPhysicalId == null || priorPhysicalId.isBlank()) {
return null;
}
- Vpc existing;
- try {
- existing = ec2Service.describeVpcs(region, List.of(priorPhysicalId), Map.of())
- .stream().findFirst().orElse(null);
- } catch (AwsException notFound) {
- // Expected when the VPC was deleted out of band since the prior update.
- LOG.debugv(notFound, "No existing VPC {0} found on file, falling back to create", priorPhysicalId);
- return null;
- }
+ Vpc existing = ec2Service.describeVpcs(region, List.of(priorPhysicalId), Map.of())
+ .stream().findFirst().orElse(null);
if (existing == null) {
return null;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
index 073de3247f..e819bbecb0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
@@ -1531,7 +1531,12 @@ public class Ec2QueryHandler {
private Response handleDescribeVpcs(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "VpcId");
Map<String, List<String>> filters = getFilters(p);
+ // Resolve the lookup first so unsupported filters retain their error precedence.
List<Vpc> vpcs = service.describeVpcs(region, ids, filters);
+ // Shared service callers decide their own missing-resource behavior, as with subnets.
+ for (String vpcId : ids) {
+ service.requireVpc(region, vpcId);
+ }
XmlBuilder xml = new XmlBuilder()
.start("DescribeVpcsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
index 12f2e6cc20..726fc27294 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
@@ -4043,11 +4043,6 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
// unsupported filter matches every VPC instead of narrowing anything. Real EC2 rejects the
// name outright, which is the difference between a wrong result and an error.
requireSupportedFilters(filters, VPC_FILTERS);
- if (!vpcIds.isEmpty()) {
- for (String id : vpcIds) {
- getRequiredVpc(region, id);
- }
- }
return vpcs.scan(k -> true).stream()
.filter(v -> v.getRegion().equals(region))
.filter(v -> vpcIds.isEmpty() || vpcIds.contains(v.getVpcId()))
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsTaskMetadataController.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsTaskMetadataController.java
index d9a0f5e002..42797dad27 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsTaskMetadataController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsTaskMetadataController.java
@@ -454,15 +454,9 @@ public class EcsTaskMetadataController {
if (subnet.getVpcId() == null || region == null) {
return null;
}
- try {
- return ec2Service.describeVpcs(region, List.of(subnet.getVpcId()), Map.of()).stream()
- .findFirst()
- .orElse(null);
- } catch (AwsException e) {
- LOG.debugv("Subnet {0} references a VPC that is gone: {1}",
- subnet.getSubnetId(), e.getMessage());
- return null;
- }
+ return ec2Service.describeVpcs(region, List.of(subnet.getVpcId()), Map.of()).stream()
+ .findFirst()
+ .orElse(null);
}
private static String taskSubnetId(EcsTask task) {
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.java
index 4eb94bbe57..0267ebbcd9 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
@@ -25,7 +25,6 @@ import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
-import io.github.hectorvent.floci.services.ec2.model.Vpc;
import io.github.hectorvent.floci.services.rds.container.AutoPauseListener;
import io.github.hectorvent.floci.services.rds.container.RdsContainerHandle;
import io.github.hectorvent.floci.services.rds.container.RdsContainerManager;
@@ -8389,8 +8388,8 @@ public class RdsService implements Resettable, ResourceProvider {
}
private void validateVpcHasIpv6CidrBlock(String vpcId, String region) {
- List<Vpc> vpcs = ec2Service.describeVpcs(region, List.of(vpcId), Map.of());
- boolean hasIpv6 = !vpcs.isEmpty() && vpcs.get(0).getIpv6CidrBlockAssociationSet().stream()
+ boolean hasIpv6 = ec2Service.describeVpcs(region, List.of(vpcId), Map.of()).stream()
+ .flatMap(vpc -> vpc.getIpv6CidrBlockAssociationSet().stream())
.anyMatch(assoc -> "associated".equalsIgnoreCase(assoc.getIpv6CidrBlockState()));
if (!hasIpv6) {
throw new AwsException("InvalidParameterValue",
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisionerTest.java
index 7090728bcc..046942bd10 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisionerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisionerTest.java
@@ -2,7 +2,6 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
-import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
@@ -143,7 +142,7 @@ class Ec2VpcCfnProvisionerTest {
@Test
void aVpcDeletedOutOfBandFallsBackToCreate() {
when(ec2.describeVpcs(REGION, List.of("vpc-gone"), Map.of()))
- .thenThrow(new AwsException("InvalidVpcID.NotFound", "not found", 400));
+ .thenReturn(List.of());
when(ec2.createVpc(anyString(), anyString(), anyBoolean())).thenReturn(vpc("vpc-fresh", "10.0.0.0/16"));
StackResource r = provision("vpc-gone", """
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DescribeVpcsNotFoundIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DescribeVpcsNotFoundIntegrationTest.java
new file mode 100644
index 0000000000..ec6df57c34
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DescribeVpcsNotFoundIntegrationTest.java
@@ -0,0 +1,83 @@
+package io.github.hectorvent.floci.services.ec2;
+
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.ValidatableResponse;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasItem;
+
+@QuarkusTest
+class Ec2DescribeVpcsNotFoundIntegrationTest {
+
+ private static final String UNKNOWN = "vpc-0000000000000dead";
+ private final List<String> createdVpcs = new ArrayList<>();
+
+ private static ValidatableResponse ec2(String action, String... formParams) {
+ RequestSpecification request = given().header("Authorization",
+ "AWS4-HMAC-SHA256 Credential=test/20260926/us-east-1/ec2/aws4_request")
+ .formParam("Action", action);
+ for (int i = 0; i < formParams.length; i += 2) {
+ request.formParam(formParams[i], formParams[i + 1]);
+ }
+ return request.when().post("/").then();
+ }
+
+ @AfterEach
+ void deleteCreatedVpcs() {
+ for (String vpcId : createdVpcs) {
+ ec2("DeleteVpc", "VpcId", vpcId).statusCode(200);
+ }
+ }
+
+ @Test
+ void unknownRequestedIdIsStillAnEc2Error() {
+ ec2("DescribeVpcs", "VpcId.1", UNKNOWN).statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidVpcID.NotFound"))
+ .body("Response.Errors.Error.Message", equalTo("The vpc ID '" + UNKNOWN + "' does not exist"));
+ }
+
+ @Test
+ void unsupportedFilterIsReportedBeforeAnUnknownRequestedId() {
+ ec2("DescribeVpcs", "VpcId.1", UNKNOWN, "Filter.1.Name", "unsupported-filter",
+ "Filter.1.Value.1", "value").statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
+ }
+
+ @Test
+ void unknownIdAmongKnownIdsIsStillAnEc2Error() {
+ String known = createVpc();
+ ec2("DescribeVpcs", "VpcId.1", known, "VpcId.2", UNKNOWN).statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidVpcID.NotFound"));
+ }
+
+ @Test
+ void knownIdAndUnfilteredListingStillReturnTheVpc() {
+ String known = createVpc();
+ ec2("DescribeVpcs", "VpcId.1", known).statusCode(200)
+ .body("DescribeVpcsResponse.vpcSet.item.vpcId", equalTo(known));
+ ec2("DescribeVpcs").statusCode(200)
+ .body("DescribeVpcsResponse.vpcSet.item.vpcId", hasItem(known));
+ }
+
+ @Test
+ void filteringOutAnExistingVpcDoesNotMakeItsIdUnknown() {
+ String known = createVpc();
+ ec2("DescribeVpcs", "VpcId.1", known, "Filter.1.Name", "cidr-block",
+ "Filter.1.Value.1", "10.96.0.0/16").statusCode(200)
+ .body("DescribeVpcsResponse.vpcSet.item.size()", equalTo(0));
+ }
+
+ private String createVpc() {
+ String id = ec2("CreateVpc", "CidrBlock", "10.95.0.0/16").statusCode(200)
+ .extract().path("CreateVpcResponse.vpc.vpcId");
+ createdVpcs.add(id);
+ return id;
+ }
+}
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.java
index ff168bf3ae..5121a67631 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
@@ -88,6 +88,24 @@ import static org.mockito.Mockito.when;
class Ec2ServiceTest {
+ @Test
+ void sharedDescribeVpcsOmitsUnknownIdsButExplicitLookupStillRejectsThem() {
+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
+ mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
+ new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
+ String region = "us-east-1";
+ String unknown = "vpc-0000000000000dead";
+ Vpc known = service.createVpc(region, "10.95.0.0/16", false);
+
+ assertTrue(service.describeVpcs(region, List.of(unknown), Map.of()).isEmpty());
+ assertEquals(List.of(known), service.describeVpcs(region, List.of(known.getVpcId(), unknown), Map.of()));
+ assertTrue(service.describeVpcs("eu-west-1", List.of(known.getVpcId()), Map.of()).isEmpty());
+ assertTrue(service.describeVpcs(region, List.of(known.getVpcId()),
+ Map.of("cidr-block", List.of("10.96.0.0/16"))).isEmpty());
+ assertEquals("InvalidVpcID.NotFound", assertThrows(AwsException.class,
+ () -> service.requireVpc(region, unknown)).getErrorCode());
+ }
+
@Test
void deleteVpcRemovesVpcOwnedDefaultResourcesAndRules() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsTaskMetadataControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsTaskMetadataControllerTest.java
index b0dd1ee62e..30e64d72c8 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsTaskMetadataControllerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsTaskMetadataControllerTest.java
@@ -264,6 +264,21 @@ class EcsTaskMetadataControllerTest {
assertEquals("vpc-0a1b2c3d", body(controller.task(METADATA_ID)).path("VPCID").asText());
}
+ @Test
+ void aDeletedVpcOmitsResolverMetadataWithoutLosingTheSubnetDetails() {
+ task.setLaunchType(LaunchType.EC2);
+ when(ec2Service.describeVpcs(anyString(), anyList(), anyMap())).thenReturn(List.of());
+
+ Response response = controller.task(METADATA_ID);
+ assertEquals(200, response.getStatus());
+ JsonNode metadata = body(response);
+ assertEquals("vpc-0a1b2c3d", metadata.path("VPCID").asText());
+ JsonNode network = metadata.path("Containers").get(0).path("Networks").get(0);
+ assertFalse(network.has("DomainNameServers"));
+ assertEquals("172.31.32.0/20", network.path("IPv4SubnetCIDRBlock").asText());
+ assertEquals("172.31.32.1/20", network.path("SubnetGatewayIpv4Address").asText());
+ }
+
@Test
void taskWithTagsAddsTheTaskAndContainerInstanceTags() {
task.setLaunchType(LaunchType.EC2);
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.java
index 83fe066c7f..db1b73f31b 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
@@ -4155,6 +4155,21 @@ class RdsServiceTest {
assertTrue(rdsService.listDbProxies(null).isEmpty());
}
+ @Test
+ void createDbProxyReportsItsOwnIpv6ErrorWhenVpcLookupReturnsEmpty() {
+ when(ec2Service.describeVpcs(eq("us-east-1"), eq(List.of("vpc-default")), eq(Map.of())))
+ .thenReturn(List.of());
+
+ AwsException rejected = assertThrows(AwsException.class, () ->
+ rdsService.createDbProxy("missing-vpc-proxy", "POSTGRESQL", true, false, "NONE",
+ PROXY_ROLE_ARN, PROXY_SUBNET_IDS, List.of(), PROXY_AUTH,
+ 1800, false, Map.of(), "us-east-1", "DUAL", null));
+
+ assertEquals("InvalidParameterValue", rejected.getErrorCode());
+ assertTrue(rejected.getMessage().contains("IPv6 CIDR block"));
+ assertTrue(rdsService.listDbProxies(null).isEmpty());
+ }
+
@Test
void createDbProxyAcceptsIpv6NetworkTypeWhenVpcHasIpv6CidrBlock() {
List<String> dualStackSubnetIds = List.of("subnet-dualstack-a", "subnet-dualstack-b");