mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
fix(ec2): honor DryRun when creating VPCs, subnets and security groups (#6823)
* fix(ec2): honor DryRun when creating VPCs, subnets and security groups CreateVpc, CreateSubnet and CreateSecurityGroup never read DryRun, so a dry run created the resource it asked about. A real CreateVpc that followed left a second VPC, and the real create of a subnet or group failed: InvalidSubnet.Conflict for the subnet's CIDR block, InvalidGroup.Duplicate for the group name. Each handler now answers DryRunOperation (HTTP 412) and creates nothing. It answers after parsing the tag specifications and, for CreateSecurityGroup, reading the required GroupName and GroupDescription. Ec2Service makes every other check, so a dry run is answered before the VPC id, the VPC, the CIDR block, the tenancy, overlap with other subnets or a taken group name are checked. AWS documents no order for those checks. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): look up the VPC before answering a subnet or group dry run A DryRun CreateSubnet or CreateSecurityGroup naming a VPC that does not exist answered DryRunOperation, "would have succeeded", while the real create fails with InvalidVpcID.NotFound. CreateSubnet without a VpcId answered DryRunOperation too, where the real create gives MissingParameter. The handlers now require the VpcId and look up the VPC, the default one for a security group without a VpcId, before they answer the dry run. A RunInstances dry run already keeps the error of a missing subnet or group, and the Service Authorization Reference lists the VPC, with its tags and tenancy, in both actions' permissions. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): share the security group VPC lookup with its dry run The CreateSecurityGroup handler and Ec2Service each picked the group's VPC, the named one or the region's default, so the two copies could drift. Ec2Service.requireSecurityGroupVpc now does it for both, and the CreateSubnet handler looks up the VpcId it has just required. New tests cover a group dry run with an absent or empty VpcId, which is answered for the default VPC, and a group dry run in a missing VPC through the SDK. The comments and docs now name every check a dry run skips, the zone and the IPv6 block included, and link the Service Authorization Reference. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(ec2): list the errors a create dry run still returns The CreateVpc, CreateSubnet and CreateSecurityGroup rows said which checks a dry run skips but not which errors it keeps. They now say that a tag specification error, and a missing VpcId, GroupName, GroupDescription or VPC, comes back on a dry run too, and that an empty VpcId also puts a security group in the default VPC. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): keep tag errors ahead of the create dry-run answer CreateVpc, CreateSubnet and CreateSecurityGroup read their tag specifications before they answer DryRun, so a reserved aws: key is still rejected on a dry run, as the EC2 docs page says. A handler test now pins that for all three actions; it fails if the dry-run answer is moved ahead of the tag parsing. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): use the shared EC2 request helper in the dry-run test Ec2CreateDryRunIntegrationTest now calls Ec2Requests.ec2 with "test" and "us-east-1" instead of its own copy of that helper. The comments in the CreateSubnet and CreateSecurityGroup handlers shrink to one line each; docs/services/ec2.md already explains the order. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> --------- Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
1 parent
3c391a06fb
commit
d7763fff8e
6 files changed
+446
-9
No files matched your search
+124
@@ -0,0 +1,124 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
|
||||
import software.amazon.awssdk.services.ec2.model.Filter;
|
||||
import software.amazon.awssdk.services.ec2.model.ResourceType;
|
||||
import software.amazon.awssdk.services.ec2.model.SecurityGroup;
|
||||
import software.amazon.awssdk.services.ec2.model.Tag;
|
||||
import software.amazon.awssdk.services.ec2.model.TagSpecification;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* A create with DryRun answers DryRunOperation (HTTP 412) and creates nothing, so the same create
|
||||
* without DryRun then succeeds. A subnet or group dry run naming a missing VPC keeps the real create's
|
||||
* error.
|
||||
*/
|
||||
class Ec2CreateDryRunTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("CreateVpc with DryRun creates no VPC")
|
||||
void createVpcWithDryRun() {
|
||||
String marker = TestFixtures.uniqueName("compat-dry-run");
|
||||
TagSpecification nameTag = TagSpecification.builder().resourceType(ResourceType.VPC)
|
||||
.tags(Tag.builder().key("Name").value(marker).build()).build();
|
||||
try (Ec2Client ec2 = TestFixtures.ec2Client()) {
|
||||
try {
|
||||
expectDryRunOperation(() -> ec2.createVpc(r -> r.cidrBlock("10.212.0.0/16")
|
||||
.tagSpecifications(nameTag).dryRun(true)));
|
||||
assertThat(ec2.describeVpcs(r -> r.filters(byName(marker))).vpcs()).isEmpty();
|
||||
|
||||
ec2.createVpc(r -> r.cidrBlock("10.212.0.0/16").tagSpecifications(nameTag));
|
||||
assertThat(ec2.describeVpcs(r -> r.filters(byName(marker))).vpcs()).hasSize(1);
|
||||
} finally {
|
||||
ec2.describeVpcs(r -> r.filters(byName(marker))).vpcs()
|
||||
.forEach(vpc -> ec2.deleteVpc(r -> r.vpcId(vpc.vpcId())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("CreateSubnet with DryRun creates no subnet and leaves its CIDR block free")
|
||||
void createSubnetWithDryRun() {
|
||||
try (Ec2Client ec2 = TestFixtures.ec2Client()) {
|
||||
String vpcId = ec2.createVpc(r -> r.cidrBlock("10.213.0.0/16")).vpc().vpcId();
|
||||
try {
|
||||
expectDryRunOperation(() -> ec2.createSubnet(r -> r.vpcId(vpcId)
|
||||
.cidrBlock("10.213.8.0/24").dryRun(true)));
|
||||
assertThat(ec2.describeSubnets(r -> r.filters(byVpc(vpcId))).subnets()).isEmpty();
|
||||
|
||||
assertThat(ec2.createSubnet(r -> r.vpcId(vpcId).cidrBlock("10.213.8.0/24")).subnet().cidrBlock())
|
||||
.isEqualTo("10.213.8.0/24");
|
||||
} finally {
|
||||
ec2.describeSubnets(r -> r.filters(byVpc(vpcId))).subnets()
|
||||
.forEach(subnet -> ec2.deleteSubnet(r -> r.subnetId(subnet.subnetId())));
|
||||
ec2.deleteVpc(r -> r.vpcId(vpcId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("CreateSecurityGroup with DryRun creates no group and leaves its name free")
|
||||
void createSecurityGroupWithDryRun() {
|
||||
try (Ec2Client ec2 = TestFixtures.ec2Client()) {
|
||||
String vpcId = ec2.createVpc(r -> r.cidrBlock("10.214.0.0/16")).vpc().vpcId();
|
||||
try {
|
||||
expectDryRunOperation(() -> ec2.createSecurityGroup(r -> r.vpcId(vpcId)
|
||||
.groupName("compat-dry-run-sg").description("compatibility dry run").dryRun(true)));
|
||||
assertThat(ec2.describeSecurityGroups(r -> r.filters(byVpc(vpcId))).securityGroups())
|
||||
.extracting(SecurityGroup::groupName).containsExactly("default");
|
||||
|
||||
assertThat(ec2.createSecurityGroup(r -> r.vpcId(vpcId)
|
||||
.groupName("compat-dry-run-sg").description("compatibility dry run")).groupId())
|
||||
.isNotBlank();
|
||||
} finally {
|
||||
ec2.describeSecurityGroups(r -> r.filters(byVpc(vpcId))).securityGroups().stream()
|
||||
.filter(group -> !"default".equals(group.groupName()))
|
||||
.forEach(group -> ec2.deleteSecurityGroup(r -> r.groupId(group.groupId())));
|
||||
ec2.deleteVpc(r -> r.vpcId(vpcId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("CreateSubnet with DryRun in a missing VPC keeps InvalidVpcID.NotFound")
|
||||
void createSubnetWithDryRunInAMissingVpc() {
|
||||
try (Ec2Client ec2 = TestFixtures.ec2Client()) {
|
||||
Ec2Exception error = assertThrows(Ec2Exception.class, () -> ec2.createSubnet(r -> r
|
||||
.vpcId("vpc-0123456789abcdef0").cidrBlock("10.215.8.0/24").dryRun(true)));
|
||||
assertThat(error.statusCode()).isEqualTo(400);
|
||||
assertThat(error.awsErrorDetails().errorCode()).isEqualTo("InvalidVpcID.NotFound");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("CreateSecurityGroup with DryRun in a missing VPC keeps InvalidVpcID.NotFound")
|
||||
void createSecurityGroupWithDryRunInAMissingVpc() {
|
||||
try (Ec2Client ec2 = TestFixtures.ec2Client()) {
|
||||
Ec2Exception error = assertThrows(Ec2Exception.class, () -> ec2.createSecurityGroup(r -> r
|
||||
.vpcId("vpc-0123456789abcdef0").groupName("compat-dry-run-missing-vpc")
|
||||
.description("compatibility dry run").dryRun(true)));
|
||||
assertThat(error.statusCode()).isEqualTo(400);
|
||||
assertThat(error.awsErrorDetails().errorCode()).isEqualTo("InvalidVpcID.NotFound");
|
||||
}
|
||||
}
|
||||
|
||||
private static Filter byName(String name) {
|
||||
return Filter.builder().name("tag:Name").values(name).build();
|
||||
}
|
||||
|
||||
private static Filter byVpc(String vpcId) {
|
||||
return Filter.builder().name("vpc-id").values(vpcId).build();
|
||||
}
|
||||
|
||||
private static void expectDryRunOperation(Executable call) {
|
||||
Ec2Exception error = assertThrows(Ec2Exception.class, call);
|
||||
assertThat(error.statusCode()).isEqualTo(412);
|
||||
assertThat(error.awsErrorDetails().errorCode()).isEqualTo("DryRunOperation");
|
||||
}
|
||||
}
|
||||
@@ -294,7 +294,7 @@ naming different VPCs find nothing.
|
||||
|
||||
| Action | Description |
|
||||
|--------|-------------|
|
||||
| CreateVpc | Creates a VPC with the requested CIDR block. `InstanceTenancy` accepts `default` or `dedicated`; `host` is rejected with `InvalidParameterValue`, as on AWS. |
|
||||
| CreateVpc | Creates a VPC with the requested CIDR block. `InstanceTenancy` accepts `default` or `dedicated`; `host` is rejected with `InvalidParameterValue`, as on AWS. `DryRun=true` is answered with `DryRunOperation` and creates nothing. A tag specification error keeps its own error; the CIDR block and the tenancy are checked only without `DryRun`. |
|
||||
| DescribeVpcs | Lists or returns stored VPCs. |
|
||||
| DeleteVpc | Deletes a VPC from the local EC2 store, together with its default security group and rules, main route table and default network ACL. Fails with `DependencyViolation` while the VPC still has a subnet, a security group, route table or network ACL other than those defaults, a VPC endpoint, an attached internet gateway or egress-only internet gateway, a transit gateway attachment, an Elastic Load Balancing v2 load balancer, or anything still holding a network interface in one of its subnets: an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone network interface, or an interface endpoint. |
|
||||
| ModifyVpcAttribute | Updates supported VPC attributes. |
|
||||
@@ -320,7 +320,7 @@ private gateway lifecycles are not modelled.
|
||||
|
||||
| Action | Description |
|
||||
|--------|-------------|
|
||||
| CreateSubnet | Creates a subnet in a VPC. |
|
||||
| CreateSubnet | Creates a subnet in a VPC. `DryRun=true` is answered with `DryRunOperation` and creates nothing. A tag specification error or a missing `VpcId` or VPC keeps its own error; the CIDR block, zone, IPv6 block and overlap with other subnets are checked only without `DryRun`. |
|
||||
| DescribeSubnets | Lists or returns stored subnets. The `default-for-az` filter and its `defaultForAz` alias select default or non-default subnets; values are ORed and separate filters are ANDed. |
|
||||
| DeleteSubnet | Deletes a subnet from the local EC2 store. Fails with `DependencyViolation` while the subnet still has a transit gateway attachment, an Elastic Load Balancing v2 load balancer, or anything holding a network interface in it: an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone network interface, or an interface endpoint. |
|
||||
| ModifySubnetAttribute | Updates supported subnet attributes. |
|
||||
@@ -329,7 +329,7 @@ private gateway lifecycles are not modelled.
|
||||
|
||||
| Action | Description |
|
||||
|--------|-------------|
|
||||
| CreateSecurityGroup | Creates a security group in a VPC. |
|
||||
| CreateSecurityGroup | Creates a security group in a VPC, the default VPC when `VpcId` is absent or empty. `DryRun=true` is answered with `DryRunOperation` and creates nothing. A tag specification error or a missing `GroupName`, `GroupDescription` or VPC keeps its own error; a taken group name is checked only without `DryRun`. |
|
||||
| DescribeSecurityGroups | Lists or returns stored security groups. |
|
||||
| DeleteSecurityGroup | Deletes a security group from the local EC2 store. |
|
||||
| AuthorizeSecurityGroupIngress | Adds inbound permissions. Sources may be IPv4 ranges, IPv6 ranges, or another security group (`UserIdGroupPairs`, sent on the wire as `Groups`); prefix list sources are not stored. One rule is stored per source, each carrying its own description. |
|
||||
|
||||
@@ -1699,6 +1699,8 @@ public class Ec2QueryHandler {
|
||||
String cidrBlock = p.getFirst("CidrBlock");
|
||||
boolean amazonProvidedIpv6 = "true".equalsIgnoreCase(p.getFirst("AmazonProvidedIpv6CidrBlock"));
|
||||
List<Tag> vpcTags = parseTagsForResource(p, "vpc");
|
||||
// Answered before Ec2Service checks the CIDR block and the tenancy, an order AWS does not document.
|
||||
checkDryRun(p);
|
||||
Vpc vpc = service.createVpc(region, cidrBlock, false, amazonProvidedIpv6, p.getFirst("InstanceTenancy"));
|
||||
applyResourceTags(vpcTags, region, vpc.getVpcId());
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
@@ -3324,6 +3326,10 @@ public class Ec2QueryHandler {
|
||||
String azId = p.getFirst("AvailabilityZoneId");
|
||||
String ipv6CidrBlock = p.getFirst("Ipv6CidrBlock");
|
||||
List<Tag> tags = parseTagsForResource(p, "subnet", Set.of("subnet"));
|
||||
// A dry run needs the VPC to exist and is answered before the CIDR, zone and overlap checks.
|
||||
requireParameter(p, "VpcId");
|
||||
service.requireVpc(region, vpcId);
|
||||
checkDryRun(p);
|
||||
Subnet subnet = service.createSubnet(region, vpcId, cidrBlock, az, azId, ipv6CidrBlock);
|
||||
try {
|
||||
if (!tags.isEmpty()) {
|
||||
@@ -3402,6 +3408,9 @@ public class Ec2QueryHandler {
|
||||
String groupName = requireParameter(p, "GroupName");
|
||||
String description = requireParameter(p, "GroupDescription");
|
||||
String vpcId = p.getFirst("VpcId");
|
||||
// A dry run needs the (default) VPC to exist and is answered before the taken-name check.
|
||||
service.requireSecurityGroupVpc(region, vpcId);
|
||||
checkDryRun(p);
|
||||
SecurityGroup sg = service.createSecurityGroup(region, groupName, description, vpcId);
|
||||
applyResourceTags(resourceTags, region, sg.getGroupId());
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
|
||||
@@ -7620,13 +7620,17 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
|
||||
// ─── Security Groups ───────────────────────────────────────────────────────
|
||||
|
||||
public SecurityGroup createSecurityGroup(String region, String groupName, String description, String vpcId) {
|
||||
/**
|
||||
* The VPC a new security group goes into: the one {@code vpcId} names, or the region's default VPC
|
||||
* when {@code vpcId} is absent or empty. Fails with InvalidVpcID.NotFound when that VPC does not exist.
|
||||
*/
|
||||
public Vpc requireSecurityGroupVpc(String region, String vpcId) {
|
||||
ensureDefaultResources(region);
|
||||
if (vpcId != null && !vpcId.isEmpty()) {
|
||||
getRequiredVpc(region, vpcId);
|
||||
} else {
|
||||
vpcId = resolveDefaultVpcId(region);
|
||||
}
|
||||
return getRequiredVpc(region, vpcId != null && !vpcId.isEmpty() ? vpcId : resolveDefaultVpcId(region));
|
||||
}
|
||||
|
||||
public SecurityGroup createSecurityGroup(String region, String groupName, String description, String vpcId) {
|
||||
vpcId = requireSecurityGroupVpc(region, vpcId).getVpcId();
|
||||
// Check duplicate
|
||||
String finalVpcId = vpcId;
|
||||
boolean exists = securityGroups.scan(k -> true).stream()
|
||||
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.Ec2Requests.ec2;
|
||||
import static org.hamcrest.Matchers.emptyOrNullString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
/**
|
||||
* DryRun on CreateVpc, CreateSubnet and CreateSecurityGroup is answered with DryRunOperation and HTTP 412,
|
||||
* and nothing is created, so the real create that follows can still take the same CIDR block or group
|
||||
* name. A subnet or group dry run first needs the VPC it names to exist; Floci then answers it before the
|
||||
* CIDR block, tenancy, overlap and group name are checked, an order AWS does not document.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class Ec2CreateDryRunIntegrationTest {
|
||||
|
||||
private static final String MISSING_VPC = "vpc-0123456789abcdef0";
|
||||
|
||||
@Test
|
||||
void aCreateVpcDryRunCreatesNoVpc() {
|
||||
String name = "dryrun-" + UUID.randomUUID();
|
||||
try {
|
||||
assertDryRun(tagged(createVpc("10.91.0.0/16"), "vpc", name).formParam("DryRun", "true"));
|
||||
|
||||
ec2("DescribeVpcs", "test", "us-east-1")
|
||||
.formParam("Filter.1.Name", "tag:Name")
|
||||
.formParam("Filter.1.Value.1", name)
|
||||
.post("/").then().statusCode(200)
|
||||
.body("DescribeVpcsResponse.vpcSet", emptyOrNullString());
|
||||
|
||||
tagged(createVpc("10.91.0.0/16"), "vpc", name).formParam("DryRun", "false")
|
||||
.post("/").then().statusCode(200)
|
||||
.body("CreateVpcResponse.vpc.cidrBlock", equalTo("10.91.0.0/16"));
|
||||
} finally {
|
||||
deleteVpcsNamed(name);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCreateSubnetDryRunCreatesNoSubnetAndLeavesItsRangeFree() {
|
||||
String vpcId = createVpcId("10.92.0.0/16");
|
||||
try {
|
||||
assertDryRun(createSubnet(vpcId, "10.92.1.0/24").formParam("DryRun", "true"));
|
||||
|
||||
ec2("DescribeSubnets", "test", "us-east-1")
|
||||
.formParam("Filter.1.Name", "vpc-id")
|
||||
.formParam("Filter.1.Value.1", vpcId)
|
||||
.post("/").then().statusCode(200)
|
||||
.body("DescribeSubnetsResponse.subnetSet", emptyOrNullString());
|
||||
|
||||
createSubnet(vpcId, "10.92.1.0/24")
|
||||
.post("/").then().statusCode(200)
|
||||
.body("CreateSubnetResponse.subnet.cidrBlock", equalTo("10.92.1.0/24"));
|
||||
} finally {
|
||||
deleteVpcAndItsContents(vpcId);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCreateSecurityGroupDryRunCreatesNoGroupAndLeavesItsNameFree() {
|
||||
String vpcId = createVpcId("10.93.0.0/16");
|
||||
try {
|
||||
assertDryRun(createSecurityGroup(vpcId, "dryrun-group").formParam("DryRun", "true"));
|
||||
|
||||
ec2("DescribeSecurityGroups", "test", "us-east-1")
|
||||
.formParam("Filter.1.Name", "vpc-id")
|
||||
.formParam("Filter.1.Value.1", vpcId)
|
||||
.post("/").then().statusCode(200)
|
||||
.body("DescribeSecurityGroupsResponse.securityGroupInfo.item.groupName", equalTo("default"));
|
||||
|
||||
createSecurityGroup(vpcId, "dryrun-group")
|
||||
.post("/").then().statusCode(200)
|
||||
.body("CreateSecurityGroupResponse.return", equalTo("true"));
|
||||
} finally {
|
||||
deleteVpcAndItsContents(vpcId);
|
||||
}
|
||||
}
|
||||
|
||||
/** A group dry run with no VpcId, or an empty one, is answered for the region's default VPC. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"absent", "empty"})
|
||||
void aGroupDryRunWithoutAVpcIdIsAnsweredForTheDefaultVpc(String vpcId) {
|
||||
String name = "dryrun-default-" + UUID.randomUUID();
|
||||
try {
|
||||
RequestSpecification dryRun = ec2("CreateSecurityGroup", "test", "us-east-1")
|
||||
.formParam("GroupName", name)
|
||||
.formParam("GroupDescription", "dry run test group")
|
||||
.formParam("DryRun", "true");
|
||||
if ("empty".equals(vpcId)) {
|
||||
dryRun.formParam("VpcId", "");
|
||||
}
|
||||
assertDryRun(dryRun);
|
||||
|
||||
groupsNamed(name).body("DescribeSecurityGroupsResponse.securityGroupInfo", emptyOrNullString());
|
||||
} finally {
|
||||
for (String groupId : groupsNamed(name).extract().xmlPath()
|
||||
.getList("DescribeSecurityGroupsResponse.securityGroupInfo.item.groupId", String.class)) {
|
||||
ec2("DeleteSecurityGroup", "test", "us-east-1").formParam("GroupId", groupId).post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A dry run whose real create would fail one of those checks is answered with DryRunOperation too,
|
||||
* and the same request without DryRun still fails with its own error.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"vpc-prefix-out-of-range, InvalidVpc.Range",
|
||||
"vpc-reserved-range, InvalidVpc.Range",
|
||||
"vpc-host-tenancy, InvalidParameterValue",
|
||||
"subnet-range-in-use, InvalidSubnet.Conflict",
|
||||
"subnet-outside-the-vpc, InvalidSubnet.Range",
|
||||
"group-name-taken, InvalidGroup.Duplicate"
|
||||
})
|
||||
void aDryRunIsAnsweredBeforeTheChecksThatFailTheRealCreate(String request, String errorCode) {
|
||||
String name = "dryrun-" + UUID.randomUUID();
|
||||
String vpcId = createVpcId("10.94.0.0/16");
|
||||
try {
|
||||
createSubnet(vpcId, "10.94.1.0/24").post("/").then().statusCode(200);
|
||||
createSecurityGroup(vpcId, "taken-group").post("/").then().statusCode(200);
|
||||
|
||||
assertDryRun(failingCreate(request, vpcId, name).formParam("DryRun", "true"));
|
||||
|
||||
failingCreate(request, vpcId, name)
|
||||
.post("/").then().statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo(errorCode));
|
||||
} finally {
|
||||
try {
|
||||
deleteVpcAndItsContents(vpcId);
|
||||
} finally {
|
||||
deleteVpcsNamed(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A subnet or group dry run naming a VPC that does not exist, or a subnet dry run naming none, keeps the
|
||||
* error the real create gives, as a RunInstances dry run keeps the error of a missing subnet.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"subnet-in-missing-vpc, InvalidVpcID.NotFound",
|
||||
"subnet-without-vpc-id, MissingParameter",
|
||||
"group-in-missing-vpc, InvalidVpcID.NotFound"
|
||||
})
|
||||
void aDryRunKeepsTheErrorOfAMissingVpc(String request, String errorCode) {
|
||||
missingVpcCreate(request).formParam("DryRun", "true")
|
||||
.post("/").then().statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo(errorCode));
|
||||
|
||||
missingVpcCreate(request)
|
||||
.post("/").then().statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo(errorCode));
|
||||
}
|
||||
|
||||
private static RequestSpecification missingVpcCreate(String request) {
|
||||
return switch (request) {
|
||||
case "subnet-in-missing-vpc" -> createSubnet(MISSING_VPC, "10.97.1.0/24");
|
||||
case "subnet-without-vpc-id" -> ec2("CreateSubnet", "test", "us-east-1").formParam("CidrBlock", "10.97.1.0/24");
|
||||
case "group-in-missing-vpc" -> createSecurityGroup(MISSING_VPC, "missing-vpc-group");
|
||||
default -> throw new IllegalArgumentException(request);
|
||||
};
|
||||
}
|
||||
|
||||
/** The failing request named by {@code request}; a VPC it might create carries the tag {@code name}. */
|
||||
private static RequestSpecification failingCreate(String request, String vpcId, String name) {
|
||||
return switch (request) {
|
||||
case "vpc-prefix-out-of-range" -> tagged(createVpc("10.0.0.0/8"), "vpc", name);
|
||||
case "vpc-reserved-range" -> tagged(createVpc("127.0.0.0/16"), "vpc", name);
|
||||
case "vpc-host-tenancy" -> tagged(createVpc("10.95.0.0/16"), "vpc", name)
|
||||
.formParam("InstanceTenancy", "host");
|
||||
case "subnet-range-in-use" -> createSubnet(vpcId, "10.94.1.0/24");
|
||||
case "subnet-outside-the-vpc" -> createSubnet(vpcId, "10.96.1.0/24");
|
||||
case "group-name-taken" -> createSecurityGroup(vpcId, "taken-group");
|
||||
default -> throw new IllegalArgumentException(request);
|
||||
};
|
||||
}
|
||||
|
||||
private static void assertDryRun(RequestSpecification request) {
|
||||
request.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."));
|
||||
}
|
||||
|
||||
private static ValidatableResponse groupsNamed(String name) {
|
||||
return ec2("DescribeSecurityGroups", "test", "us-east-1")
|
||||
.formParam("Filter.1.Name", "group-name")
|
||||
.formParam("Filter.1.Value.1", name)
|
||||
.post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static RequestSpecification tagged(RequestSpecification request, String resourceType, String name) {
|
||||
return request
|
||||
.formParam("TagSpecification.1.ResourceType", resourceType)
|
||||
.formParam("TagSpecification.1.Tag.1.Key", "Name")
|
||||
.formParam("TagSpecification.1.Tag.1.Value", name);
|
||||
}
|
||||
|
||||
private static RequestSpecification createVpc(String cidrBlock) {
|
||||
return ec2("CreateVpc", "test", "us-east-1").formParam("CidrBlock", cidrBlock);
|
||||
}
|
||||
|
||||
private static RequestSpecification createSubnet(String vpcId, String cidrBlock) {
|
||||
return ec2("CreateSubnet", "test", "us-east-1").formParam("VpcId", vpcId).formParam("CidrBlock", cidrBlock);
|
||||
}
|
||||
|
||||
private static RequestSpecification createSecurityGroup(String vpcId, String groupName) {
|
||||
return ec2("CreateSecurityGroup", "test", "us-east-1")
|
||||
.formParam("VpcId", vpcId)
|
||||
.formParam("GroupName", groupName)
|
||||
.formParam("GroupDescription", "dry run test group");
|
||||
}
|
||||
|
||||
private static String createVpcId(String cidrBlock) {
|
||||
return createVpc(cidrBlock).post("/").then().statusCode(200)
|
||||
.extract().path("CreateVpcResponse.vpc.vpcId");
|
||||
}
|
||||
|
||||
private static void deleteVpcsNamed(String name) {
|
||||
XmlPath vpcs = ec2("DescribeVpcs", "test", "us-east-1")
|
||||
.formParam("Filter.1.Name", "tag:Name")
|
||||
.formParam("Filter.1.Value.1", name)
|
||||
.post("/").then().statusCode(200).extract().xmlPath();
|
||||
for (String vpcId : vpcs.getList("DescribeVpcsResponse.vpcSet.item.vpcId", String.class)) {
|
||||
deleteVpcAndItsContents(vpcId);
|
||||
}
|
||||
}
|
||||
|
||||
/** Deletes the VPC with every subnet and non-default group in it, including any a dry run left. */
|
||||
private static void deleteVpcAndItsContents(String vpcId) {
|
||||
XmlPath subnets = ec2("DescribeSubnets", "test", "us-east-1")
|
||||
.formParam("Filter.1.Name", "vpc-id")
|
||||
.formParam("Filter.1.Value.1", vpcId)
|
||||
.post("/").then().statusCode(200).extract().xmlPath();
|
||||
for (String subnetId : subnets.getList("DescribeSubnetsResponse.subnetSet.item.subnetId", String.class)) {
|
||||
ec2("DeleteSubnet", "test", "us-east-1").formParam("SubnetId", subnetId).post("/").then().statusCode(200);
|
||||
}
|
||||
XmlPath groups = ec2("DescribeSecurityGroups", "test", "us-east-1")
|
||||
.formParam("Filter.1.Name", "vpc-id")
|
||||
.formParam("Filter.1.Value.1", vpcId)
|
||||
.post("/").then().statusCode(200).extract().xmlPath();
|
||||
for (String groupId : groups.getList("DescribeSecurityGroupsResponse.securityGroupInfo.item"
|
||||
+ ".findAll { it.groupName != 'default' }.groupId", String.class)) {
|
||||
ec2("DeleteSecurityGroup", "test", "us-east-1").formParam("GroupId", groupId).post("/").then().statusCode(200);
|
||||
}
|
||||
ec2("DeleteVpc", "test", "us-east-1").formParam("VpcId", vpcId).post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsPartition;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.ec2.model.BlockDeviceMapping;
|
||||
@@ -616,6 +617,44 @@ class Ec2QueryHandlerTest {
|
||||
return (String) response.getEntity();
|
||||
}
|
||||
|
||||
/** A rejected tag specification keeps its error on a dry run: the tags are read before DryRun is answered. */
|
||||
@ParameterizedTest
|
||||
@CsvSource({"CreateVpc,vpc,InvalidParameter", "CreateSubnet,subnet,InvalidParameter",
|
||||
"CreateSecurityGroup,security-group,InvalidParameterValue"})
|
||||
void aDryRunKeepsTheErrorOfAReservedTagKey(String action, String resourceType, String code) {
|
||||
Ec2Service service = mock(Ec2Service.class);
|
||||
MultivaluedMap<String, String> params = createSubnetParams("10.38.1.0/24");
|
||||
params.putSingle("GroupName", "test");
|
||||
params.putSingle("GroupDescription", "test");
|
||||
params.putSingle("DryRun", "true");
|
||||
params.putSingle("TagSpecification.1.ResourceType", resourceType);
|
||||
params.putSingle("TagSpecification.1.Tag.1.Key", "aws:reserved");
|
||||
params.putSingle("TagSpecification.1.Tag.1.Value", "invalid");
|
||||
|
||||
Response response = handler(service).handle(action, params, "us-east-1");
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
assertTrue(response.getEntity().toString().contains("<Code>" + code + "</Code>"));
|
||||
verifyNoInteractions(service);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSecurityGroupDryRunWithoutAVpcIdNeedsTheDefaultVpcToExist() {
|
||||
Ec2Service service = mock(Ec2Service.class);
|
||||
when(service.requireSecurityGroupVpc("us-east-1", null)).thenThrow(new AwsException(
|
||||
"InvalidVpcID.NotFound", "The vpc ID 'vpc-default-us-east-1' does not exist", 400));
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("GroupName", "test");
|
||||
params.putSingle("GroupDescription", "test");
|
||||
params.putSingle("DryRun", "true");
|
||||
|
||||
Response response = handler(service).handle("CreateSecurityGroup", params, "us-east-1");
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
assertTrue(response.getEntity().toString().contains("<Code>InvalidVpcID.NotFound</Code>"));
|
||||
verify(service, never()).createSecurityGroup(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
private Ec2QueryHandler handler(Ec2Service service) {
|
||||
return handler(service, new RegionResolver("us-east-1", "000000000000"));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user