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

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

* fix(ec2): preserve DescribeVpcs filter error precedence

* fix(ec2): remove obsolete shared VPC lookup catches
This commit is contained in:
Aniket Shukla authored and GitHub committed 2026-09-26 16:32:43 -05:00
1 parent d658c75a41
commit 5ace4281f3
10 files changed
+144 -32

No files matched your search

@@ -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;
}
@@ -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())
@@ -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()))
@@ -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) {
@@ -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",
@@ -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", """
@@ -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;
}
}
@@ -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),
@@ -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);
@@ -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");