From a283c7a49bf416360f5f493952d3e99419a43f8f Mon Sep 17 00:00:00 2001 From: mrfelek <17274927+mrfelek@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:30:09 +0100 Subject: [PATCH] fix(ec2): honour DryRun on the VPC, subnet, internet gateway and route table calls (#9018) * fix(ec2): honour DryRun on the VPC, subnet, internet gateway and route table calls --- .../aws/services/ec2/Ec2QueryHandler.java | 21 +- .../io/floci/aws/services/ec2/Ec2Service.java | 107 +++++++++- .../ec2/Ec2DryRunIamIntegrationTest.java | 65 ++++-- .../ec2/Ec2VpcDryRunIntegrationTest.java | 196 ++++++++++++++++++ .../ElbV2SubnetDependencyIntegrationTest.java | 2 +- 5 files changed, 359 insertions(+), 32 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/ec2/Ec2VpcDryRunIntegrationTest.java diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java b/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java index 0d567fb9ce..54b83f77d2 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2QueryHandler.java @@ -1825,7 +1825,7 @@ public class Ec2QueryHandler { } private Response handleDeleteVpc(MultivaluedMap p, String region) { - service.deleteVpc(region, p.getFirst("VpcId")); + service.deleteVpc(region, p.getFirst("VpcId"), dryRun(p)); return booleanResponse("DeleteVpc"); } @@ -3501,6 +3501,7 @@ public class Ec2QueryHandler { private Response handleCreateDefaultVpc(MultivaluedMap p, String region) { + checkDryRun(p); Vpc vpc = service.createDefaultVpc(region); XmlBuilder xml = new XmlBuilder() .start("CreateDefaultVpcResponse", AwsNamespaces.EC2) @@ -3618,7 +3619,7 @@ public class Ec2QueryHandler { } private Response handleDeleteSubnet(MultivaluedMap p, String region) { - service.deleteSubnet(region, p.getFirst("SubnetId")); + service.deleteSubnet(region, p.getFirst("SubnetId"), dryRun(p)); return booleanResponse("DeleteSubnet"); } @@ -4344,6 +4345,7 @@ public class Ec2QueryHandler { private Response handleCreateInternetGateway(MultivaluedMap p, String region) { List resourceTags = parseTagsForResource(p, "internet-gateway"); + checkDryRun(p); InternetGateway igw = service.createInternetGateway(region); applyResourceTags(resourceTags, region, igw.getInternetGatewayId()); XmlBuilder xml = new XmlBuilder() @@ -4370,17 +4372,17 @@ public class Ec2QueryHandler { } private Response handleDeleteInternetGateway(MultivaluedMap p, String region) { - service.deleteInternetGateway(region, p.getFirst("InternetGatewayId")); + service.deleteInternetGateway(region, p.getFirst("InternetGatewayId"), dryRun(p)); return booleanResponse("DeleteInternetGateway"); } private Response handleAttachInternetGateway(MultivaluedMap p, String region) { - service.attachInternetGateway(region, p.getFirst("InternetGatewayId"), p.getFirst("VpcId")); + service.attachInternetGateway(region, p.getFirst("InternetGatewayId"), p.getFirst("VpcId"), dryRun(p)); return booleanResponse("AttachInternetGateway"); } private Response handleDetachInternetGateway(MultivaluedMap p, String region) { - service.detachInternetGateway(region, p.getFirst("InternetGatewayId"), p.getFirst("VpcId")); + service.detachInternetGateway(region, p.getFirst("InternetGatewayId"), p.getFirst("VpcId"), dryRun(p)); return booleanResponse("DetachInternetGateway"); } @@ -4389,7 +4391,7 @@ public class Ec2QueryHandler { private Response handleCreateRouteTable(MultivaluedMap p, String region) { List resourceTags = parseTagsForResource(p, "route-table"); String vpcId = p.getFirst("VpcId"); - RouteTable rt = service.createRouteTable(region, vpcId); + RouteTable rt = service.createRouteTable(region, vpcId, dryRun(p)); applyResourceTags(resourceTags, region, rt.getRouteTableId()); XmlBuilder xml = new XmlBuilder() .start("CreateRouteTableResponse", AwsNamespaces.EC2) @@ -4420,14 +4422,14 @@ public class Ec2QueryHandler { } private Response handleDeleteRouteTable(MultivaluedMap p, String region) { - service.deleteRouteTable(region, p.getFirst("RouteTableId")); + service.deleteRouteTable(region, p.getFirst("RouteTableId"), dryRun(p)); return booleanResponse("DeleteRouteTable"); } private Response handleAssociateRouteTable(MultivaluedMap p, String region) { String rtId = p.getFirst("RouteTableId"); String subnetId = p.getFirst("SubnetId"); - RouteTableAssociation assoc = service.associateRouteTable(region, rtId, subnetId); + RouteTableAssociation assoc = service.associateRouteTable(region, rtId, subnetId, dryRun(p)); XmlBuilder xml = new XmlBuilder() .start("AssociateRouteTableResponse", AwsNamespaces.EC2) .elem("requestId", UUID.randomUUID().toString()) @@ -4440,6 +4442,7 @@ public class Ec2QueryHandler { } private Response handleDisassociateRouteTable(MultivaluedMap p, String region) { + checkDryRun(p); service.disassociateRouteTable(region, p.getFirst("AssociationId")); return booleanResponse("DisassociateRouteTable"); } @@ -4505,7 +4508,7 @@ public class Ec2QueryHandler { String dest = p.getFirst("DestinationCidrBlock"); String destIpv6 = p.getFirst("DestinationIpv6CidrBlock"); String destPrefixList = p.getFirst("DestinationPrefixListId"); - service.deleteRoute(region, rtId, dest, destIpv6, destPrefixList); + service.deleteRoute(region, rtId, dest, destIpv6, destPrefixList, dryRun(p)); return booleanResponse("DeleteRoute"); } diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java index 14f75f1408..e41e0fea32 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -7027,6 +7027,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } public void deleteVpc(String region, String vpcId) { + deleteVpc(region, vpcId, false); + } + + /** + * As above; with {@code dryRun} the VPC must exist and hold nothing DeleteVpc refuses to delete it + * with, and the request is then answered with DryRunOperation, the VPC and its default resources kept. + */ + public void deleteVpc(String region, String vpcId, boolean dryRun) { ensureDefaultResources(region); getRequiredVpc(region, vpcId); synchronized (attachmentTopologyLock(region)) { @@ -7036,6 +7044,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab requireNoProviderDependency(provider -> provider.hasVpcDependency(region, vpcId), "The vpc '" + vpcId + "' has dependencies and cannot be deleted."); requireNoVpcDependents(region, vpcId); + if (dryRun) { + throw dryRunOperation(); + } deleteVpcDefaultResources(region, vpcId); vpcs.delete(key(region, vpcId)); removeTags(region, vpcId); @@ -8301,6 +8312,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } public void deleteSubnet(String region, String subnetId) { + deleteSubnet(region, subnetId, false); + } + + /** + * As above; with {@code dryRun} the subnet must exist and nothing may still use it, and the request is + * then answered with DryRunOperation, the subnet kept. + */ + public void deleteSubnet(String region, String subnetId, boolean dryRun) { ensureDefaultResources(region); if (subnets.get(key(region, subnetId)).isEmpty()) { throw new AwsException("InvalidSubnetID.NotFound", "The subnet ID '" + subnetId + "' does not exist", 400); @@ -8313,6 +8332,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab "The subnet '" + subnetId + "' has dependencies and cannot be deleted."); requireNoProviderDependency(provider -> provider.hasSubnetDependency(region, subnetId), "The subnet '" + subnetId + "' has dependencies and cannot be deleted."); + if (dryRun) { + throw dryRunOperation(); + } subnets.delete(key(region, subnetId)); } if (vpcNetworkManager != null) { @@ -11851,26 +11873,57 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } public void deleteInternetGateway(String region, String igwId) { + deleteInternetGateway(region, igwId, false); + } + + /** + * As above; with {@code dryRun} the gateway must exist, and the request is then answered with + * DryRunOperation, the gateway kept. + */ + public void deleteInternetGateway(String region, String igwId, boolean dryRun) { ensureDefaultResources(region); - if (internetGateways.get(key(region, igwId)).isEmpty()) { - throw new AwsException("InvalidInternetGatewayID.NotFound", "The internet gateway '" + igwId + "' does not exist", 400); + getRequiredInternetGateway(region, igwId); + if (dryRun) { + throw dryRunOperation(); } internetGateways.delete(key(region, igwId)); } public void attachInternetGateway(String region, String igwId, String vpcId) { + attachInternetGateway(region, igwId, vpcId, false); + } + + /** + * As above; with {@code dryRun} the VPC and the gateway must exist, and the request is then answered + * with DryRunOperation, nothing attached. + */ + public void attachInternetGateway(String region, String igwId, String vpcId, boolean dryRun) { ensureDefaultResources(region); synchronized (attachmentTopologyLock(region)) { getRequiredVpc(region, vpcId); InternetGateway igw = getRequiredInternetGateway(region, igwId); + if (dryRun) { + throw dryRunOperation(); + } igw.getAttachments().add(new InternetGatewayAttachment(vpcId, "available")); internetGateways.put(key(region, igwId), igw); } } public void detachInternetGateway(String region, String igwId, String vpcId) { + detachInternetGateway(region, igwId, vpcId, false); + } + + /** + * As above; with {@code dryRun} the gateway must exist, and the request is then answered with + * DryRunOperation, nothing detached. + */ + public void detachInternetGateway(String region, String igwId, String vpcId, boolean dryRun) { ensureDefaultResources(region); InternetGateway igw = getRequiredInternetGateway(region, igwId); + if (dryRun) { + throw dryRunOperation(); + } igw.getAttachments().removeIf(a -> a.getVpcId().equals(vpcId)); internetGateways.put(key(region, igwId), igw); @@ -12635,8 +12688,19 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab // ─── Route Tables ────────────────────────────────────────────────────────── public RouteTable createRouteTable(String region, String vpcId) { + return createRouteTable(region, vpcId, false); + } + + /** + * As above; with {@code dryRun} the VPC must exist, and the request is then answered with + * DryRunOperation, no route table created. + */ + public RouteTable createRouteTable(String region, String vpcId, boolean dryRun) { ensureDefaultResources(region); Vpc vpc = getRequiredVpc(region, vpcId); + if (dryRun) { + throw dryRunOperation(); + } String rtId = "rtb-" + randomHex(8); RouteTable rt = new RouteTable(); @@ -12688,18 +12752,38 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } public void deleteRouteTable(String region, String routeTableId) { + deleteRouteTable(region, routeTableId, false); + } + + /** + * As above; with {@code dryRun} the route table must exist, and the request is then answered with + * DryRunOperation, the route table kept. + */ + public void deleteRouteTable(String region, String routeTableId, boolean dryRun) { ensureDefaultResources(region); - RouteTable rt = routeTables.get(key(region, routeTableId)).orElse(null); - if (rt == null) { - throw new AwsException("InvalidRouteTableID.NotFound", "The route table '" + routeTableId + "' does not exist", 400); + RouteTable rt = getRequiredRouteTable(region, routeTableId); + if (dryRun) { + throw dryRunOperation(); } routeTables.delete(key(region, routeTableId)); notifyRouteTableUpdated(region, rt); } public RouteTableAssociation associateRouteTable(String region, String routeTableId, String subnetId) { + return associateRouteTable(region, routeTableId, subnetId, false); + } + + /** + * As above; with {@code dryRun} the route table must exist, and the request is then answered with + * DryRunOperation, nothing associated. + */ + public RouteTableAssociation associateRouteTable(String region, String routeTableId, String subnetId, + boolean dryRun) { ensureDefaultResources(region); RouteTable rt = getRequiredRouteTable(region, routeTableId); + if (dryRun) { + throw dryRunOperation(); + } String assocId = "rtbassoc-" + randomHex(8); RouteTableAssociation assoc = new RouteTableAssociation(); @@ -13053,6 +13137,16 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab public void deleteRoute(String region, String routeTableId, String destinationCidrBlock, String destinationIpv6CidrBlock, String destinationPrefixListId) { + deleteRoute(region, routeTableId, destinationCidrBlock, destinationIpv6CidrBlock, destinationPrefixListId, + false); + } + + /** + * As above; with {@code dryRun} the route table must hold a route to the destination, and not the + * local route, and the request is then answered with DryRunOperation, the route kept. + */ + public void deleteRoute(String region, String routeTableId, String destinationCidrBlock, + String destinationIpv6CidrBlock, String destinationPrefixListId, boolean dryRun) { requireExactlyOneDestination("DeleteRoute", destinationCidrBlock, destinationIpv6CidrBlock, destinationPrefixListId); final String canonicalDestinationCidrBlock = canonicalizeIpv4Cidr(destinationCidrBlock); @@ -13078,6 +13172,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab + " in route table " + routeTableId, 400); } } + if (dryRun) { + throw dryRunOperation(); + } next.removeAll(matched); current.setRoutes(next); routeTables.put(key(region, routeTableId), current); diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2DryRunIamIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2DryRunIamIntegrationTest.java index ee2f426004..e897e783bd 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2DryRunIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2DryRunIamIntegrationTest.java @@ -20,6 +20,8 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Supplier; import static io.floci.aws.testing.AwsSdkErrors.assertAwsError; import static org.awaitility.Awaitility.await; @@ -105,41 +107,70 @@ class Ec2DryRunIamIntegrationTest { .instanceType(AttributeValue.builder().value("t3.small").build()).dryRun(true))); } + @Test + void aDeleteVpcDryRunNeedsTheCallersCurrentPermission() throws Exception { + try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1, endpoint)) { + String vpcId = admin.createVpc(r -> r.cidrBlock("10.95.0.0/16")).vpc().vpcId(); + try { + assertADryRunNeedsTheCallersCurrentPermission("DeleteVpc", + () -> admin.describeVpcs(r -> r.vpcIds(vpcId)).vpcs(), + caller -> caller.deleteVpc(r -> r.vpcId(vpcId).dryRun(true))); + } finally { + // There unless a dry run deleted it. + if (!admin.describeVpcs(r -> r.filters(f -> f.name("vpc-id").values(vpcId))).vpcs().isEmpty()) { + admin.deleteVpc(r -> r.vpcId(vpcId)); + } + } + } + } + /** * A caller the policy allows {@code action} gets DryRunOperation for {@code dryRun} on a running instance, * and UnauthorizedOperation once the policy is removed; the instance is unchanged either way. */ private void assertAnInstanceDryRunNeedsTheCallersCurrentPermission(String action, BiConsumer dryRun) throws Exception { - String policy = """ - {"Version":"2012-10-17","Statement":[{ - "Effect":"Allow","Action":"ec2:%s","Resource":"*" - }]} - """.formatted(action); - try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1, endpoint); - SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, - "dryrun-" + action.toLowerCase(Locale.ROOT) + "-", "instances", policy); - Ec2Client caller = AwsTestClients.create(Ec2Client.builder(), user.accessKeyId(), - user.secretAccessKey(), Region.US_EAST_1, endpoint)) { + try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1, endpoint)) { String instanceId = admin.runInstances(r -> r.imageId("ami-1234567890abcdef0") .instanceType(InstanceType.T3_MICRO).minCount(1).maxCount(1)).instances().get(0).instanceId(); try { await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100)) .untilAsserted(() -> assertEquals("running", instance(admin, instanceId).state().nameAsString())); - Instance before = instance(admin, instanceId); - assertAwsError("DryRunOperation", 412, () -> dryRun.accept(caller, instanceId)); - SignedIamUsers.iam(endpoint, "DeleteUserPolicy", Map.of("UserName", user.name(), "PolicyName", "instances")) - .then().statusCode(200); - assertAwsError("UnauthorizedOperation", 403, () -> dryRun.accept(caller, instanceId)); - - assertEquals(before, instance(admin, instanceId)); + assertADryRunNeedsTheCallersCurrentPermission(action, () -> instance(admin, instanceId), + caller -> dryRun.accept(caller, instanceId)); } finally { admin.terminateInstances(r -> r.instanceIds(instanceId)); } } } + /** + * A caller the policy allows {@code action} gets DryRunOperation for {@code dryRun}, and UnauthorizedOperation + * once the policy is removed; {@code state} reads the same before and after. + */ + private void assertADryRunNeedsTheCallersCurrentPermission(String action, Supplier state, + Consumer dryRun) throws Exception { + String policy = """ + {"Version":"2012-10-17","Statement":[{ + "Effect":"Allow","Action":"ec2:%s","Resource":"*" + }]} + """.formatted(action); + try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, + "dryrun-" + action.toLowerCase(Locale.ROOT) + "-", "dryrun", policy); + Ec2Client caller = AwsTestClients.create(Ec2Client.builder(), user.accessKeyId(), + user.secretAccessKey(), Region.US_EAST_1, endpoint)) { + Object before = state.get(); + + assertAwsError("DryRunOperation", 412, () -> dryRun.accept(caller)); + SignedIamUsers.iam(endpoint, "DeleteUserPolicy", Map.of("UserName", user.name(), "PolicyName", "dryrun")) + .then().statusCode(200); + assertAwsError("UnauthorizedOperation", 403, () -> dryRun.accept(caller)); + + assertEquals(before, state.get()); + } + } + private static Instance instance(Ec2Client client, String instanceId) { return client.describeInstances(r -> r.instanceIds(instanceId)).reservations().get(0).instances().get(0); } diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2VpcDryRunIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2VpcDryRunIntegrationTest.java new file mode 100644 index 0000000000..9ed48ebdd8 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2VpcDryRunIntegrationTest.java @@ -0,0 +1,196 @@ +package io.floci.aws.services.ec2; + +import io.floci.aws.testing.QueryRequests; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.Stream; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * DryRun on the VPC, subnet, internet gateway and route table calls is answered with DryRunOperation and + * HTTP 412 once the request has passed the checks the real call makes, and changes nothing. A dry run the + * real call would refuse keeps that call's error. + */ +@QuarkusTest +class Ec2VpcDryRunIntegrationTest { + + /** Each test works in an account of its own, so the describe calls list only the fixture's resources. */ + private static final AtomicLong ACCOUNTS = new AtomicLong(726300000000L); + private static final String MISSING_VPC = "vpc-0123456789abcdef0"; + private static final String MISSING_GATEWAY = "igw-0123456789abcdef0"; + private static final String MISSING_TABLE = "rtb-0123456789abcdef0"; + + private String account; + /** The fixture's ids by the names the requests below give them in braces, such as {vpc}. */ + private final Map ids = new HashMap<>(); + + /** + * A VPC with two subnets, one holding a network interface; an internet gateway attached to it; a route + * table routing 0.0.0.0/0 to the gateway and associated with the occupied subnet, and a second one with + * neither. Beside them, an empty VPC and a gateway attached to nothing. + */ + @BeforeEach + void buildTheNetwork() { + account = Long.toString(ACCOUNTS.incrementAndGet()); + ids.clear(); + ids.put("vpc", create("CreateVpc", "vpc.vpcId", "CidrBlock", "10.0.0.0/16")); + ids.put("emptyVpc", create("CreateVpc", "vpc.vpcId", "CidrBlock", "10.1.0.0/16")); + ids.put("subnet", create("CreateSubnet", "subnet.subnetId", "VpcId", ids.get("vpc"), + "CidrBlock", "10.0.1.0/24")); + ids.put("freeSubnet", create("CreateSubnet", "subnet.subnetId", "VpcId", ids.get("vpc"), + "CidrBlock", "10.0.2.0/24")); + create("CreateNetworkInterface", "networkInterface.networkInterfaceId", "SubnetId", ids.get("subnet")); + ids.put("gateway", create("CreateInternetGateway", "internetGateway.internetGatewayId")); + ids.put("spareGateway", create("CreateInternetGateway", "internetGateway.internetGatewayId")); + ec2("AttachInternetGateway", "InternetGatewayId", ids.get("gateway"), "VpcId", ids.get("vpc")); + ids.put("table", create("CreateRouteTable", "routeTable.routeTableId", "VpcId", ids.get("vpc"))); + ids.put("spareTable", create("CreateRouteTable", "routeTable.routeTableId", "VpcId", ids.get("vpc"))); + ec2("CreateRoute", "RouteTableId", ids.get("table"), "DestinationCidrBlock", "0.0.0.0/0", + "GatewayId", ids.get("gateway")); + ids.put("association", create("AssociateRouteTable", "associationId", "RouteTableId", ids.get("table"), + "SubnetId", ids.get("subnet"))); + } + + /** A request each call's real call accepts in the fixture. */ + static Stream acceptedRequests() { + return Stream.of( + new String[] {"DeleteVpc", "VpcId={emptyVpc}"}, + new String[] {"CreateDefaultVpc", ""}, + new String[] {"DeleteSubnet", "SubnetId={freeSubnet}"}, + new String[] {"CreateInternetGateway", ""}, + new String[] {"AttachInternetGateway", "InternetGatewayId={spareGateway} VpcId={emptyVpc}"}, + new String[] {"DetachInternetGateway", "InternetGatewayId={gateway} VpcId={vpc}"}, + new String[] {"DeleteInternetGateway", "InternetGatewayId={spareGateway}"}, + new String[] {"CreateRouteTable", "VpcId={vpc}"}, + new String[] {"DeleteRouteTable", "RouteTableId={spareTable}"}, + new String[] {"AssociateRouteTable", "RouteTableId={spareTable} SubnetId={freeSubnet}"}, + new String[] {"DisassociateRouteTable", "AssociationId={association}"}, + new String[] {"DeleteRoute", "RouteTableId={table} DestinationCidrBlock=0.0.0.0/0"}); + } + + @ParameterizedTest + @MethodSource("acceptedRequests") + void aDryRunIsAnsweredWithDryRunOperationAndChangesNothing(String action, String params) { + String before = snapshot(); + + request(action, params(params)).formParam("DryRun", "true").post("/").then() + .statusCode(412) + .body("Response.Errors.Error.Code", equalTo("DryRunOperation")) + .body("Response.Errors.Error.Message", + equalTo("Request would have succeeded, but DryRun flag is set.")); + + assertEquals(before, snapshot()); + } + + @ParameterizedTest + @MethodSource("acceptedRequests") + void aDryRunValueThatIsNotABooleanIsRefused(String action, String params) { + String before = snapshot(); + + request(action, params(params)).formParam("DryRun", "maybe").post("/").then() + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue")) + .body("Response.Errors.Error.Message", equalTo("DryRun is not a valid boolean.")); + + assertEquals(before, snapshot()); + } + + /** The real call refuses each of these; its dry run keeps the same error, and neither changes anything. */ + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "DeleteVpc | VpcId={vpc} | DependencyViolation", + "DeleteVpc | VpcId=" + MISSING_VPC + " | InvalidVpcID.NotFound", + "DeleteSubnet | SubnetId={subnet} | DependencyViolation", + "DeleteSubnet | SubnetId=subnet-0123456789abcdef0 | InvalidSubnetID.NotFound", + "CreateInternetGateway | TagSpecification.1.ResourceType=internet-gateway" + + " TagSpecification.1.Tag.1.Key=aws:dry-run | InvalidParameterValue", + "AttachInternetGateway | InternetGatewayId={spareGateway} VpcId=" + MISSING_VPC + " | InvalidVpcID.NotFound", + "DetachInternetGateway | InternetGatewayId=" + MISSING_GATEWAY + " VpcId={vpc}" + + " | InvalidInternetGatewayID.NotFound", + "DeleteInternetGateway | InternetGatewayId=" + MISSING_GATEWAY + " | InvalidInternetGatewayID.NotFound", + "CreateRouteTable | VpcId=" + MISSING_VPC + " | InvalidVpcID.NotFound", + "DeleteRouteTable | RouteTableId=" + MISSING_TABLE + " | InvalidRouteTableID.NotFound", + "AssociateRouteTable | RouteTableId=" + MISSING_TABLE + " SubnetId={freeSubnet}" + + " | InvalidRouteTableID.NotFound", + "DeleteRoute | RouteTableId={table} DestinationCidrBlock=10.0.0.0/16 | InvalidParameterValue", + "DeleteRoute | RouteTableId={table} DestinationCidrBlock=10.9.0.0/16 | InvalidRoute.NotFound", + "DeleteRoute | RouteTableId={table} | MissingParameter" + }) + void aDryRunTheRealCallWouldRefuseKeepsItsError(String action, String params, String code) { + String before = snapshot(); + + for (String dryRun : List.of("true", "false")) { + request(action, params(params)).formParam("DryRun", dryRun).post("/").then() + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo(code)); + } + + assertEquals(before, snapshot()); + } + + /** + * Everything these calls can change in the test's account, as the describe calls report it: the VPCs + * and what DeleteVpc removes with one (its default security group and network ACL), the subnets, the + * network interface, the internet gateways and the route tables with their routes and associations. + */ + private String snapshot() { + return String.join("\n", + body("DescribeVpcs"), + body("DescribeSubnets"), + body("DescribeNetworkInterfaces"), + body("DescribeSecurityGroups"), + body("DescribeNetworkAcls"), + body("DescribeInternetGateways"), + body("DescribeRouteTables")); + } + + /** A describe call's answer without the request id, the one part that differs on every call. */ + private String body(String action) { + return request(action).post("/").then().statusCode(200).extract().asString() + .replaceAll("[^<]*", ""); + } + + /** {@code Key=Value} pairs separated by spaces, with a fixture's name in braces standing for its id. */ + private String[] params(String spec) { + if (spec == null || spec.isBlank()) { + return new String[0]; + } + return Stream.of(spec.trim().split(" +")) + .flatMap(pair -> Stream.of(pair.split("=", 2))) + .map(this::withIds) + .toArray(String[]::new); + } + + private String withIds(String part) { + String result = part; + for (Map.Entry id : ids.entrySet()) { + result = result.replace("{" + id.getKey() + "}", id.getValue()); + } + return result; + } + + /** Runs {@code action} and returns what its answer holds at {@code path}. */ + private String create(String action, String path, String... params) { + return ec2(action, params).getString(action + "Response." + path); + } + + private XmlPath ec2(String action, String... params) { + return request(action, params).post("/").then().statusCode(200).extract().xmlPath(); + } + + private RequestSpecification request(String action, String... params) { + return QueryRequests.request(account, "ec2", action, params); + } +} diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2SubnetDependencyIntegrationTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2SubnetDependencyIntegrationTest.java index 47230df278..3b5b9710fc 100644 --- a/src/test/java/io/floci/aws/services/elbv2/ElbV2SubnetDependencyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2SubnetDependencyIntegrationTest.java @@ -161,7 +161,7 @@ class ElbV2SubnetDependencyIntegrationTest { doAnswer(invocation -> { deleting.countDown(); return invocation.callRealMethod(); - }).when(ec2Service).deleteSubnet(REGION, replacement); + }).when(ec2Service).deleteSubnet(REGION, replacement, false); String arn = existing; try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future attach = executor.submit(() -> {