refactor(cloudformation): move the EC2 networking types into Ec2NetworkCfnProvisioner (#3223)

* refactor(cloudformation): move the EC2 networking types into Ec2NetworkCfnProvisioner

Batch 4 of the CloudFormationResourceProvisioner split. AWS::EC2::Subnet, InternetGateway,
RouteTable, Route, NatGateway, EIP and SubnetRouteTableAssociation move into a new
Ec2NetworkCfnProvisioner that injects only Ec2Service; the seven arms, their switch cases
and type-list entries leave the monolith (SecurityGroup and Instance stay for now).

Behaviour is preserved: same physical ids (the EC2 id, a generated one for a Route, the
public IP for an EIP), same attribute keys, no delete arm (the switch had none for these
types, so stack teardown still leaves them alone; that follows separately), and the same
re-create-on-update path. The one addition is the Route's CidrBlock attribute, the read-only
property the registry schema declares, set to the destination the route was created with.
The read-only attributes Floci does not emulate (Subnet NetworkAclAssociationId,
Ipv6CidrBlocks, BlockPublicAccessStates; NatGateway EniId, AutoProvisionZones, AutoScalingIps,
RouteTableId) are recorded in getatt-attribute-gaps.tsv with reasons, since the coverage gate
starts auditing these types once they leave the switch.

The unit test covers each type's physical id and exact attribute set with a mocked service.

* fix(cloudformation): delete the EC2 networking resources a stack created

The legacy switch had no delete arm for Subnet, InternetGateway, RouteTable, Route,
NatGateway, EIP or SubnetRouteTableAssociation, so DeleteStack logged "No delete
implemented" and left all seven behind. Ec2NetworkCfnProvisioner now deletes each through
its own Ec2Service call, tolerating only that type's not-found code (InvalidSubnetID.NotFound,
InvalidInternetGatewayID.NotFound, InvalidRouteTableID.NotFound, InvalidRoute.NotFound,
NatGatewayNotFound, InvalidAllocationID.NotFound, InvalidAssociationID.NotFound); a
DependencyViolation still fails the stack delete, as on AWS.

A Route's physical id becomes <RouteTableId>|<destination>, the registry primary identifier
and what Ref returns on AWS; the generated LogicalId-<random> id identified nothing, so a
route could never have been deleted. An id without the separator, from a stack created under
the switch, is left alone rather than guessed at. An EIP's Ref is its public IP, so the release
uses the AllocationId recorded at create time and falls back to a lookup by address.

CloudFormationEc2NetworkingIntegrationTest provisions a public/private networking stack the
way CDK lays one out, checks the Ref and Fn::GetAtt shapes, and asserts the delete removes
every id from the EC2 describe calls.

* fix(cloudformation): keep EC2 networking resources across stack updates instead of re-creating them

provision runs again on every UpdateStack, and the switch created a new subnet, gateway,
route table, route, NAT gateway, EIP and association each time, re-pointing the stack at the
copies and leaving the originals behind. Ec2NetworkCfnProvisioner now describes the prior
entity and keeps it when its create-only properties are unchanged (Subnet: VpcId, CidrBlock,
AvailabilityZone; RouteTable: VpcId; NatGateway: SubnetId, AllocationId; association: both;
Route: table and destination; InternetGateway and EIP: nothing a template can change), applying
the mutable ones in place (MapPublicIpOnLaunch, a route's target through ReplaceRoute). A
changed create-only property creates the replacement, and the ReplacementCleanup record
deletes the displaced entity once the update commits or restores it on rollback, as
CloudFormation does; a prior entity gone out of band is created anew.

The end-to-end test deploys the same template twice and asserts every id survives, then
changes the public subnet's CIDR and asserts the subnet and the NAT gateway inside it are
replaced and the displaced ones removed. The VPC is created through the EC2 API and passed in
as a literal, since Ec2VpcCfnProvisioner still re-creates a VPC on every update (#3033).

* fix(cloudformation): apply Tags to EC2 networking resources

The switch ignored the Tags property on Subnet, InternetGateway, RouteTable, NatGateway and
EIP, so a tagged template produced untagged resources and DescribeSubnets and friends showed
no tagSet. Ec2NetworkCfnProvisioner now writes the resolved tags through CreateTags on create
(a NAT gateway takes them on its own create call) and reconciles them on an in-place update:
keys the template dropped are removed with DeleteTags, the rest rewritten. A template with
no Tags property leaves whatever the entity carries, as before.

* fix(cloudformation): honour ConnectivityType on a CloudFormation NAT gateway

The switch created every AWS::EC2::NatGateway as public, whatever the template said, so a
private NAT gateway (no EIP, the shape a private-only VPC uses) came out public with no
address. The provisioner now passes ConnectivityType through, defaulting to public as the
schema does, validates the pairing the way AWS does (a public gateway requires AllocationId,
a private one must not carry one) with ValidationError, and treats ConnectivityType as the
create-only property it is: a change replaces the gateway.

* fix(cloudformation): validate the required properties of the EC2 networking types

A template that omitted VpcId on a Subnet or RouteTable, RouteTableId or SubnetId on an
association, or RouteTableId or a single destination on a Route passed the null through to
Ec2Service, which answered with its own parameter errors or a NullPointerException. The
provisioner now fails the resource with ValidationError using the repo's wording
("AWS::EC2::Subnet requires VpcId"; a Route requires exactly one of the three destination
properties), before any service call, so the stack event names the property.

* fix(cloudformation): never orphan an EC2 networking entity when a step after its create fails

Tags were applied before the resource had its physical id, and the replacement record is
only written when provision returns, so a CreateTags failure after the EC2 create left the
new subnet, gateway, route table or EIP behind: the engine deletes a failed create only when
it can see the id (and the rollback-owned marker), and on a failed update it restores the
previous resource metadata and forgets what the attempt made. The provisioner now writes the
id and attributes right after the create and runs the following steps under a guard that, when
this provision created the entity, deletes it again before the failure propagates; a reused
entity is left as it is.

* fix(cloudformation): roll back in-place changes to EC2 networking resources

rollbackUpdate answered true for a reused gateway, route table, NAT gateway or EIP on the
grounds that nothing about them is mutable, which stopped being true once Tags were applied
in place: a later resource failing produced UPDATE_ROLLBACK_COMPLETE with the failed
template's tags still on the entity. A subnet or route changed in place reported not rolled
back and stayed changed.

The provisioner now snapshots what an in-place update is about to change on a reused entity
(the prior tags and the keys it writes, a subnet's prior MapPublicIpOnLaunch, a route's prior
target) into an internal __FlociEc2NetworkPrior attribute before the change, and
rollbackUpdate restores it: keys the update added are removed and the prior tags written
back, the subnet attribute and the route target put back through ModifySubnetAttribute and
ReplaceRoute. completeUpdate and clearUpdate drop the snapshot. Every one of the seven types
now rolls back for real; the one case left is the resource whose own provision failed
mid-way, whose previous metadata the engine restores before any rollback runs, as for every
provisioner.

The end-to-end test flips a route table tag and a subnet's MapPublicIpOnLaunch next to a
resource that cannot be created and asserts UPDATE_ROLLBACK_COMPLETE leaves both as before.

* fix(cloudformation): require SubnetId on a CloudFormation NAT gateway

The registry schema declares no required properties for AWS::EC2::NatGateway, but
CreateNatGateway cannot do anything without a subnet and Ec2Service answered a missing one
with InvalidSubnetID.NotFound for "null". The provisioner now fails the resource with the
repo's ValidationError wording before any service call, as it does for the other required
properties. Also bounds the test helper's varargs loop so an odd argument count cannot read
past the array, which CodeQL flagged.

* fix(cloudformation): key a CloudFormation route by the canonical CIDR the service stores

Ec2Service canonicalises an IPv4 destination on CreateRoute (10.40.0.18/24 is stored as
10.40.0.0/24), but the provisioner built the physical id, the CidrBlock attribute and the
reuse check from the template's raw value. A template with a non-canonical destination
therefore missed its own route on every unchanged update and tried to create it again,
which RouteAlreadyExists refused, and Ref exposed a string AWS would never return. The
provisioner now runs the IPv4 destination through the same CidrCanonicalizer before using it
as an identifier; IPv6 and prefix-list destinations are unchanged, and the create and replace
calls still pass the raw value, which the service canonicalises again.

* fix(cloudformation): undo a partial in-place change when an EC2 networking update fails mid-way

The in-place snapshot lived only on the attempted StackResource. When the update of a reused
entity failed after its first change (DeleteTags done, CreateTags refused), the engine
discarded that object, restored the previous metadata and never called rollbackUpdate, so
the entity kept the partial change under an UPDATE_ROLLBACK_COMPLETE. The guard that already
undoes a create when a later step throws now also restores a reused entity from its snapshot
before the failure propagates, and the NAT gateway's reuse-path tags and the route's in-place
re-target run inside it. The engine's metadata restore then matches the entity again.

* fix(cloudformation): report a failed compensation on an EC2 networking resource instead of hiding it

When the undo inside the guard failed too (the delete of an entity this provision created, or
the restore of a reused one from its snapshot), the failure was only attached as suppressed,
the snapshot was already gone, and the engine, seeing no failure marker on the attempted
resource, restored the previous metadata and reported UPDATE_ROLLBACK_COMPLETE over a
partially updated entity or a leaked create.

The guard now uses the engine's contract for exactly this, as IotCfnProvisioner and
IamRoleCfnProvisioner do: a created entity carries __FlociRollbackOwned while the steps run,
so a failed undo leaves it for the engine's create rollback to delete and report; a reused
entity keeps its snapshot when the restore fails, and the reason goes into
__FlociUpdateRollbackFailure, which the engine copies onto the committed resource so the
rollback walker reports UPDATE_ROLLBACK_FAILED with it. A successful undo or restore clears
both markers; the original failure still propagates.

* fix(cloudformation): keep a replacement that a failed update could not remove owed to the next cleanup

During a replacement update, when a step after the EC2 create failed and the undo delete of
the new entity failed too, the rollback-owned and failure markers sat on the attempted
resource, which the engine discards while restoring the previous one: the stack reported
UPDATE_ROLLBACK_FAILED, correctly, but the new entity's id went with the attempt and nothing
would ever retry deleting it.

The entity is now listed as a non-retainable entry in the ReplacementCleanup record (new
recordOrphan), and the engine's mergeFailedUpdateResourceTracking hook, which so far carried
only ApiGatewayV2 tracking, merges the attempt's record onto the restored resource (new
mergeDisplaced), for every provisioner that uses the helper. The engine already runs that
record before every committed update and before a stack delete, retrying up to three times
and reporting the failure otherwise, so the orphan is removed at the next opportunity.
ReplacementCleanupTest pins the helper; the merge hook is covered next to its existing case.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-07 23:29:35 -05:00
1 parent 1f4d43c4cc
commit 725577416d
10 files changed
+2033 -91

No files matched your search

@@ -17,6 +17,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
@@ -169,6 +170,28 @@ class ApiGatewayV2CfnProvisionerTest {
previous.getAttributes().get("__FlociApiGatewayV2BodyAuthorizerIds"));
}
@Test
void carriesAReplacementCleanupRecordOntoTheRestoredResourceForAnyType() {
StackResource previous = new StackResource();
previous.setLogicalId("Subnet");
previous.setResourceType("AWS::EC2::Subnet");
previous.setPhysicalId("subnet-prior");
previous.setAttributes(new java.util.HashMap<>());
StackResource attempted = new StackResource();
attempted.setLogicalId("Subnet");
attempted.setResourceType("AWS::EC2::Subnet");
attempted.setPhysicalId("subnet-replacement");
attempted.setAttributes(new java.util.HashMap<>(Map.of(
"__FlociReplacementCleanup",
"{\"region\":\"us-east-1\",\"displaced\":[{\"physicalId\":\"subnet-replacement\",\"resourceType\":\"AWS::EC2::Subnet\",\"region\":\"us-east-1\",\"retainable\":false,\"cleanupAttempts\":1}]}")));
provisioner.mergeFailedUpdateResourceTracking(previous, attempted);
String record = previous.getAttributes().get("__FlociReplacementCleanup");
assertTrue(record != null && record.contains("subnet-replacement") && record.contains("\"cleanupAttempts\":1"),
"the orphan the attempt could not remove is owed on the restored resource: " + record);
}
@Test
void materializesInheritedJwtSecurityAndHonorsOperationOptOut() throws Exception {
Authorizer authorizer = new Authorizer();
@@ -34,6 +34,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetada
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2LaunchTemplateCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2NetworkCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2NetworkAclCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2SecurityGroupRuleCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2VpcCfnProvisioner;
@@ -302,6 +303,7 @@ final class CfnProvisionerFixture {
discovered.add(new Ec2NetworkAclCfnProvisioner(ec2Service));
discovered.add(new Ec2SecurityGroupRuleCfnProvisioner(ec2Service));
discovered.add(new Ec2LaunchTemplateCfnProvisioner(ec2Service));
discovered.add(new Ec2NetworkCfnProvisioner(ec2Service));
}
if (route53Service != null) {
discovered.add(new Route53CfnProvisioner(route53Service));
@@ -0,0 +1,291 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* A public/private networking stack the way CDK lays one out: internet gateway and attachment,
* a public subnet with a route table routing {@code 0.0.0.0/0} to the gateway and an association, an
* EIP and a NAT gateway in that subnet, and a private route table routing to the NAT. Asserts the
* {@code Ref} shapes ({@code Route} is {@code <RouteTableId>|<destination>}, {@code EIP} the public IP)
* and the {@code Fn::GetAtt} attributes, that an {@code UpdateStack} with the same template keeps
* every id (the legacy switch re-created all of them), that a changed subnet CIDR replaces the subnet
* and the NAT gateway inside it and removes the displaced ones, and that {@code DeleteStack} removes
* every one of the seven networking resources, which the legacy switch left behind. A second case
* changes a route table's tag and a subnet's MapPublicIpOnLaunch in place next to a resource that
* fails, and asserts the rollback puts both back. The VPC is
* created through the EC2 API and passed in as a literal: {@code Ec2VpcCfnProvisioner} still
* re-creates a VPC on every update (the #3033 fix), which would rightly replace everything in it.
*/
@QuarkusTest
class CloudFormationEc2NetworkingIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260907/us-east-1/cloudformation/aws4_request";
private static final String EC2_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260907/us-east-1/ec2/aws4_request";
private static final String STACK = "ec2-networking-it";
private static String template(String vpcId, String publicSubnetCidr) {
return template(vpcId, publicSubnetCidr, "{\"Key\": \"tier\", \"Value\": \"web\"}");
}
private static final String ROLLBACK_STACK = "ec2-networking-rollback-it";
/** A subnet and a tagged route table; the second form flips the mutable properties and adds a resource that cannot be created. */
private static String rollbackTemplate(String vpcId, boolean changed) {
String failing = changed
? ",\n \"Boom\": {\"Type\": \"AWS::SecretsManager::Secret\","
+ " \"Properties\": {\"SecretString\": \"x\", \"GenerateSecretString\": {\"SecretStringTemplate\": \"{}\", \"GenerateStringKey\": \"p\"}}}"
: "";
return """
{
"Resources": {
"Subnet": {"Type": "AWS::EC2::Subnet",
"Properties": {"VpcId": "%1$s", "CidrBlock": "10.41.0.0/24", "MapPublicIpOnLaunch": %2$s}},
"Rt": {"Type": "AWS::EC2::RouteTable",
"Properties": {"VpcId": "%1$s", "Tags": [{"Key": "Name", "Value": "%3$s"}]}}%4$s
},
"Outputs": {"SubnetId": {"Value": {"Ref": "Subnet"}}, "RtId": {"Value": {"Ref": "Rt"}}}
}
""".formatted(vpcId, changed ? "false" : "true", changed ? "after" : "before", failing);
}
@Test
void anInPlaceChangeNextToAFailingResourceIsRolledBack() throws Exception {
String vpcId = between(ec2("CreateVpc", Map.of("CidrBlock", "10.41.0.0/16")), "<vpcId>", "</vpcId>");
cloudFormation(ROLLBACK_STACK, "CreateStack", rollbackTemplate(vpcId, false));
Map<String, String> out = XmlParser.extractPairs(describeStacks(ROLLBACK_STACK, "CREATE_COMPLETE"), "Outputs", "OutputKey", "OutputValue");
assertTrue(ec2("DescribeRouteTables").contains("<value>before</value>"));
assertTrue(subnetXml(out.get("SubnetId")).contains("<mapPublicIpOnLaunch>true</mapPublicIpOnLaunch>"));
cloudFormation(ROLLBACK_STACK, "UpdateStack", rollbackTemplate(vpcId, true));
describeStacks(ROLLBACK_STACK, "UPDATE_ROLLBACK_COMPLETE");
String routeTables = ec2("DescribeRouteTables");
assertTrue(routeTables.contains("<value>before</value>") && !routeTables.contains("<value>after</value>"),
"the route table's prior tag must be back: " + routeTables);
assertTrue(subnetXml(out.get("SubnetId")).contains("<mapPublicIpOnLaunch>true</mapPublicIpOnLaunch>"),
"the subnet's prior MapPublicIpOnLaunch must be back");
cloudFormation(ROLLBACK_STACK, "DeleteStack", null);
awaitStackDeleted(ROLLBACK_STACK);
ec2("DeleteVpc", Map.of("VpcId", vpcId));
}
private static String subnetXml(String subnetId) {
return ec2("DescribeSubnets", Map.of("SubnetId.1", subnetId));
}
private static String template(String vpcId, String publicSubnetCidr, String extraSubnetTag) {
return """
{
"Resources": {
"Igw": {"Type": "AWS::EC2::InternetGateway"},
"Attach": {"Type": "AWS::EC2::VPCGatewayAttachment",
"Properties": {"VpcId": "%1$s", "InternetGatewayId": {"Ref": "Igw"}}},
"PublicSubnet": {"Type": "AWS::EC2::Subnet",
"Properties": {"VpcId": "%1$s", "CidrBlock": "%2$s",
"AvailabilityZone": "us-east-1a", "MapPublicIpOnLaunch": true,
"Tags": [{"Key": "Name", "Value": "public"}, %3$s]}},
"PublicRt": {"Type": "AWS::EC2::RouteTable",
"Properties": {"VpcId": "%1$s", "Tags": [{"Key": "Name", "Value": "public-rt"}]}},
"PublicRoute": {"Type": "AWS::EC2::Route", "DependsOn": "Attach",
"Properties": {"RouteTableId": {"Ref": "PublicRt"}, "DestinationCidrBlock": "0.0.0.0/0",
"GatewayId": {"Ref": "Igw"}}},
"PeerRoute": {"Type": "AWS::EC2::Route",
"Properties": {"RouteTableId": {"Ref": "PublicRt"}, "DestinationCidrBlock": "10.99.0.18/24",
"GatewayId": {"Ref": "Igw"}}},
"PublicAssoc": {"Type": "AWS::EC2::SubnetRouteTableAssociation",
"Properties": {"RouteTableId": {"Ref": "PublicRt"}, "SubnetId": {"Ref": "PublicSubnet"}}},
"NatEip": {"Type": "AWS::EC2::EIP", "Properties": {"Domain": "vpc"}},
"Nat": {"Type": "AWS::EC2::NatGateway",
"Properties": {"SubnetId": {"Ref": "PublicSubnet"}, "AllocationId": {"Fn::GetAtt": ["NatEip", "AllocationId"]}}},
"PrivateRt": {"Type": "AWS::EC2::RouteTable", "Properties": {"VpcId": "%1$s"}},
"PrivateRoute": {"Type": "AWS::EC2::Route",
"Properties": {"RouteTableId": {"Ref": "PrivateRt"}, "DestinationCidrBlock": "0.0.0.0/0",
"NatGatewayId": {"Ref": "Nat"}}}
},
"Outputs": {
"SubnetId": {"Value": {"Ref": "PublicSubnet"}},
"SubnetAz": {"Value": {"Fn::GetAtt": ["PublicSubnet", "AvailabilityZone"]}},
"IgwId": {"Value": {"Ref": "Igw"}},
"PublicRtId": {"Value": {"Ref": "PublicRt"}},
"PrivateRtId": {"Value": {"Ref": "PrivateRt"}},
"PublicRouteRef": {"Value": {"Ref": "PublicRoute"}},
"PublicRouteCidr": {"Value": {"Fn::GetAtt": ["PublicRoute", "CidrBlock"]}},
"PeerRouteRef": {"Value": {"Ref": "PeerRoute"}},
"AssocId": {"Value": {"Ref": "PublicAssoc"}},
"EipRef": {"Value": {"Ref": "NatEip"}},
"EipAllocationId": {"Value": {"Fn::GetAtt": ["NatEip", "AllocationId"]}},
"NatId": {"Value": {"Ref": "Nat"}}
}
}
""".formatted(vpcId, publicSubnetCidr, extraSubnetTag);
}
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void networkingStackExposesTheAwsRefShapesAndDeletesEverythingItCreated() throws Exception {
String vpcId = between(ec2("CreateVpc", Map.of("CidrBlock", "10.40.0.0/16")), "<vpcId>", "</vpcId>");
cloudFormation("CreateStack", template(vpcId, "10.40.0.0/24"));
String stacks = describeStacks("CREATE_COMPLETE");
Map<String, String> out = XmlParser.extractPairs(stacks, "Outputs", "OutputKey", "OutputValue");
assertTrue(out.get("SubnetId").startsWith("subnet-"), out.get("SubnetId"));
assertEquals("us-east-1a", out.get("SubnetAz"));
assertTrue(out.get("IgwId").startsWith("igw-"), out.get("IgwId"));
assertTrue(out.get("PublicRtId").startsWith("rtb-"), out.get("PublicRtId"));
assertEquals(out.get("PublicRtId") + "|0.0.0.0/0", out.get("PublicRouteRef"),
"Ref of a Route is the registry primary identifier, table id and destination");
assertEquals("0.0.0.0/0", out.get("PublicRouteCidr"));
assertEquals(out.get("PublicRtId") + "|10.99.0.0/24", out.get("PeerRouteRef"),
"a non-canonical destination is keyed by the canonical CIDR the service stores");
assertTrue(out.get("AssocId").startsWith("rtbassoc-"), out.get("AssocId"));
assertTrue(out.get("EipAllocationId").startsWith("eipalloc-"), out.get("EipAllocationId"));
assertFalse(out.get("EipRef").startsWith("eipalloc-"), "Ref of an EIP is its public IP: " + out.get("EipRef"));
assertTrue(out.get("NatId").startsWith("nat-"), out.get("NatId"));
String subnets = ec2("DescribeSubnets");
assertTrue(subnets.contains(out.get("SubnetId")));
assertTrue(subnets.contains("<key>tier</key>") && subnets.contains("<value>web</value>"), "subnet tags must reach EC2: " + subnets);
String routeTables = ec2("DescribeRouteTables");
assertTrue(routeTables.contains("<value>public-rt</value>"), "route table tags must reach EC2");
assertTrue(routeTables.contains(out.get("PublicRtId")) && routeTables.contains(out.get("AssocId")));
assertTrue(routeTables.contains(out.get("NatId")), "the private route must point at the NAT gateway");
assertTrue(ec2("DescribeNatGateways").contains(out.get("NatId")));
assertTrue(ec2("DescribeAddresses").contains(out.get("EipAllocationId")));
assertTrue(ec2("DescribeInternetGateways").contains(out.get("IgwId")));
// The same template again: every id survives (the switch re-created all seven).
cloudFormation("UpdateStack", template(vpcId, "10.40.0.0/24"));
Map<String, String> again = XmlParser.extractPairs(describeStacks("UPDATE_COMPLETE"), "Outputs", "OutputKey", "OutputValue");
assertEquals(out, again, "an unchanged update must keep every networking resource");
// Tags are mutable: a dropped key goes, a changed value is written, the subnet stays.
cloudFormation("UpdateStack", template(vpcId, "10.40.0.0/24", "{\"Key\": \"env\", \"Value\": \"test\"}"));
assertEquals(out.get("SubnetId"), XmlParser.extractPairs(describeStacks("UPDATE_COMPLETE"), "Outputs", "OutputKey", "OutputValue").get("SubnetId"));
String retagged = ec2("DescribeSubnets");
assertTrue(retagged.contains("<key>env</key>"), "the new tag must be written");
assertFalse(retagged.contains("<key>tier</key>"), "the dropped tag must be removed");
// CidrBlock is createOnly: the public subnet is replaced, and with it the NAT gateway and the
// association that name it; the gateway, EIP and route tables stay.
cloudFormation("UpdateStack", template(vpcId, "10.40.2.0/24"));
Map<String, String> replaced = XmlParser.extractPairs(describeStacks("UPDATE_COMPLETE"), "Outputs", "OutputKey", "OutputValue");
assertFalse(out.get("SubnetId").equals(replaced.get("SubnetId")), "a changed CIDR must replace the subnet");
assertFalse(out.get("NatId").equals(replaced.get("NatId")), "the NAT gateway follows its subnet");
assertFalse(out.get("AssocId").equals(replaced.get("AssocId")), "the association follows its subnet");
assertEquals(out.get("IgwId"), replaced.get("IgwId"));
assertEquals(out.get("EipAllocationId"), replaced.get("EipAllocationId"));
assertEquals(out.get("PublicRtId"), replaced.get("PublicRtId"));
assertEquals(out.get("PrivateRtId"), replaced.get("PrivateRtId"));
assertFalse(ec2("DescribeSubnets").contains(out.get("SubnetId")), "the displaced subnet must be gone");
assertFalse(ec2("DescribeNatGateways").contains(out.get("NatId")), "the displaced NAT gateway must be gone");
assertTrue(ec2("DescribeSubnets").contains(replaced.get("SubnetId")));
out = replaced;
cloudFormation("DeleteStack", null);
awaitStackDeleted();
for (String id : List.of(out.get("SubnetId"), out.get("PublicRtId"), out.get("PrivateRtId"),
out.get("AssocId"), out.get("NatId"), out.get("EipAllocationId"), out.get("IgwId"))) {
String everything = ec2("DescribeSubnets") + ec2("DescribeRouteTables") + ec2("DescribeNatGateways")
+ ec2("DescribeAddresses") + ec2("DescribeInternetGateways");
assertFalse(everything.contains(id), "stack delete must remove " + id);
}
ec2("DeleteVpc", Map.of("VpcId", vpcId));
}
private static String between(String haystack, String open, String close) {
int start = haystack.indexOf(open);
int end = haystack.indexOf(close, start);
assertTrue(start >= 0 && end > start, "missing " + open + " in " + haystack);
return haystack.substring(start + open.length(), end);
}
private static void cloudFormation(String action, String templateBody) {
cloudFormation(STACK, action, templateBody);
}
private static void cloudFormation(String stack, String action, String templateBody) {
var request = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stack);
if (templateBody != null) {
request.formParam("TemplateBody", templateBody);
}
request.when().post("/").then().statusCode(200);
}
private static String describeStacks(String expectedStatus) {
return describeStacks(STACK, expectedStatus);
}
private static String describeStacks(String stack, String expectedStatus) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stack)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
.extract().asString();
}
private static void awaitStackDeleted() throws InterruptedException {
awaitStackDeleted(STACK);
}
private static void awaitStackDeleted(String stack) throws InterruptedException {
for (int i = 0; i < 200; i++) {
String body = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stack)
.when().post("/").then().extract().asString();
if (body.contains("does not exist")) {
return;
}
if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
fail("stack delete failed: " + body);
}
Thread.sleep(50);
}
fail("stack " + stack + " was not deleted within the timeout");
}
private static String ec2(String action) {
return ec2(action, Map.of());
}
private static String ec2(String action, Map<String, String> params) {
var request = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", EC2_AUTH)
.formParam("Action", action)
.formParam("Version", "2016-11-15");
params.forEach(request::formParam);
return request.when().post("/").then().statusCode(200).extract().asString();
}
}
@@ -0,0 +1,935 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
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;
import io.github.hectorvent.floci.services.ec2.model.Address;
import io.github.hectorvent.floci.services.ec2.model.InternetGateway;
import io.github.hectorvent.floci.services.ec2.model.NatGateway;
import io.github.hectorvent.floci.services.ec2.model.Route;
import io.github.hectorvent.floci.services.ec2.model.RouteTable;
import io.github.hectorvent.floci.services.ec2.model.RouteTableAssociation;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import org.mockito.ArgumentCaptor;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import io.github.hectorvent.floci.core.common.AwsException;
import java.util.Map;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* The EC2 networking provisioner in isolation: one mocked service. Every case asserts the exact
* physical id and the exact {@code Fn::GetAtt} attribute keys, since an unmapped type still reports
* CREATE_COMPLETE through the dispatcher's stub arm.
*/
class Ec2NetworkCfnProvisionerTest {
private static final String REGION = "us-east-1";
private static final String VPC_ID = "vpc-0123456789abcdef0";
private static final String SUBNET_ID = "subnet-0123456789abcdef0";
private static final String RTB_ID = "rtb-0123456789abcdef0";
private static final String IGW_ID = "igw-0123456789abcdef0";
private static final String NAT_ID = "nat-0123456789abcdef0";
private static final String ASSOC_ID = "rtbassoc-0123456789abcdef0";
private static final String ALLOC_ID = "eipalloc-0123456789abcdef0";
private static final String PUBLIC_IP = "54.0.0.1";
private final Ec2Service ec2 = mock(Ec2Service.class);
private final Ec2NetworkCfnProvisioner provisioner = new Ec2NetworkCfnProvisioner(ec2);
private final ObjectMapper mapper = new ObjectMapper();
private ProvisionContext ctx() {
return ctx(null);
}
private ProvisionContext ctx(String priorPhysicalId) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
when(engine.resolveStringList(any())).thenCallRealMethod();
return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
}
private static StackResource resource(String type, String logicalId) {
StackResource r = new StackResource();
r.setLogicalId(logicalId);
r.setResourceType(type);
r.setAttributes(new HashMap<>());
return r;
}
private static Subnet subnet() {
Subnet s = new Subnet();
s.setSubnetId(SUBNET_ID);
s.setVpcId(VPC_ID);
s.setCidrBlock("10.0.1.0/24");
s.setAvailabilityZone("us-east-1a");
return s;
}
@Test
void subnetSetsItsIdAndTheThreeAttributesAndAppliesMapPublicIpOnLaunch() {
when(ec2.createSubnet(REGION, VPC_ID, "10.0.1.0/24", "us-east-1a")).thenReturn(subnet());
ObjectNode props = mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24")
.put("AvailabilityZone", "us-east-1a").put("MapPublicIpOnLaunch", true);
StackResource r = resource("AWS::EC2::Subnet", "Subnet");
provisioner.provision(r, props, ctx());
assertEquals(SUBNET_ID, r.getPhysicalId());
assertEquals(Set.of("SubnetId", "VpcId", "AvailabilityZone"), r.getAttributes().keySet());
assertEquals("us-east-1a", r.getAttributes().get("AvailabilityZone"));
verify(ec2).modifySubnetAttribute(REGION, SUBNET_ID, "mapPublicIpOnLaunch", "true");
}
@Test
void subnetWithoutMapPublicIpOnLaunchLeavesTheAttributeAlone() {
when(ec2.createSubnet(eq(REGION), eq(VPC_ID), eq("10.0.1.0/24"), isNull())).thenReturn(subnet());
provisioner.provision(resource("AWS::EC2::Subnet", "Subnet"),
mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24"), ctx());
verify(ec2, never()).modifySubnetAttribute(any(), any(), any(), any());
}
@Test
void internetGatewaySetsItsIdAttribute() {
InternetGateway igw = new InternetGateway();
igw.setInternetGatewayId(IGW_ID);
when(ec2.createInternetGateway(REGION)).thenReturn(igw);
StackResource r = resource("AWS::EC2::InternetGateway", "Igw");
provisioner.provision(r, mapper.createObjectNode(), ctx());
assertEquals(IGW_ID, r.getPhysicalId());
assertEquals(Set.of("InternetGatewayId"), r.getAttributes().keySet());
}
@Test
void routeTableSetsItsIdAttribute() {
RouteTable rt = new RouteTable();
rt.setRouteTableId(RTB_ID);
rt.setVpcId(VPC_ID);
when(ec2.createRouteTable(REGION, VPC_ID)).thenReturn(rt);
StackResource r = resource("AWS::EC2::RouteTable", "Rtb");
provisioner.provision(r, mapper.createObjectNode().put("VpcId", VPC_ID), ctx());
assertEquals(RTB_ID, r.getPhysicalId());
assertEquals(Set.of("RouteTableId"), r.getAttributes().keySet());
}
@Test
void associationSetsTheSchemasIdAttribute() {
RouteTableAssociation assoc = new RouteTableAssociation();
assoc.setRouteTableAssociationId(ASSOC_ID);
when(ec2.associateRouteTable(REGION, RTB_ID, SUBNET_ID)).thenReturn(assoc);
StackResource r = resource("AWS::EC2::SubnetRouteTableAssociation", "Assoc");
provisioner.provision(r, mapper.createObjectNode().put("RouteTableId", RTB_ID).put("SubnetId", SUBNET_ID), ctx());
assertEquals(ASSOC_ID, r.getPhysicalId());
assertEquals(Set.of("Id"), r.getAttributes().keySet());
}
@Test
void routePassesEveryTargetAndExposesTheDestinationAsCidrBlock() {
StackResource r = resource("AWS::EC2::Route", "Default");
ObjectNode props = mapper.createObjectNode().put("RouteTableId", RTB_ID)
.put("DestinationCidrBlock", "0.0.0.0/0").put("GatewayId", IGW_ID);
provisioner.provision(r, props, ctx());
verify(ec2).createRoute(REGION, RTB_ID, "0.0.0.0/0", null, null, IGW_ID, null, null, null);
assertEquals(RTB_ID + "|0.0.0.0/0", r.getPhysicalId(), "Ref is the registry primary identifier");
assertEquals(Set.of("CidrBlock"), r.getAttributes().keySet());
assertEquals("0.0.0.0/0", r.getAttributes().get("CidrBlock"));
}
@Test
void routeToAPrefixListExposesThatAsCidrBlock() {
StackResource r = resource("AWS::EC2::Route", "S3Route");
ObjectNode props = mapper.createObjectNode().put("RouteTableId", RTB_ID)
.put("DestinationPrefixListId", "pl-63a5400a").put("NatGatewayId", NAT_ID);
provisioner.provision(r, props, ctx());
verify(ec2).createRoute(REGION, RTB_ID, null, null, "pl-63a5400a", null, NAT_ID, null, null);
assertEquals("pl-63a5400a", r.getAttributes().get("CidrBlock"));
}
@Test
void natGatewayIsCreatedPublicWithNoTags() {
NatGateway nat = new NatGateway();
nat.setNatGatewayId(NAT_ID);
when(ec2.createNatGateway(REGION, SUBNET_ID, ALLOC_ID, "public", List.of())).thenReturn(nat);
StackResource r = resource("AWS::EC2::NatGateway", "Nat");
provisioner.provision(r, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID), ctx());
assertEquals(NAT_ID, r.getPhysicalId());
assertEquals(Set.of("NatGatewayId"), r.getAttributes().keySet());
}
@Test
void eipRefIsThePublicIpAndAllocationIdIsAnAttribute() {
Address addr = new Address();
addr.setAllocationId(ALLOC_ID);
addr.setPublicIp(PUBLIC_IP);
when(ec2.allocateAddress(REGION)).thenReturn(addr);
StackResource r = resource("AWS::EC2::EIP", "Eip");
provisioner.provision(r, mapper.createObjectNode().put("Domain", "vpc"), ctx());
assertEquals(PUBLIC_IP, r.getPhysicalId());
assertEquals(Set.of("AllocationId", "PublicIp"), r.getAttributes().keySet());
assertEquals(ALLOC_ID, r.getAttributes().get("AllocationId"));
}
@Test
void deletesUseEachTypesOwnApiAndTolerateOnlyItsNotFoundCode() {
provisioner.delete("AWS::EC2::Subnet", SUBNET_ID, REGION);
provisioner.delete("AWS::EC2::InternetGateway", IGW_ID, REGION);
provisioner.delete("AWS::EC2::RouteTable", RTB_ID, REGION);
provisioner.delete("AWS::EC2::NatGateway", NAT_ID, REGION);
provisioner.delete("AWS::EC2::SubnetRouteTableAssociation", ASSOC_ID, REGION);
verify(ec2).deleteSubnet(REGION, SUBNET_ID);
verify(ec2).deleteInternetGateway(REGION, IGW_ID);
verify(ec2).deleteRouteTable(REGION, RTB_ID);
verify(ec2).deleteNatGateway(REGION, NAT_ID);
verify(ec2).disassociateRouteTable(REGION, ASSOC_ID);
doThrow(new AwsException("InvalidSubnetID.NotFound", "gone", 400)).when(ec2).deleteSubnet(REGION, "subnet-gone");
assertDoesNotThrow(() -> provisioner.delete("AWS::EC2::Subnet", "subnet-gone", REGION));
doThrow(new AwsException("DependencyViolation", "has dependencies", 400)).when(ec2).deleteSubnet(REGION, "subnet-busy");
AwsException e = assertThrows(AwsException.class, () -> provisioner.delete("AWS::EC2::Subnet", "subnet-busy", REGION));
assertEquals("DependencyViolation", e.getErrorCode());
}
@Test
void routeDeleteParsesTheTableAndDestinationFromItsId() {
provisioner.delete("AWS::EC2::Route", RTB_ID + "|0.0.0.0/0", REGION);
provisioner.delete("AWS::EC2::Route", RTB_ID + "|::/0", REGION);
provisioner.delete("AWS::EC2::Route", RTB_ID + "|pl-63a5400a", REGION);
verify(ec2).deleteRoute(REGION, RTB_ID, "0.0.0.0/0", null, null);
verify(ec2).deleteRoute(REGION, RTB_ID, null, "::/0", null);
verify(ec2).deleteRoute(REGION, RTB_ID, null, null, "pl-63a5400a");
}
@Test
void routeDeleteToleratesAMissingRouteOrTableAndSkipsALegacyGeneratedId() {
doThrow(new AwsException("InvalidRouteTableID.NotFound", "gone", 400))
.when(ec2).deleteRoute(REGION, "rtb-gone", "10.0.0.0/8", null, null);
assertDoesNotThrow(() -> provisioner.delete("AWS::EC2::Route", "rtb-gone|10.0.0.0/8", REGION));
assertDoesNotThrow(() -> provisioner.delete("AWS::EC2::Route", "Default-1a2b3c4d", REGION));
verify(ec2, never()).deleteRoute(eq(REGION), eq("Default-1a2b3c4d"), any(), any(), any());
}
@Test
void eipReleaseUsesTheRecordedAllocationIdOrLooksTheAddressUpByIp() {
StackResource r = resource("AWS::EC2::EIP", "Eip");
r.setPhysicalId(PUBLIC_IP);
r.getAttributes().put("AllocationId", ALLOC_ID);
provisioner.delete(r, REGION);
verify(ec2).releaseAddress(REGION, ALLOC_ID);
verify(ec2, never()).describeAddresses(any(), any(), any());
Address addr = new Address();
addr.setAllocationId("eipalloc-byip");
addr.setPublicIp("54.0.0.2");
when(ec2.describeAddresses(REGION, List.of(), Map.of("public-ip", List.of("54.0.0.2")))).thenReturn(List.of(addr));
provisioner.delete("AWS::EC2::EIP", "54.0.0.2", REGION);
verify(ec2).releaseAddress(REGION, "eipalloc-byip");
when(ec2.describeAddresses(REGION, List.of(), Map.of("public-ip", List.of("54.0.0.3")))).thenReturn(List.of());
assertDoesNotThrow(() -> provisioner.delete("AWS::EC2::EIP", "54.0.0.3", REGION));
}
private static StackResource prior(String type, String logicalId, String physicalId, Map<String, String> attributes) {
StackResource r = resource(type, logicalId);
r.setPhysicalId(physicalId);
r.getAttributes().putAll(attributes);
return r;
}
@Test
void anUnchangedSubnetIsKeptAndOnlyMapPublicIpOnLaunchIsApplied() {
when(ec2.describeSubnets(REGION, List.of(SUBNET_ID), Map.of())).thenReturn(List.of(subnet()));
StackResource r = prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of("SubnetId", SUBNET_ID, "VpcId", VPC_ID, "AvailabilityZone", "us-east-1a"));
ObjectNode props = mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24")
.put("AvailabilityZone", "us-east-1a").put("MapPublicIpOnLaunch", false);
provisioner.provision(r, props, ctx(SUBNET_ID));
verify(ec2, never()).createSubnet(any(), any(), any(), any());
verify(ec2).modifySubnetAttribute(REGION, SUBNET_ID, "mapPublicIpOnLaunch", "false");
assertEquals(SUBNET_ID, r.getPhysicalId());
assertFalse(provisioner.hasReplacementUpdate(r));
assertTrue(provisioner.rollbackUpdate(r), "the prior MapPublicIpOnLaunch is restored from the snapshot");
verify(ec2).modifySubnetAttribute(REGION, SUBNET_ID, "mapPublicIpOnLaunch", "false");
assertFalse(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));
}
@Test
void aSubnetWithAChangedCidrIsReplacedAndThePriorOneIsOwedToCleanup() {
Subnet current = subnet();
current.setCidrBlock("10.0.1.0/24");
when(ec2.describeSubnets(REGION, List.of(SUBNET_ID), Map.of())).thenReturn(List.of(current));
Subnet replacement = subnet();
replacement.setSubnetId("subnet-replacement");
when(ec2.createSubnet(REGION, VPC_ID, "10.0.2.0/24", "us-east-1a")).thenReturn(replacement);
StackResource r = prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of("SubnetId", SUBNET_ID));
ObjectNode props = mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.2.0/24").put("AvailabilityZone", "us-east-1a");
provisioner.provision(r, props, ctx(SUBNET_ID));
assertEquals("subnet-replacement", r.getPhysicalId());
assertTrue(provisioner.hasReplacementUpdate(r));
assertEquals(SUBNET_ID, provisioner.updateCleanupPhysicalId(r));
provisioner.completeUpdate(r);
verify(ec2).deleteSubnet(REGION, SUBNET_ID);
}
@Test
void aSubnetGoneOutOfBandIsCreatedAnew() {
when(ec2.describeSubnets(REGION, List.of(SUBNET_ID), Map.of()))
.thenThrow(new AwsException("InvalidSubnetID.NotFound", "gone", 400));
when(ec2.createSubnet(REGION, VPC_ID, "10.0.1.0/24", null)).thenReturn(subnet());
StackResource r = prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of());
provisioner.provision(r, mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24"), ctx(SUBNET_ID));
assertEquals(SUBNET_ID, r.getPhysicalId());
}
@Test
void anInternetGatewayAndARouteTableInTheSameVpcAreKeptAndRollBackAsComplete() {
InternetGateway igw = new InternetGateway();
igw.setInternetGatewayId(IGW_ID);
when(ec2.describeInternetGateways(REGION, List.of(IGW_ID), Map.of())).thenReturn(List.of(igw));
RouteTable rt = new RouteTable();
rt.setRouteTableId(RTB_ID);
rt.setVpcId(VPC_ID);
when(ec2.describeRouteTables(REGION, List.of(RTB_ID), Map.of())).thenReturn(List.of(rt));
StackResource igwResource = prior("AWS::EC2::InternetGateway", "Igw", IGW_ID, Map.of("InternetGatewayId", IGW_ID));
StackResource rtResource = prior("AWS::EC2::RouteTable", "Rtb", RTB_ID, Map.of("RouteTableId", RTB_ID));
provisioner.provision(igwResource, mapper.createObjectNode(), ctx(IGW_ID));
provisioner.provision(rtResource, mapper.createObjectNode().put("VpcId", VPC_ID), ctx(RTB_ID));
verify(ec2, never()).createInternetGateway(any());
verify(ec2, never()).createRouteTable(any(), any());
assertTrue(provisioner.rollbackUpdate(igwResource));
assertTrue(provisioner.rollbackUpdate(rtResource));
}
@Test
void aRouteTableMovedToAnotherVpcIsReplaced() {
RouteTable rt = new RouteTable();
rt.setRouteTableId(RTB_ID);
rt.setVpcId(VPC_ID);
when(ec2.describeRouteTables(REGION, List.of(RTB_ID), Map.of())).thenReturn(List.of(rt));
RouteTable replacement = new RouteTable();
replacement.setRouteTableId("rtb-replacement");
when(ec2.createRouteTable(REGION, "vpc-other")).thenReturn(replacement);
StackResource r = prior("AWS::EC2::RouteTable", "Rtb", RTB_ID, Map.of("RouteTableId", RTB_ID));
provisioner.provision(r, mapper.createObjectNode().put("VpcId", "vpc-other"), ctx(RTB_ID));
assertEquals("rtb-replacement", r.getPhysicalId());
assertEquals(RTB_ID, provisioner.updateCleanupPhysicalId(r));
assertTrue(provisioner.rollbackUpdate(r));
verify(ec2).deleteRouteTable(REGION, "rtb-replacement");
assertEquals(RTB_ID, r.getPhysicalId());
}
@Test
void aNatGatewayWithTheSameSubnetAndAllocationIsKeptAndAChangedSubnetReplacesIt() {
NatGateway nat = new NatGateway();
nat.setNatGatewayId(NAT_ID);
nat.setSubnetId(SUBNET_ID);
nat.setAllocationId(ALLOC_ID);
when(ec2.describeNatGateways(REGION, List.of(NAT_ID), Map.of())).thenReturn(List.of(nat));
StackResource same = prior("AWS::EC2::NatGateway", "Nat", NAT_ID, Map.of("NatGatewayId", NAT_ID));
provisioner.provision(same, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID), ctx(NAT_ID));
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any());
assertEquals(NAT_ID, same.getPhysicalId());
NatGateway replacement = new NatGateway();
replacement.setNatGatewayId("nat-replacement");
when(ec2.createNatGateway(REGION, "subnet-other", ALLOC_ID, "public", List.of())).thenReturn(replacement);
StackResource moved = prior("AWS::EC2::NatGateway", "Nat", NAT_ID, Map.of("NatGatewayId", NAT_ID));
provisioner.provision(moved, mapper.createObjectNode().put("SubnetId", "subnet-other").put("AllocationId", ALLOC_ID), ctx(NAT_ID));
assertEquals("nat-replacement", moved.getPhysicalId());
assertEquals(NAT_ID, provisioner.updateCleanupPhysicalId(moved));
}
@Test
void anAllocatedEipIsKeptAcrossUpdates() {
Address addr = new Address();
addr.setAllocationId(ALLOC_ID);
addr.setPublicIp(PUBLIC_IP);
when(ec2.describeAddresses(REGION, List.of(ALLOC_ID), Map.of())).thenReturn(List.of(addr));
StackResource r = prior("AWS::EC2::EIP", "Eip", PUBLIC_IP, Map.of("AllocationId", ALLOC_ID, "PublicIp", PUBLIC_IP));
provisioner.provision(r, mapper.createObjectNode().put("Domain", "vpc"), ctx(PUBLIC_IP));
verify(ec2, never()).allocateAddress(any());
assertEquals(PUBLIC_IP, r.getPhysicalId());
}
@Test
void anAssociationWithTheSamePairIsKeptAndAnotherSubnetReplacesIt() {
RouteTableAssociation assoc = new RouteTableAssociation();
assoc.setRouteTableAssociationId(ASSOC_ID);
assoc.setRouteTableId(RTB_ID);
assoc.setSubnetId(SUBNET_ID);
RouteTable rt = new RouteTable();
rt.setRouteTableId(RTB_ID);
rt.setAssociations(List.of(assoc));
when(ec2.describeRouteTables(REGION, List.of(), Map.of("association.route-table-association-id", List.of(ASSOC_ID))))
.thenReturn(List.of(rt));
StackResource same = prior("AWS::EC2::SubnetRouteTableAssociation", "Assoc", ASSOC_ID, Map.of("Id", ASSOC_ID));
provisioner.provision(same, mapper.createObjectNode().put("RouteTableId", RTB_ID).put("SubnetId", SUBNET_ID), ctx(ASSOC_ID));
verify(ec2, never()).associateRouteTable(any(), any(), any());
RouteTableAssociation replacement = new RouteTableAssociation();
replacement.setRouteTableAssociationId("rtbassoc-replacement");
when(ec2.associateRouteTable(REGION, RTB_ID, "subnet-other")).thenReturn(replacement);
StackResource moved = prior("AWS::EC2::SubnetRouteTableAssociation", "Assoc", ASSOC_ID, Map.of("Id", ASSOC_ID));
provisioner.provision(moved, mapper.createObjectNode().put("RouteTableId", RTB_ID).put("SubnetId", "subnet-other"), ctx(ASSOC_ID));
assertEquals("rtbassoc-replacement", moved.getPhysicalId());
assertEquals(ASSOC_ID, provisioner.updateCleanupPhysicalId(moved));
provisioner.completeUpdate(moved);
verify(ec2).disassociateRouteTable(REGION, ASSOC_ID);
}
@Test
void aRouteWithTheSameTableAndDestinationChangesItsTargetInPlace() {
Route route = new Route();
route.setDestinationCidrBlock("0.0.0.0/0");
route.setGatewayId(IGW_ID);
RouteTable rt = new RouteTable();
rt.setRouteTableId(RTB_ID);
rt.setRoutes(List.of(route));
when(ec2.describeRouteTables(REGION, List.of(RTB_ID), Map.of())).thenReturn(List.of(rt));
StackResource r = prior("AWS::EC2::Route", "Default", RTB_ID + "|0.0.0.0/0", Map.of("CidrBlock", "0.0.0.0/0"));
ObjectNode props = mapper.createObjectNode().put("RouteTableId", RTB_ID).put("DestinationCidrBlock", "0.0.0.0/0").put("NatGatewayId", NAT_ID);
provisioner.provision(r, props, ctx(RTB_ID + "|0.0.0.0/0"));
verify(ec2).replaceRoute(REGION, RTB_ID, "0.0.0.0/0", null, null, null, NAT_ID, null);
verify(ec2, never()).createRoute(any(), any(), any(), any(), any(), any(), any(), any(), any());
assertEquals(RTB_ID + "|0.0.0.0/0", r.getPhysicalId());
assertTrue(provisioner.rollbackUpdate(r), "the prior target is restored from the snapshot");
verify(ec2).replaceRoute(REGION, RTB_ID, "0.0.0.0/0", null, null, IGW_ID, null, null);
assertFalse(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));
}
@Test
void aRouteWithAChangedDestinationIsANewRouteAndThePriorOneIsOwedToCleanup() {
StackResource r = prior("AWS::EC2::Route", "Default", RTB_ID + "|0.0.0.0/0", Map.of("CidrBlock", "0.0.0.0/0"));
ObjectNode props = mapper.createObjectNode().put("RouteTableId", RTB_ID).put("DestinationCidrBlock", "10.1.0.0/16").put("GatewayId", IGW_ID);
provisioner.provision(r, props, ctx(RTB_ID + "|0.0.0.0/0"));
verify(ec2).createRoute(REGION, RTB_ID, "10.1.0.0/16", null, null, IGW_ID, null, null, null);
assertEquals(RTB_ID + "|10.1.0.0/16", r.getPhysicalId());
assertEquals(RTB_ID + "|0.0.0.0/0", provisioner.updateCleanupPhysicalId(r));
provisioner.completeUpdate(r);
verify(ec2).deleteRoute(REGION, RTB_ID, "0.0.0.0/0", null, null);
}
/** The EC2 Tag model has no equals, so tag lists are compared as key=value pairs. */
private static List<String> pairs(List<Tag> tags) {
return tags.stream().map(t -> t.getKey() + "=" + t.getValue()).toList();
}
@SuppressWarnings("unchecked")
private List<String> tagsWritten(String resourceId) {
ArgumentCaptor<List<Tag>> tags = ArgumentCaptor.forClass(List.class);
verify(ec2).createTags(eq(REGION), eq(List.of(resourceId)), tags.capture());
return pairs(tags.getValue());
}
private static ObjectNode withTags(ObjectNode props, String... keyValues) {
var tags = props.putArray("Tags");
for (int i = 0; i + 1 < keyValues.length; i += 2) {
tags.addObject().put("Key", keyValues[i]).put("Value", keyValues[i + 1]);
}
return props;
}
@Test
void tagsAreWrittenOnCreateForEveryTaggableType() {
when(ec2.createSubnet(eq(REGION), eq(VPC_ID), eq("10.0.1.0/24"), isNull())).thenReturn(subnet());
RouteTable rt = new RouteTable();
rt.setRouteTableId(RTB_ID);
when(ec2.createRouteTable(REGION, VPC_ID)).thenReturn(rt);
InternetGateway igw = new InternetGateway();
igw.setInternetGatewayId(IGW_ID);
when(ec2.createInternetGateway(REGION)).thenReturn(igw);
Address addr = new Address();
addr.setAllocationId(ALLOC_ID);
addr.setPublicIp(PUBLIC_IP);
when(ec2.allocateAddress(REGION)).thenReturn(addr);
provisioner.provision(resource("AWS::EC2::Subnet", "Subnet"),
withTags(mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24"), "Name", "public"), ctx());
provisioner.provision(resource("AWS::EC2::RouteTable", "Rtb"),
withTags(mapper.createObjectNode().put("VpcId", VPC_ID), "Name", "public-rt"), ctx());
provisioner.provision(resource("AWS::EC2::InternetGateway", "Igw"), withTags(mapper.createObjectNode(), "Name", "igw"), ctx());
provisioner.provision(resource("AWS::EC2::EIP", "Eip"), withTags(mapper.createObjectNode(), "Name", "nat-ip"), ctx());
assertEquals(List.of("Name=public"), tagsWritten(SUBNET_ID));
assertEquals(List.of("Name=public-rt"), tagsWritten(RTB_ID));
assertEquals(List.of("Name=igw"), tagsWritten(IGW_ID));
assertEquals(List.of("Name=nat-ip"), tagsWritten(ALLOC_ID));
verify(ec2, never()).deleteTags(any(), any(), any());
}
@Test
void aPrivateNatGatewayNeedsNoAllocationAndAPublicOneRequiresIt() {
NatGateway nat = new NatGateway();
nat.setNatGatewayId(NAT_ID);
when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), isNull(), eq("private"), any())).thenReturn(nat);
StackResource r = resource("AWS::EC2::NatGateway", "Nat");
provisioner.provision(r, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("ConnectivityType", "private"), ctx());
assertEquals(NAT_ID, r.getPhysicalId());
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(resource("AWS::EC2::NatGateway", "Nat2"),
mapper.createObjectNode().put("SubnetId", SUBNET_ID), ctx()));
assertEquals("ValidationError", e.getErrorCode());
AwsException e2 = assertThrows(AwsException.class, () -> provisioner.provision(resource("AWS::EC2::NatGateway", "Nat3"),
mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("ConnectivityType", "private").put("AllocationId", ALLOC_ID), ctx()));
assertEquals("ValidationError", e2.getErrorCode());
}
@Test
void aNatGatewayWhoseConnectivityTypeChangedIsReplaced() {
NatGateway nat = new NatGateway();
nat.setNatGatewayId(NAT_ID);
nat.setSubnetId(SUBNET_ID);
nat.setAllocationId(ALLOC_ID);
nat.setConnectivityType("public");
when(ec2.describeNatGateways(REGION, List.of(NAT_ID), Map.of())).thenReturn(List.of(nat));
NatGateway replacement = new NatGateway();
replacement.setNatGatewayId("nat-private");
when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), isNull(), eq("private"), any())).thenReturn(replacement);
StackResource r = prior("AWS::EC2::NatGateway", "Nat", NAT_ID, Map.of("NatGatewayId", NAT_ID));
provisioner.provision(r, mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("ConnectivityType", "private"), ctx(NAT_ID));
assertEquals("nat-private", r.getPhysicalId());
assertEquals(NAT_ID, provisioner.updateCleanupPhysicalId(r));
}
@Test
void natGatewayTagsGoThroughItsCreateCall() {
NatGateway nat = new NatGateway();
nat.setNatGatewayId(NAT_ID);
when(ec2.createNatGateway(eq(REGION), eq(SUBNET_ID), eq(ALLOC_ID), eq("public"), any())).thenReturn(nat);
provisioner.provision(resource("AWS::EC2::NatGateway", "Nat"),
withTags(mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID), "Name", "nat"), ctx());
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Tag>> tags = ArgumentCaptor.forClass(List.class);
verify(ec2).createNatGateway(eq(REGION), eq(SUBNET_ID), eq(ALLOC_ID), eq("public"), tags.capture());
assertEquals(List.of("Name=nat"), pairs(tags.getValue()));
verify(ec2, never()).createTags(any(), any(), any());
}
@Test
void aReusedSubnetDropsTheTagKeysTheTemplateRemovedAndWritesTheRest() {
Subnet current = subnet();
current.setTags(List.of(new Tag("Name", "old"), new Tag("team", "net")));
when(ec2.describeSubnets(REGION, List.of(SUBNET_ID), Map.of())).thenReturn(List.of(current));
StackResource r = prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of("SubnetId", SUBNET_ID));
ObjectNode props = withTags(mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24"), "Name", "new");
provisioner.provision(r, props, ctx(SUBNET_ID));
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Tag>> removed = ArgumentCaptor.forClass(List.class);
verify(ec2).deleteTags(eq(REGION), eq(List.of(SUBNET_ID)), removed.capture());
assertEquals(List.of("team=null"), pairs(removed.getValue()));
assertEquals(List.of("Name=new"), tagsWritten(SUBNET_ID));
}
@Test
void aTagChangeOnAReusedEntityIsRolledBackToThePriorTags() {
RouteTable rt = new RouteTable();
rt.setRouteTableId(RTB_ID);
rt.setVpcId(VPC_ID);
rt.setTags(List.of(new Tag("Name", "old"), new Tag("team", "net")));
when(ec2.describeRouteTables(REGION, List.of(RTB_ID), Map.of())).thenReturn(List.of(rt));
StackResource r = prior("AWS::EC2::RouteTable", "Rtb", RTB_ID, Map.of("RouteTableId", RTB_ID));
provisioner.provision(r, withTags(mapper.createObjectNode().put("VpcId", VPC_ID), "Name", "new", "env", "test"), ctx(RTB_ID));
assertTrue(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR), "the prior tags are snapshotted");
assertTrue(provisioner.rollbackUpdate(r));
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Tag>> removed = ArgumentCaptor.forClass(List.class);
verify(ec2, org.mockito.Mockito.times(2)).deleteTags(eq(REGION), eq(List.of(RTB_ID)), removed.capture());
assertEquals(List.of("env=null"), pairs(removed.getAllValues().get(1)), "the key the update added is removed");
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Tag>> written = ArgumentCaptor.forClass(List.class);
verify(ec2, org.mockito.Mockito.times(2)).createTags(eq(REGION), eq(List.of(RTB_ID)), written.capture());
assertEquals(List.of("Name=old", "team=net"), pairs(written.getAllValues().get(1)), "the prior tags are written back");
assertFalse(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));
}
@Test
void anUnchangedReuseLeavesNoSnapshotAndRollsBackAsComplete() {
RouteTable rt = new RouteTable();
rt.setRouteTableId(RTB_ID);
rt.setVpcId(VPC_ID);
rt.setTags(List.of(new Tag("Name", "same")));
when(ec2.describeRouteTables(REGION, List.of(RTB_ID), Map.of())).thenReturn(List.of(rt));
StackResource r = prior("AWS::EC2::RouteTable", "Rtb", RTB_ID, Map.of("RouteTableId", RTB_ID));
provisioner.provision(r, withTags(mapper.createObjectNode().put("VpcId", VPC_ID), "Name", "same"), ctx(RTB_ID));
assertFalse(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));
assertTrue(provisioner.rollbackUpdate(r));
verify(ec2, never()).deleteTags(any(), any(), any());
}
@Test
void completingOrClearingAnUpdateDropsTheSnapshot() {
StackResource r = prior("AWS::EC2::RouteTable", "Rtb", RTB_ID, Map.of(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR, "{}"));
provisioner.completeUpdate(r);
assertFalse(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));
r.getAttributes().put(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR, "{}");
provisioner.clearUpdate(r);
assertFalse(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));
}
@Test
void aTemplateWithoutTagsLeavesExistingTagsAlone() {
Subnet current = subnet();
current.setTags(List.of(new Tag("Name", "kept")));
when(ec2.describeSubnets(REGION, List.of(SUBNET_ID), Map.of())).thenReturn(List.of(current));
StackResource r = prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of("SubnetId", SUBNET_ID));
provisioner.provision(r, mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24"), ctx(SUBNET_ID));
verify(ec2, never()).deleteTags(any(), any(), any());
verify(ec2, never()).createTags(any(), any(), any());
}
@Test
void requiredPropertiesAreValidatedBeforeAnyServiceCall() {
record Case(String type, ObjectNode props, String expected) { }
List<Case> cases = List.of(
new Case("AWS::EC2::Subnet", mapper.createObjectNode().put("CidrBlock", "10.0.1.0/24"), "AWS::EC2::Subnet requires VpcId"),
new Case("AWS::EC2::RouteTable", mapper.createObjectNode(), "AWS::EC2::RouteTable requires VpcId"),
new Case("AWS::EC2::SubnetRouteTableAssociation", mapper.createObjectNode().put("SubnetId", SUBNET_ID),
"AWS::EC2::SubnetRouteTableAssociation requires RouteTableId"),
new Case("AWS::EC2::SubnetRouteTableAssociation", mapper.createObjectNode().put("RouteTableId", RTB_ID),
"AWS::EC2::SubnetRouteTableAssociation requires SubnetId"),
new Case("AWS::EC2::NatGateway", mapper.createObjectNode().put("AllocationId", ALLOC_ID), "AWS::EC2::NatGateway requires SubnetId"),
new Case("AWS::EC2::Route", mapper.createObjectNode().put("DestinationCidrBlock", "0.0.0.0/0"), "AWS::EC2::Route requires RouteTableId"),
new Case("AWS::EC2::Route", mapper.createObjectNode().put("RouteTableId", RTB_ID),
"AWS::EC2::Route requires exactly one of DestinationCidrBlock, DestinationIpv6CidrBlock or DestinationPrefixListId"),
new Case("AWS::EC2::Route", mapper.createObjectNode().put("RouteTableId", RTB_ID).put("DestinationCidrBlock", "0.0.0.0/0").put("DestinationIpv6CidrBlock", "::/0"),
"AWS::EC2::Route requires exactly one of DestinationCidrBlock, DestinationIpv6CidrBlock or DestinationPrefixListId"));
for (Case c : cases) {
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(resource(c.type(), "R"), c.props(), ctx()), c.expected());
assertEquals("ValidationError", e.getErrorCode());
assertEquals(c.expected(), e.getMessage());
}
verify(ec2, never()).createSubnet(any(), any(), any(), any());
verify(ec2, never()).createRouteTable(any(), any());
verify(ec2, never()).associateRouteTable(any(), any(), any());
verify(ec2, never()).createRoute(any(), any(), any(), any(), any(), any(), any(), any(), any());
verify(ec2, never()).createNatGateway(any(), any(), any(), any(), any());
}
@Test
void aNonCanonicalIpv4DestinationIsKeyedByItsCanonicalFormAndReusedAsSuch() {
StackResource created = resource("AWS::EC2::Route", "Default");
provisioner.provision(created, mapper.createObjectNode().put("RouteTableId", RTB_ID)
.put("DestinationCidrBlock", "10.40.0.18/24").put("GatewayId", IGW_ID), ctx());
assertEquals(RTB_ID + "|10.40.0.0/24", created.getPhysicalId(), "the id carries the canonical CIDR the service stores");
assertEquals("10.40.0.0/24", created.getAttributes().get("CidrBlock"));
verify(ec2).createRoute(REGION, RTB_ID, "10.40.0.18/24", null, null, IGW_ID, null, null, null);
Route stored = new Route();
stored.setDestinationCidrBlock("10.40.0.0/24");
stored.setGatewayId(IGW_ID);
RouteTable rt = new RouteTable();
rt.setRouteTableId(RTB_ID);
rt.setRoutes(List.of(stored));
when(ec2.describeRouteTables(REGION, List.of(RTB_ID), Map.of())).thenReturn(List.of(rt));
StackResource updated = prior("AWS::EC2::Route", "Default", RTB_ID + "|10.40.0.0/24", Map.of("CidrBlock", "10.40.0.0/24"));
provisioner.provision(updated, mapper.createObjectNode().put("RouteTableId", RTB_ID)
.put("DestinationCidrBlock", "10.40.0.18/24").put("GatewayId", IGW_ID), ctx(RTB_ID + "|10.40.0.0/24"));
verify(ec2).replaceRoute(REGION, RTB_ID, "10.40.0.18/24", null, null, IGW_ID, null, null);
verify(ec2, org.mockito.Mockito.times(1)).createRoute(any(), any(), any(), any(), any(), any(), any(), any(), any());
assertEquals(RTB_ID + "|10.40.0.0/24", updated.getPhysicalId());
}
@Test
void aFailedStepAfterACreateDeletesWhatWasJustCreatedAndPropagates() {
when(ec2.createSubnet(eq(REGION), eq(VPC_ID), eq("10.0.1.0/24"), isNull())).thenReturn(subnet());
RouteTable rt = new RouteTable();
rt.setRouteTableId(RTB_ID);
when(ec2.createRouteTable(REGION, VPC_ID)).thenReturn(rt);
InternetGateway igw = new InternetGateway();
igw.setInternetGatewayId(IGW_ID);
when(ec2.createInternetGateway(REGION)).thenReturn(igw);
Address addr = new Address();
addr.setAllocationId(ALLOC_ID);
addr.setPublicIp(PUBLIC_IP);
when(ec2.allocateAddress(REGION)).thenReturn(addr);
doThrow(new AwsException("TagLimitExceeded", "too many tags", 400)).when(ec2).createTags(any(), any(), any());
for (var attempt : List.of(
Map.entry("AWS::EC2::Subnet", withTags(mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24"), "k", "v")),
Map.entry("AWS::EC2::RouteTable", withTags(mapper.createObjectNode().put("VpcId", VPC_ID), "k", "v")),
Map.entry("AWS::EC2::InternetGateway", withTags(mapper.createObjectNode(), "k", "v")),
Map.entry("AWS::EC2::EIP", withTags(mapper.createObjectNode(), "k", "v")))) {
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(resource(attempt.getKey(), "R"), attempt.getValue(), ctx()), attempt.getKey());
assertEquals("TagLimitExceeded", e.getErrorCode());
}
verify(ec2).deleteSubnet(REGION, SUBNET_ID);
verify(ec2).deleteRouteTable(REGION, RTB_ID);
verify(ec2).deleteInternetGateway(REGION, IGW_ID);
verify(ec2).releaseAddress(REGION, ALLOC_ID);
}
@Test
void aSuccessfulCreateLeavesNoRollbackOwnedMarker() {
when(ec2.createSubnet(eq(REGION), eq(VPC_ID), eq("10.0.1.0/24"), isNull())).thenReturn(subnet());
StackResource r = resource("AWS::EC2::Subnet", "Subnet");
provisioner.provision(r, withTags(mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24"), "k", "v"), ctx());
assertFalse(r.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR));
assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
}
@Test
void aFailedUndoOfACreateLeavesTheEntityRollbackOwnedAndReportsTheReason() {
when(ec2.createSubnet(eq(REGION), eq(VPC_ID), eq("10.0.1.0/24"), isNull())).thenReturn(subnet());
doThrow(new AwsException("TagLimitExceeded", "too many tags", 400)).when(ec2).createTags(any(), any(), any());
doThrow(new AwsException("DependencyViolation", "in use", 400)).when(ec2).deleteSubnet(REGION, SUBNET_ID);
StackResource r = resource("AWS::EC2::Subnet", "Subnet");
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r,
withTags(mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24"), "k", "v"), ctx()));
assertEquals("TagLimitExceeded", e.getErrorCode());
assertEquals(1, e.getSuppressed().length);
assertEquals(SUBNET_ID, r.getPhysicalId(), "the id stays so the engine's rollback can delete it");
assertEquals("true", r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
assertTrue(r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR).contains("Could not remove " + SUBNET_ID));
}
@Test
void aReplacementThatCouldNotBeRemovedAfterAFailedStepIsOwedToTheNextCleanup() {
Subnet current = subnet();
current.setCidrBlock("10.0.1.0/24");
when(ec2.describeSubnets(REGION, List.of(SUBNET_ID), Map.of())).thenReturn(List.of(current));
Subnet replacement = subnet();
replacement.setSubnetId("subnet-replacement");
when(ec2.createSubnet(REGION, VPC_ID, "10.0.2.0/24", "us-east-1a")).thenReturn(replacement);
doThrow(new AwsException("TagLimitExceeded", "too many tags", 400)).when(ec2).createTags(any(), any(), any());
doThrow(new AwsException("DependencyViolation", "in use", 400)).when(ec2).deleteSubnet(REGION, "subnet-replacement");
StackResource r = prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of("SubnetId", SUBNET_ID));
ObjectNode props = withTags(mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.2.0/24").put("AvailabilityZone", "us-east-1a"), "k", "v");
assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx(SUBNET_ID)));
assertTrue(r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR).contains("Could not remove subnet-replacement"));
assertTrue(provisioner.hasReplacementUpdate(r), "the replacement is listed in the attempt's cleanup record");
// The engine restores the previous resource and carries the record across (mergeFailedUpdateResourceTracking).
StackResource previous = prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of("SubnetId", SUBNET_ID));
ReplacementCleanup.mergeDisplaced(previous, r);
assertEquals("subnet-replacement", provisioner.updateCleanupPhysicalId(previous), "the replacement stays owed a delete");
provisioner.completeUpdate(previous);
verify(ec2, org.mockito.Mockito.times(2)).deleteSubnet(REGION, "subnet-replacement");
}
@Test
void aFreshCreateThatCouldNotBeRemovedRecordsNoCleanupEntry() {
when(ec2.createSubnet(eq(REGION), eq(VPC_ID), eq("10.0.1.0/24"), isNull())).thenReturn(subnet());
doThrow(new AwsException("TagLimitExceeded", "too many tags", 400)).when(ec2).createTags(any(), any(), any());
doThrow(new AwsException("DependencyViolation", "in use", 400)).when(ec2).deleteSubnet(REGION, SUBNET_ID);
StackResource r = resource("AWS::EC2::Subnet", "Subnet");
assertThrows(AwsException.class, () -> provisioner.provision(r,
withTags(mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24"), "k", "v"), ctx()));
assertEquals("true", r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR), "the engine's create rollback owns it");
assertFalse(provisioner.hasReplacementUpdate(r));
}
@Test
void aFailedRestoreOfAReusedEntityKeepsTheSnapshotAndReportsTheReason() {
RouteTable rt = new RouteTable();
rt.setRouteTableId(RTB_ID);
rt.setVpcId(VPC_ID);
rt.setTags(List.of(new Tag("Name", "old")));
when(ec2.describeRouteTables(REGION, List.of(RTB_ID), Map.of())).thenReturn(List.of(rt));
// Two distinct instances: the attempt's failure and the restore's, since a throwable cannot suppress itself.
doThrow(new AwsException("TagLimitExceeded", "too many tags", 400))
.doThrow(new AwsException("TagLimitExceeded", "still too many tags", 400))
.when(ec2).createTags(eq(REGION), eq(List.of(RTB_ID)), any());
StackResource r = prior("AWS::EC2::RouteTable", "Rtb", RTB_ID, Map.of("RouteTableId", RTB_ID));
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r,
withTags(mapper.createObjectNode().put("VpcId", VPC_ID), "Name", "new"), ctx(RTB_ID)));
assertEquals("TagLimitExceeded", e.getErrorCode());
assertEquals(1, e.getSuppressed().length);
assertTrue(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR), "the snapshot is kept");
assertTrue(r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR).contains("Could not restore " + RTB_ID));
verify(ec2, never()).deleteRouteTable(any(), any());
}
@Test
void aFailureMidWayThroughAnInPlaceTagChangePutsThePriorTagsBack() {
RouteTable rt = new RouteTable();
rt.setRouteTableId(RTB_ID);
rt.setVpcId(VPC_ID);
rt.setTags(List.of(new Tag("Name", "old"), new Tag("team", "net")));
when(ec2.describeRouteTables(REGION, List.of(RTB_ID), Map.of())).thenReturn(List.of(rt));
// deleteTags (of "team") succeeds, then the createTags of the new set throws; the restore's createTags succeeds.
doThrow(new AwsException("TagLimitExceeded", "too many tags", 400)).doNothing()
.when(ec2).createTags(eq(REGION), eq(List.of(RTB_ID)), any());
StackResource r = prior("AWS::EC2::RouteTable", "Rtb", RTB_ID, Map.of("RouteTableId", RTB_ID));
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r,
withTags(mapper.createObjectNode().put("VpcId", VPC_ID), "Name", "new", "env", "test"), ctx(RTB_ID)));
assertEquals("TagLimitExceeded", e.getErrorCode());
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Tag>> written = ArgumentCaptor.forClass(List.class);
verify(ec2, org.mockito.Mockito.times(2)).createTags(eq(REGION), eq(List.of(RTB_ID)), written.capture());
assertEquals(List.of("Name=old", "team=net"), pairs(written.getAllValues().get(1)), "the prior tags are put back");
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Tag>> removed = ArgumentCaptor.forClass(List.class);
verify(ec2, org.mockito.Mockito.times(2)).deleteTags(eq(REGION), eq(List.of(RTB_ID)), removed.capture());
assertEquals(List.of("env=null"), pairs(removed.getAllValues().get(1)), "the key the failed update added is removed again");
assertFalse(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));
assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR), "a successful restore reports nothing");
verify(ec2, never()).deleteRouteTable(any(), any());
}
@Test
void aFailedSubnetAttributeChangeAfterTagsPutsTheTagsBack() {
Subnet current = subnet();
current.setTags(List.of(new Tag("Name", "old")));
when(ec2.describeSubnets(REGION, List.of(SUBNET_ID), Map.of())).thenReturn(List.of(current));
doThrow(new AwsException("InvalidParameterValue", "nope", 400))
.when(ec2).modifySubnetAttribute(REGION, SUBNET_ID, "mapPublicIpOnLaunch", "true");
StackResource r = prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of("SubnetId", SUBNET_ID));
ObjectNode props = withTags(mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24")
.put("MapPublicIpOnLaunch", true), "Name", "new");
assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx(SUBNET_ID)));
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Tag>> written = ArgumentCaptor.forClass(List.class);
verify(ec2, org.mockito.Mockito.times(2)).createTags(eq(REGION), eq(List.of(SUBNET_ID)), written.capture());
assertEquals(List.of("Name=old"), pairs(written.getAllValues().get(1)));
// the snapshot recorded the prior value before the flip was attempted, so the restore writes it back
verify(ec2).modifySubnetAttribute(REGION, SUBNET_ID, "mapPublicIpOnLaunch", "false");
verify(ec2, org.mockito.Mockito.times(2)).modifySubnetAttribute(any(), any(), any(), any());
verify(ec2, never()).deleteSubnet(any(), any());
}
@Test
void aFailedRouteRetargetPutsThePriorTargetBack() {
Route route = new Route();
route.setDestinationCidrBlock("0.0.0.0/0");
route.setGatewayId(IGW_ID);
RouteTable rt = new RouteTable();
rt.setRouteTableId(RTB_ID);
rt.setRoutes(List.of(route));
when(ec2.describeRouteTables(REGION, List.of(RTB_ID), Map.of())).thenReturn(List.of(rt));
doThrow(new AwsException("InvalidNatGatewayID.NotFound", "gone", 400)).doNothing()
.when(ec2).replaceRoute(eq(REGION), eq(RTB_ID), eq("0.0.0.0/0"), isNull(), isNull(), any(), any(), any());
StackResource r = prior("AWS::EC2::Route", "Default", RTB_ID + "|0.0.0.0/0", Map.of("CidrBlock", "0.0.0.0/0"));
assertThrows(AwsException.class, () -> provisioner.provision(r, mapper.createObjectNode().put("RouteTableId", RTB_ID)
.put("DestinationCidrBlock", "0.0.0.0/0").put("NatGatewayId", NAT_ID), ctx(RTB_ID + "|0.0.0.0/0")));
verify(ec2).replaceRoute(REGION, RTB_ID, "0.0.0.0/0", null, null, null, NAT_ID, null);
verify(ec2).replaceRoute(REGION, RTB_ID, "0.0.0.0/0", null, null, IGW_ID, null, null);
assertFalse(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));
}
@Test
void aFailedNatGatewayTagChangePutsThePriorTagsBack() {
NatGateway nat = new NatGateway();
nat.setNatGatewayId(NAT_ID);
nat.setSubnetId(SUBNET_ID);
nat.setAllocationId(ALLOC_ID);
nat.setTags(List.of(new Tag("Name", "old")));
when(ec2.describeNatGateways(REGION, List.of(NAT_ID), Map.of())).thenReturn(List.of(nat));
doThrow(new AwsException("TagLimitExceeded", "too many tags", 400)).doNothing()
.when(ec2).createTags(eq(REGION), eq(List.of(NAT_ID)), any());
StackResource r = prior("AWS::EC2::NatGateway", "Nat", NAT_ID, Map.of("NatGatewayId", NAT_ID));
assertThrows(AwsException.class, () -> provisioner.provision(r,
withTags(mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID), "Name", "new"), ctx(NAT_ID)));
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Tag>> written = ArgumentCaptor.forClass(List.class);
verify(ec2, org.mockito.Mockito.times(2)).createTags(eq(REGION), eq(List.of(NAT_ID)), written.capture());
assertEquals(List.of("Name=old"), pairs(written.getAllValues().get(1)));
verify(ec2, never()).deleteNatGateway(any(), any());
}
@Test
void aFailedStepOnAReusedEntityLeavesItAlone() {
when(ec2.describeSubnets(REGION, List.of(SUBNET_ID), Map.of())).thenReturn(List.of(subnet()));
doThrow(new AwsException("TagLimitExceeded", "too many tags", 400)).when(ec2).createTags(any(), any(), any());
StackResource r = prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of("SubnetId", SUBNET_ID));
assertThrows(AwsException.class, () -> provisioner.provision(r,
withTags(mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24"), "k", "v"), ctx(SUBNET_ID)));
verify(ec2, never()).deleteSubnet(any(), any());
}
@Test
void unknownTypeIsRejected() {
StackResource r = resource("AWS::EC2::SecurityGroup", "Sg");
assertThrows(IllegalStateException.class, () -> provisioner.provision(r, mapper.createObjectNode(), ctx()));
}
}
@@ -0,0 +1,84 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** The cleanup record's orphan handling in isolation: what a provisioner records and what the engine's merge carries. */
class ReplacementCleanupTest {
private static StackResource resource(String physicalId) {
StackResource r = new StackResource();
r.setLogicalId("Subnet");
r.setResourceType("AWS::EC2::Subnet");
r.setPhysicalId(physicalId);
r.setAttributes(new HashMap<>());
return r;
}
@Test
void anOrphanIsOwedADeleteAndLeavesTheRecordOnceDeleted() {
StackResource r = resource("subnet-prior");
List<String> deleted = new ArrayList<>();
ReplacementCleanup.recordOrphan(r, "subnet-replacement", "AWS::EC2::Subnet", "us-east-1");
assertTrue(ReplacementCleanup.hasReplacement(r));
assertEquals("subnet-replacement", ReplacementCleanup.cleanupPhysicalId(r));
UpdateCleanupResult result = ReplacementCleanup.complete(r, (type, id, region) -> deleted.add(type + ":" + id + ":" + region));
assertEquals(List.of("AWS::EC2::Subnet:subnet-replacement:us-east-1"), deleted);
assertTrue(result.complete());
assertFalse(ReplacementCleanup.hasReplacement(r));
}
@Test
void anOrphanIsNeverRetained() {
StackResource r = resource("subnet-prior");
r.setUpdateReplacePolicy("Retain");
ReplacementCleanup.recordOrphan(r, "subnet-replacement", "AWS::EC2::Subnet", "us-east-1");
assertEquals("subnet-replacement", ReplacementCleanup.cleanupPhysicalId(r), "Retain keeps what a committed replacement displaced, not a failed update's leftovers");
}
@Test
void mergingCarriesUnknownOrphansWithTheirAttemptsAndSkipsKnownOrOwnIds() {
// The attempt's own id is left out of the record on purpose (complete/cleanupPhysicalId skip
// it), which is why the engine merges the record onto the restored previous resource.
StackResource attempted = resource("subnet-attempt");
ReplacementCleanup.recordOrphan(attempted, "subnet-replacement", "AWS::EC2::Subnet", "us-east-1");
ReplacementCleanup.recordOrphan(attempted, "subnet-old-orphan", "AWS::EC2::Subnet", "us-east-1");
// one failed attempt already counted on both
ReplacementCleanup.complete(attempted, (type, id, region) -> { throw new IllegalStateException("still in use"); });
StackResource previous = resource("subnet-prior");
ReplacementCleanup.recordOrphan(previous, "subnet-old-orphan", "AWS::EC2::Subnet", "us-east-1");
ReplacementCleanup.mergeDisplaced(previous, attempted);
String record = previous.getAttributes().get(CfnRollback.REPLACEMENT_CLEANUP_ATTR);
assertTrue(record.indexOf("subnet-old-orphan") == record.lastIndexOf("subnet-old-orphan"), "the known orphan is listed once: " + record);
assertTrue(record.contains("\"physicalId\":\"subnet-replacement\",\"resourceType\":\"AWS::EC2::Subnet\",\"region\":\"us-east-1\",\"retainable\":false,\"cleanupAttempts\":1"),
"the new orphan keeps its attempt count: " + record);
List<String> owed = new ArrayList<>();
ReplacementCleanup.complete(previous, (type, id, region) -> owed.add(id));
assertEquals(List.of("subnet-old-orphan", "subnet-replacement"), owed);
assertFalse(ReplacementCleanup.hasReplacement(previous));
}
@Test
void mergingNothingLeavesTheTargetUntouched() {
StackResource previous = resource("subnet-prior");
ReplacementCleanup.mergeDisplaced(previous, resource("subnet-replacement"));
assertNull(previous.getAttributes().get(CfnRollback.REPLACEMENT_CLEANUP_ATTR));
}
}