diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java index e84607432f..933d42c142 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java @@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.cloudfront.model.Distribution; import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig; import io.github.hectorvent.floci.services.cloudfront.model.Origin; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.ReplacementCleanup; import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback; import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry; import io.github.hectorvent.floci.services.cloudformation.provisioners.ProvisionContext; @@ -205,15 +206,8 @@ public class CloudFormationResourceProvisioner { "AWS::CloudFront::Distribution", "AWS::DynamoDB::GlobalTable", "AWS::DynamoDB::Table", - "AWS::EC2::EIP", "AWS::EC2::Instance", - "AWS::EC2::InternetGateway", - "AWS::EC2::NatGateway", - "AWS::EC2::Route", - "AWS::EC2::RouteTable", "AWS::EC2::SecurityGroup", - "AWS::EC2::Subnet", - "AWS::EC2::SubnetRouteTableAssociation", "AWS::EKS::Cluster", "AWS::EKS::Nodegroup", "AWS::Events::EventBus", @@ -420,15 +414,7 @@ public class CloudFormationResourceProvisioner { // EC2 networking. These delegate to Ec2Service so the resources actually exist // (describe-subnets, ELBv2, etc. can find them) instead of being stubbed with a // fake physical id. Topological ordering guarantees parents are provisioned first. - case "AWS::EC2::Subnet" -> provisionSubnet(resource, properties, engine, region); case "AWS::EC2::SecurityGroup" -> provisionSecurityGroup(resource, properties, engine, region, stackName); - case "AWS::EC2::InternetGateway" -> provisionInternetGateway(resource, region); - case "AWS::EC2::RouteTable" -> provisionRouteTable(resource, properties, engine, region); - case "AWS::EC2::SubnetRouteTableAssociation" -> - provisionSubnetRouteTableAssociation(resource, properties, engine, region); - case "AWS::EC2::Route" -> provisionRoute(resource, properties, engine, region); - case "AWS::EC2::NatGateway" -> provisionNatGateway(resource, properties, engine, region); - case "AWS::EC2::EIP" -> provisionEip(resource, region); case "AWS::EC2::Instance" -> provisionEc2Instance(resource, properties, engine, region); // RDS. DBInstance/DBCluster start real RDS containers (same as the direct API). case "AWS::RDS::DBSubnetGroup" -> provisionDbSubnetGroup(resource, properties, engine, stackName, region); @@ -730,21 +716,6 @@ public class CloudFormationResourceProvisioner { // Ref/exports resolve to a real vpc-/subnet-/... id rather than a stub. - private void provisionSubnet(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, String region) { - String vpcId = resolveOptional(props, "VpcId", engine); - String cidr = resolveOptional(props, "CidrBlock", engine); - String az = resolveOptional(props, "AvailabilityZone", engine); - String mapPublicIpOnLaunch = resolveOptional(props, "MapPublicIpOnLaunch", engine); - var subnet = ec2Service.createSubnet(region, vpcId, cidr, az); - if (mapPublicIpOnLaunch != null) { - ec2Service.modifySubnetAttribute(region, subnet.getSubnetId(), "mapPublicIpOnLaunch", mapPublicIpOnLaunch); - } - r.setPhysicalId(subnet.getSubnetId()); - r.getAttributes().put("SubnetId", subnet.getSubnetId()); - r.getAttributes().put("VpcId", subnet.getVpcId()); - r.getAttributes().put("AvailabilityZone", subnet.getAvailabilityZone()); - } - private void provisionSecurityGroup(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, String region, String stackName) { String groupName = resolveOptional(props, "GroupName", engine); @@ -781,59 +752,6 @@ public class CloudFormationResourceProvisioner { } } - private void provisionInternetGateway(StackResource r, String region) { - var igw = ec2Service.createInternetGateway(region); - r.setPhysicalId(igw.getInternetGatewayId()); - r.getAttributes().put("InternetGatewayId", igw.getInternetGatewayId()); - } - - private void provisionRouteTable(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, String region) { - String vpcId = resolveOptional(props, "VpcId", engine); - var rt = ec2Service.createRouteTable(region, vpcId); - r.setPhysicalId(rt.getRouteTableId()); - r.getAttributes().put("RouteTableId", rt.getRouteTableId()); - } - - private void provisionSubnetRouteTableAssociation(StackResource r, JsonNode props, - CloudFormationTemplateEngine engine, String region) { - String routeTableId = resolveOptional(props, "RouteTableId", engine); - String subnetId = resolveOptional(props, "SubnetId", engine); - var assoc = ec2Service.associateRouteTable(region, routeTableId, subnetId); - r.setPhysicalId(assoc.getRouteTableAssociationId()); - r.getAttributes().put("Id", assoc.getRouteTableAssociationId()); - } - - private void provisionRoute(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, String region) { - String routeTableId = resolveOptional(props, "RouteTableId", engine); - String destinationCidr = resolveOptional(props, "DestinationCidrBlock", engine); - String destinationIpv6Cidr = resolveOptional(props, "DestinationIpv6CidrBlock", engine); - String destinationPrefixListId = resolveOptional(props, "DestinationPrefixListId", engine); - String gatewayId = resolveOptional(props, "GatewayId", engine); - String natGatewayId = resolveOptional(props, "NatGatewayId", engine); - String egressOnlyInternetGatewayId = resolveOptional(props, "EgressOnlyInternetGatewayId", engine); - String vpcPeeringConnectionId = resolveOptional(props, "VpcPeeringConnectionId", engine); - ec2Service.createRoute(region, routeTableId, destinationCidr, destinationIpv6Cidr, - destinationPrefixListId, gatewayId, natGatewayId, egressOnlyInternetGatewayId, - vpcPeeringConnectionId); - r.setPhysicalId(r.getLogicalId() + "-" + UUID.randomUUID().toString().substring(0, 8)); - } - - private void provisionNatGateway(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, String region) { - String subnetId = resolveOptional(props, "SubnetId", engine); - String allocationId = resolveOptional(props, "AllocationId", engine); - var nat = ec2Service.createNatGateway(region, subnetId, allocationId, "public", List.of()); - r.setPhysicalId(nat.getNatGatewayId()); - r.getAttributes().put("NatGatewayId", nat.getNatGatewayId()); - } - - private void provisionEip(StackResource r, String region) { - var addr = ec2Service.allocateAddress(region); - // Ref on AWS::EC2::EIP returns the public IP; AllocationId is exposed via Fn::GetAtt. - r.setPhysicalId(addr.getPublicIp()); - r.getAttributes().put("AllocationId", addr.getAllocationId()); - r.getAttributes().put("PublicIp", addr.getPublicIp()); - } - // ── CloudWatch Logs ───────────────────────────────────────────────────────── /** @@ -5456,6 +5374,9 @@ public class CloudFormationResourceProvisioner { * attributes must not overwrite the committed resource state. */ void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) { + // Any provisioner using ReplacementCleanup: an entity the failed attempt created and could + // not remove is owed to the next cleanup, which runs on the restored resource. + ReplacementCleanup.mergeDisplaced(previous, attempted); if (!"AWS::ApiGatewayV2::Api".equals(previous.getResourceType()) || !Objects.equals(previous.getResourceType(), attempted.getResourceType())) { return; diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java new file mode 100644 index 0000000000..70823677cf --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java @@ -0,0 +1,630 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.CidrCanonicalizer; +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 jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Supplier; + +/** + * CloudFormation provisioning for the EC2 networking types: {@code AWS::EC2::Subnet}, + * {@code InternetGateway}, {@code RouteTable}, {@code Route}, {@code NatGateway}, {@code EIP} and + * {@code SubnetRouteTableAssociation}. Extracted from {@code CloudFormationResourceProvisioner} as + * part of the per-service decomposition. The physical id is the EC2 id the service assigns, except + * for a Route, whose id is the registry primary identifier {@code |} (what + * Ref returns on AWS and what a delete needs), and an EIP, whose Ref is its public IP. + * + *

{@code provision} runs again on every {@code UpdateStack}. A resource whose create-only + * properties (the schema's {@code createOnlyProperties} that Floci emulates) are unchanged is kept: + * its prior entity is described and reused, and the mutable properties are applied in place. A + * changed create-only property creates the replacement and the {@link ReplacementCleanup} record + * deletes the displaced entity once the update commits or restores it on rollback, as CloudFormation + * does. A prior entity that is gone out of band is created anew. + * + *

Deletes tolerate only the service's own not-found code for each type; a + * {@code DependencyViolation} still fails the stack delete, as on AWS. + */ +@ApplicationScoped +public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner { + + private static final String SUBNET = "AWS::EC2::Subnet"; + private static final String INTERNET_GATEWAY = "AWS::EC2::InternetGateway"; + private static final String ROUTE_TABLE = "AWS::EC2::RouteTable"; + private static final String ROUTE = "AWS::EC2::Route"; + private static final String NAT_GATEWAY = "AWS::EC2::NatGateway"; + private static final String EIP = "AWS::EC2::EIP"; + private static final String SUBNET_ROUTE_TABLE_ASSOCIATION = "AWS::EC2::SubnetRouteTableAssociation"; + private static final String ROUTE_ID_SEPARATOR = "|"; + private static final Logger LOG = Logger.getLogger(Ec2NetworkCfnProvisioner.class); + /** + * What an in-place update changed on a reused entity, recorded before the change so a stack + * rollback can put it back: the prior tags (and the keys the update wrote), a subnet's prior + * MapPublicIpOnLaunch, a route's prior target. Internal, like the other {@code __Floci} attributes. + */ + static final String IN_PLACE_PRIOR_ATTR = "__FlociEc2NetworkPrior"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private final Ec2Service ec2Service; + + @Inject + public Ec2NetworkCfnProvisioner(Ec2Service ec2Service) { + this.ec2Service = ec2Service; + } + + @Override + public Set resourceTypes() { + return Set.of(SUBNET, INTERNET_GATEWAY, ROUTE_TABLE, ROUTE, NAT_GATEWAY, EIP, SUBNET_ROUTE_TABLE_ASSOCIATION); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + Map attributesBefore = Map.copyOf(r.getAttributes()); + switch (r.getResourceType()) { + case SUBNET -> provisionSubnet(r, props, ctx); + case INTERNET_GATEWAY -> provisionInternetGateway(r, props, ctx); + case ROUTE_TABLE -> provisionRouteTable(r, props, ctx); + case ROUTE -> provisionRoute(r, props, ctx); + case NAT_GATEWAY -> provisionNatGateway(r, props, ctx); + case EIP -> provisionEip(r, props, ctx); + case SUBNET_ROUTE_TABLE_ASSOCIATION -> provisionSubnetRouteTableAssociation(r, props, ctx); + default -> throw new IllegalStateException("Ec2NetworkCfnProvisioner cannot handle " + r.getResourceType()); + } + // A provision that left the resource with a new physical id replaced the entity: the + // displaced one is deleted once the update commits, or restored if the update rolls back. + ReplacementCleanup.record(r, ctx, attributesBefore); + } + + @Override + public boolean hasReplacementUpdate(StackResource resource) { + return ReplacementCleanup.hasReplacement(resource); + } + + @Override + public String updateCleanupPhysicalId(StackResource resource) { + return ReplacementCleanup.cleanupPhysicalId(resource); + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR); + return ReplacementCleanup.complete(resource, this::delete); + } + + @Override + public void clearUpdate(StackResource resource) { + resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR); + ReplacementCleanup.clear(resource); + } + + /** + * A replacement is undone through the cleanup record: the displaced entity was never touched. + * A reused entity that an update changed in place (tags, a subnet's MapPublicIpOnLaunch, a + * route's target) is put back from the snapshot taken before the change. Without either, the + * update changed nothing about the entity. A provision that fails mid-way restores its own + * snapshot before the failure propagates (see {@link #guarded}), so the previous metadata the + * engine restores for that resource matches the entity again. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + if (ReplacementCleanup.rollback(resource, this::delete)) { + resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR); + return true; + } + String snapshot = resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR); + if (snapshot != null) { + restoreInPlace(resource, snapshot); + } + return true; + } + + private void restoreInPlace(StackResource resource, String snapshot) { + ObjectNode prior; + try { + prior = (ObjectNode) MAPPER.readTree(snapshot); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Unreadable in-place snapshot on " + resource.getLogicalId(), e); + } + String region = prior.path("region").asText(); + String entityId = prior.path("entityId").asText(); + if (prior.has("tags")) { + Map priorTags = new LinkedHashMap<>(); + prior.get("tags").fields().forEachRemaining(f -> priorTags.put(f.getKey(), f.getValue().asText())); + List added = new ArrayList<>(); + prior.path("appliedKeys").forEach(key -> { + if (!priorTags.containsKey(key.asText())) { + added.add(new Tag(key.asText(), null)); + } + }); + if (!added.isEmpty()) { + ec2Service.deleteTags(region, List.of(entityId), added); + } + if (!priorTags.isEmpty()) { + ec2Service.createTags(region, List.of(entityId), toTagList(priorTags)); + } + } + if (prior.has("mapPublicIpOnLaunch")) { + ec2Service.modifySubnetAttribute(region, entityId, "mapPublicIpOnLaunch", prior.get("mapPublicIpOnLaunch").asText()); + } + if (prior.has("route")) { + ObjectNode target = (ObjectNode) prior.get("route"); + String routeTableId = target.path("routeTableId").asText(); + String cidr = text(target, "destinationCidrBlock"); + String ipv6 = text(target, "destinationIpv6CidrBlock"); + String prefixList = text(target, "destinationPrefixListId"); + String egressOnly = text(target, "egressOnlyInternetGatewayId"); + if (egressOnly != null) { + ec2Service.deleteRoute(region, routeTableId, cidr, ipv6, prefixList); + ec2Service.createRoute(region, routeTableId, cidr, ipv6, prefixList, null, null, egressOnly, null); + } else { + ec2Service.replaceRoute(region, routeTableId, cidr, ipv6, prefixList, + text(target, "gatewayId"), text(target, "natGatewayId"), text(target, "vpcPeeringConnectionId")); + } + } + } + + private static String text(ObjectNode node, String field) { + return node.hasNonNull(field) ? node.get(field).asText() : null; + } + + /** The snapshot for this resource, created on first use so the fields of several changes accumulate. */ + private static ObjectNode inPlacePrior(StackResource r, String entityId, ProvisionContext ctx) { + String existing = r.getAttributes().get(IN_PLACE_PRIOR_ATTR); + try { + ObjectNode node = existing == null ? MAPPER.createObjectNode() : (ObjectNode) MAPPER.readTree(existing); + node.put("region", ctx.region()); + node.put("entityId", entityId); + return node; + } catch (JsonProcessingException e) { + throw new IllegalStateException("Unreadable in-place snapshot on " + r.getLogicalId(), e); + } + } + + private static void writeInPlacePrior(StackResource r, ObjectNode node) { + r.getAttributes().put(IN_PLACE_PRIOR_ATTR, node.toString()); + } + + /** An EIP's Ref is its public IP, so its release needs the AllocationId recorded at create time. */ + @Override + public void delete(StackResource resource, String region) { + if (EIP.equals(resource.getResourceType()) && resource.getAttributes() != null + && resource.getAttributes().get("AllocationId") != null) { + String allocationId = resource.getAttributes().get("AllocationId"); + CfnDeletes.safeDelete("elastic IP", allocationId, + () -> ec2Service.releaseAddress(region, allocationId), "InvalidAllocationID.NotFound"); + return; + } + delete(resource.getResourceType(), resource.getPhysicalId(), region); + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + if (physicalId == null || physicalId.isBlank()) { + return; + } + switch (resourceType) { + case SUBNET -> CfnDeletes.safeDelete("subnet", physicalId, + () -> ec2Service.deleteSubnet(region, physicalId), "InvalidSubnetID.NotFound"); + case INTERNET_GATEWAY -> CfnDeletes.safeDelete("internet gateway", physicalId, + () -> ec2Service.deleteInternetGateway(region, physicalId), "InvalidInternetGatewayID.NotFound"); + case ROUTE_TABLE -> CfnDeletes.safeDelete("route table", physicalId, + () -> ec2Service.deleteRouteTable(region, physicalId), "InvalidRouteTableID.NotFound"); + case ROUTE -> deleteRoute(physicalId, region); + case NAT_GATEWAY -> CfnDeletes.safeDelete("NAT gateway", physicalId, + () -> ec2Service.deleteNatGateway(region, physicalId), "NatGatewayNotFound"); + case EIP -> releaseByPublicIp(physicalId, region); + case SUBNET_ROUTE_TABLE_ASSOCIATION -> CfnDeletes.safeDelete("route table association", physicalId, + () -> ec2Service.disassociateRouteTable(region, physicalId), "InvalidAssociationID.NotFound"); + default -> { } + } + } + + /** + * The route's id names its table and destination; a route created by the switch before this + * provisioner existed carries a generated id with no separator and cannot be located, so it is + * left alone rather than guessed at. A table that is already gone took its routes with it. + */ + private void deleteRoute(String physicalId, String region) { + int separator = physicalId.indexOf(ROUTE_ID_SEPARATOR); + if (separator <= 0 || separator == physicalId.length() - 1) { + return; + } + String routeTableId = physicalId.substring(0, separator); + String destination = physicalId.substring(separator + 1); + CfnDeletes.safeDelete("route", physicalId, () -> ec2Service.deleteRoute(region, routeTableId, + isIpv4Cidr(destination) ? destination : null, + isIpv6Cidr(destination) ? destination : null, + isPrefixList(destination) ? destination : null), + "InvalidRoute.NotFound", "InvalidRouteTableID.NotFound"); + } + + /** Without the recorded AllocationId (a rollback of a failed create, for instance), the address is looked up by IP. */ + private void releaseByPublicIp(String publicIp, String region) { + ec2Service.describeAddresses(region, List.of(), Map.of("public-ip", List.of(publicIp))).stream() + .findFirst() + .ifPresent(address -> CfnDeletes.safeDelete("elastic IP", address.getAllocationId(), + () -> ec2Service.releaseAddress(region, address.getAllocationId()), "InvalidAllocationID.NotFound")); + } + + /** + * Reconciles the template's {@code Tags} onto an entity: keys the template dropped are removed, + * the rest written. A template without a Tags property leaves whatever the entity carries. + */ + private void applyTags(StackResource r, boolean reused, String resourceId, List current, JsonNode props, ProvisionContext ctx) { + if (props == null || !props.has("Tags")) { + return; + } + Map desired = ctx.resolveTags(props, "Tags"); + Map currentTags = new LinkedHashMap<>(); + for (Tag tag : current == null ? List.of() : current) { + currentTags.put(tag.getKey(), tag.getValue()); + } + List stale = ProvisionContext.staleTagKeys(currentTags, desired); + if (reused && ctx.isUpdate() && (!stale.isEmpty() || !desired.equals(currentTags))) { + ObjectNode prior = inPlacePrior(r, resourceId, ctx); + ObjectNode tags = prior.putObject("tags"); + currentTags.forEach(tags::put); + var applied = prior.putArray("appliedKeys"); + desired.keySet().forEach(applied::add); + writeInPlacePrior(r, prior); + } + if (!stale.isEmpty()) { + ec2Service.deleteTags(ctx.region(), List.of(resourceId), + stale.stream().map(key -> new Tag(key, null)).toList()); + } + if (!desired.isEmpty()) { + ec2Service.createTags(ctx.region(), List.of(resourceId), toTagList(desired)); + } + } + + private static List tagList(JsonNode props, ProvisionContext ctx) { + return toTagList(ctx.resolveTags(props, "Tags")); + } + + private static List toTagList(Map tags) { + List out = new ArrayList<>(); + tags.forEach((key, value) -> out.add(new Tag(key, value))); + return out; + } + + private Subnet findSubnet(String subnetId, String region) { + return tolerateNotFound(() -> ec2Service.describeSubnets(region, List.of(subnetId), Map.of()).stream() + .findFirst().orElse(null), "InvalidSubnetID.NotFound", subnetId); + } + + private InternetGateway findInternetGateway(String igwId, String region) { + return tolerateNotFound(() -> ec2Service.describeInternetGateways(region, List.of(igwId), Map.of()).stream() + .findFirst().orElse(null), "InvalidInternetGatewayID.NotFound", igwId); + } + + private RouteTable findRouteTable(String routeTableId, String region) { + return tolerateNotFound(() -> ec2Service.describeRouteTables(region, List.of(routeTableId), Map.of()).stream() + .findFirst().orElse(null), "InvalidRouteTableID.NotFound", routeTableId); + } + + private RouteTableAssociation findAssociation(String associationId, String region) { + return ec2Service.describeRouteTables(region, List.of(), + Map.of("association.route-table-association-id", List.of(associationId))).stream() + .flatMap(rt -> rt.getAssociations().stream()) + .filter(a -> associationId.equals(a.getRouteTableAssociationId())) + .findFirst().orElse(null); + } + + private NatGateway findNatGateway(String natGatewayId, String region) { + return tolerateNotFound(() -> ec2Service.describeNatGateways(region, List.of(natGatewayId), Map.of()).stream() + .filter(nat -> !"deleted".equals(nat.getState())) + .findFirst().orElse(null), "NatGatewayNotFound", natGatewayId); + } + + private Address findAddress(String allocationId, String publicIp, String region) { + List

matches = allocationId != null + ? ec2Service.describeAddresses(region, List.of(allocationId), Map.of()) + : ec2Service.describeAddresses(region, List.of(), Map.of("public-ip", List.of(publicIp))); + return matches.stream().findFirst().orElse(null); + } + + private Route findRoute(String routeTableId, String destination, String region) { + RouteTable table = findRouteTable(routeTableId, region); + return table == null ? null : table.getRoutes().stream() + .filter(route -> destination.equals(routeDestination(route))) + .findFirst().orElse(null); + } + + private static String routeDestination(Route route) { + if (route.getDestinationCidrBlock() != null) { + return route.getDestinationCidrBlock(); + } + if (route.getDestinationIpv6CidrBlock() != null) { + return route.getDestinationIpv6CidrBlock(); + } + return route.getDestinationPrefixListId(); + } + + private static T tolerateNotFound(Supplier lookup, String notFoundCode, String id) { + try { + return lookup.get(); + } catch (AwsException e) { + if (!notFoundCode.equals(e.getErrorCode())) { + throw e; + } + LOG.debugv("{0} is gone; creating it anew", id); + return null; + } + } + + /** The schema's required properties fail the resource with the repo's ValidationError wording, not a null into the service. */ + private static void require(String type, String property, String value) { + if (value == null || value.isBlank()) { + throw new AwsException("ValidationError", type + " requires " + property, 400); + } + } + + private static boolean isPrefixList(String destination) { + return destination.startsWith("pl-"); + } + + private static boolean isIpv6Cidr(String destination) { + return destination.contains(":"); + } + + private static boolean isIpv4Cidr(String destination) { + return !isPrefixList(destination) && !isIpv6Cidr(destination); + } + + private void provisionSubnet(StackResource r, JsonNode props, ProvisionContext ctx) { + String vpcId = ctx.resolveOptional(props, "VpcId"); + String cidr = ctx.resolveOptional(props, "CidrBlock"); + String az = ctx.resolveOptional(props, "AvailabilityZone"); + String mapPublicIpOnLaunch = ctx.resolveOptional(props, "MapPublicIpOnLaunch"); + require(SUBNET, "VpcId", vpcId); + // VpcId, CidrBlock and AvailabilityZone are createOnly: unchanged, the subnet is kept and + // only MapPublicIpOnLaunch is applied; changed, a new subnet replaces it. + Subnet existing = ctx.isUpdate() ? findSubnet(ctx.priorPhysicalId(), ctx.region()) : null; + boolean reuse = existing != null && Objects.equals(vpcId, existing.getVpcId()) + && Objects.equals(cidr, existing.getCidrBlock()) + && (az == null || az.equals(existing.getAvailabilityZone())); + Subnet subnet = reuse ? existing : ec2Service.createSubnet(ctx.region(), vpcId, cidr, az); + r.setPhysicalId(subnet.getSubnetId()); + r.getAttributes().put("SubnetId", subnet.getSubnetId()); + r.getAttributes().put("VpcId", subnet.getVpcId()); + r.getAttributes().put("AvailabilityZone", subnet.getAvailabilityZone()); + guarded(r, ctx, !reuse, () -> ec2Service.deleteSubnet(ctx.region(), subnet.getSubnetId()), () -> { + applyTags(r, reuse, subnet.getSubnetId(), reuse ? existing.getTags() : List.of(), props, ctx); + if (mapPublicIpOnLaunch != null) { + if (reuse && ctx.isUpdate() && existing.isMapPublicIpOnLaunch() != Boolean.parseBoolean(mapPublicIpOnLaunch)) { + ObjectNode prior = inPlacePrior(r, subnet.getSubnetId(), ctx); + prior.put("mapPublicIpOnLaunch", String.valueOf(existing.isMapPublicIpOnLaunch())); + writeInPlacePrior(r, prior); + } + ec2Service.modifySubnetAttribute(ctx.region(), subnet.getSubnetId(), "mapPublicIpOnLaunch", mapPublicIpOnLaunch); + } + }); + } + + /** + * Runs the steps that follow an EC2 create or change a reused entity in place. If one of them + * throws, what this provision did is undone before the failure propagates: a created entity is + * deleted again, a reused one is put back from its snapshot. The engine only removes a failed + * create it can see, and on a failed update it restores the previous resource metadata and + * discards the attempted one, snapshot included, so the undo has to happen here. + * + *

A compensation that fails is reported, never hidden. A created entity carries + * {@link CfnRollback#ROLLBACK_OWNED_ATTR} while the steps run, so the engine's create rollback + * deletes it (and reports that failing) if the undo here could not, and during an update the + * entity is also listed in the cleanup record, which the engine carries onto the restored + * resource and runs before the next committed update or the stack delete; a reused entity keeps its + * snapshot and the reason lands in {@link CfnRollback#UPDATE_ROLLBACK_FAILURE_ATTR}, which the + * engine copies onto the committed resource so the rollback walker reports + * UPDATE_ROLLBACK_FAILED instead of claiming the prior state is live. + */ + private void guarded(StackResource r, ProvisionContext ctx, boolean created, Runnable undoCreate, Runnable steps) { + if (created) { + r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true"); + } + try { + steps.run(); + r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR); + } catch (RuntimeException e) { + if (created) { + try { + undoCreate.run(); + r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR); + } catch (RuntimeException undo) { + e.addSuppressed(undo); + String reason = "Could not remove " + r.getPhysicalId() + ", created for " + r.getLogicalId() + + " by a failed update: " + undo.getMessage(); + LOG.warn(reason); + r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, reason); + if (ctx.isUpdate()) { + // The engine restores the previous resource and keeps only what the cleanup + // record carries, so the replacement is listed there for the next cleanup. + ReplacementCleanup.recordOrphan(r, r.getPhysicalId(), r.getResourceType(), ctx.region()); + } + } + } else { + String snapshot = r.getAttributes().get(IN_PLACE_PRIOR_ATTR); + if (snapshot != null) { + try { + restoreInPlace(r, snapshot); + r.getAttributes().remove(IN_PLACE_PRIOR_ATTR); + } catch (RuntimeException undo) { + e.addSuppressed(undo); + String reason = "Could not restore " + r.getPhysicalId() + " for " + r.getLogicalId() + + " after a failed update: " + undo.getMessage(); + LOG.warn(reason); + r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, reason); + } + } + } + throw e; + } + } + + private void provisionInternetGateway(StackResource r, JsonNode props, ProvisionContext ctx) { + InternetGateway existing = ctx.isUpdate() ? findInternetGateway(ctx.priorPhysicalId(), ctx.region()) : null; + InternetGateway igw = existing != null ? existing : ec2Service.createInternetGateway(ctx.region()); + r.setPhysicalId(igw.getInternetGatewayId()); + r.getAttributes().put("InternetGatewayId", igw.getInternetGatewayId()); + guarded(r, ctx, existing == null, () -> ec2Service.deleteInternetGateway(ctx.region(), igw.getInternetGatewayId()), + () -> applyTags(r, existing != null, igw.getInternetGatewayId(), existing != null ? existing.getTags() : List.of(), props, ctx)); + } + + private void provisionRouteTable(StackResource r, JsonNode props, ProvisionContext ctx) { + String vpcId = ctx.resolveOptional(props, "VpcId"); + require(ROUTE_TABLE, "VpcId", vpcId); + // VpcId is createOnly: a table in the same VPC is kept, one in another VPC is replaced. + RouteTable existing = ctx.isUpdate() ? findRouteTable(ctx.priorPhysicalId(), ctx.region()) : null; + boolean reuse = existing != null && Objects.equals(vpcId, existing.getVpcId()); + RouteTable rt = reuse ? existing : ec2Service.createRouteTable(ctx.region(), vpcId); + r.setPhysicalId(rt.getRouteTableId()); + r.getAttributes().put("RouteTableId", rt.getRouteTableId()); + guarded(r, ctx, !reuse, () -> ec2Service.deleteRouteTable(ctx.region(), rt.getRouteTableId()), + () -> applyTags(r, reuse, rt.getRouteTableId(), reuse ? existing.getTags() : List.of(), props, ctx)); + } + + private void provisionSubnetRouteTableAssociation(StackResource r, JsonNode props, ProvisionContext ctx) { + String routeTableId = ctx.resolveOptional(props, "RouteTableId"); + String subnetId = ctx.resolveOptional(props, "SubnetId"); + require(SUBNET_ROUTE_TABLE_ASSOCIATION, "RouteTableId", routeTableId); + require(SUBNET_ROUTE_TABLE_ASSOCIATION, "SubnetId", subnetId); + // Both properties are createOnly: the same pair keeps the association, anything else is a + // new association and the prior one is removed once the update commits. + RouteTableAssociation existing = ctx.isUpdate() ? findAssociation(ctx.priorPhysicalId(), ctx.region()) : null; + RouteTableAssociation assoc = existing != null && Objects.equals(routeTableId, existing.getRouteTableId()) + && Objects.equals(subnetId, existing.getSubnetId()) + ? existing : ec2Service.associateRouteTable(ctx.region(), routeTableId, subnetId); + r.setPhysicalId(assoc.getRouteTableAssociationId()); + r.getAttributes().put("Id", assoc.getRouteTableAssociationId()); + } + + private void provisionRoute(StackResource r, JsonNode props, ProvisionContext ctx) { + String routeTableId = ctx.resolveOptional(props, "RouteTableId"); + String destinationCidr = ctx.resolveOptional(props, "DestinationCidrBlock"); + String destinationIpv6Cidr = ctx.resolveOptional(props, "DestinationIpv6CidrBlock"); + String destinationPrefixListId = ctx.resolveOptional(props, "DestinationPrefixListId"); + String gatewayId = ctx.resolveOptional(props, "GatewayId"); + String natGatewayId = ctx.resolveOptional(props, "NatGatewayId"); + String egressOnlyInternetGatewayId = ctx.resolveOptional(props, "EgressOnlyInternetGatewayId"); + String vpcPeeringConnectionId = ctx.resolveOptional(props, "VpcPeeringConnectionId"); + require(ROUTE, "RouteTableId", routeTableId); + long destinations = java.util.stream.Stream.of(destinationCidr, destinationIpv6Cidr, destinationPrefixListId) + .filter(value -> value != null && !value.isBlank()).count(); + if (destinations != 1) { + throw new AwsException("ValidationError", ROUTE + " requires exactly one of DestinationCidrBlock," + + " DestinationIpv6CidrBlock or DestinationPrefixListId", 400); + } + // The registry primary identifier is RouteTableId|CidrBlock, which is also what Ref returns + // on AWS, and the only id a later delete can act on. CidrBlock is the schema's read-only + // attribute: the destination the route was created with, whichever property carried it. + // Ec2Service stores an IPv4 destination in canonical form (10.0.0.18/24 is 10.0.0.0/24), so + // the id, the attribute and the reuse check use that form too, or an unchanged update + // would miss its own route and try to create it again. + String canonicalCidr = destinationCidr == null ? null + : CidrCanonicalizer.canonicalize(destinationCidr).orElse(destinationCidr); + String destination = canonicalCidr != null ? canonicalCidr + : destinationIpv6Cidr != null ? destinationIpv6Cidr : destinationPrefixListId; + String physicalId = routeTableId + ROUTE_ID_SEPARATOR + destination; + Supplier create = () -> { + ec2Service.createRoute(ctx.region(), routeTableId, destinationCidr, destinationIpv6Cidr, + destinationPrefixListId, gatewayId, natGatewayId, egressOnlyInternetGatewayId, + vpcPeeringConnectionId); + return null; + }; + // The table and destination are createOnly: the same pair changes the target in place, + // another pair is a new route and the prior one goes once the update commits. + Route current = ctx.isUpdate() && physicalId.equals(ctx.priorPhysicalId()) + ? findRoute(routeTableId, destination, ctx.region()) : null; + if (current != null) { + ObjectNode prior = inPlacePrior(r, physicalId, ctx); + ObjectNode target = prior.putObject("route"); + target.put("routeTableId", routeTableId); + target.put("destinationCidrBlock", current.getDestinationCidrBlock()); + target.put("destinationIpv6CidrBlock", current.getDestinationIpv6CidrBlock()); + target.put("destinationPrefixListId", current.getDestinationPrefixListId()); + target.put("gatewayId", current.getGatewayId()); + target.put("natGatewayId", current.getNatGatewayId()); + target.put("egressOnlyInternetGatewayId", current.getEgressOnlyInternetGatewayId()); + target.put("vpcPeeringConnectionId", current.getVpcPeeringConnectionId()); + writeInPlacePrior(r, prior); + guarded(r, ctx, false, () -> { }, () -> { + if (egressOnlyInternetGatewayId != null) { + // ReplaceRoute has no egress-only target; re-creating the route is the same outcome. + ec2Service.deleteRoute(ctx.region(), routeTableId, destinationCidr, destinationIpv6Cidr, destinationPrefixListId); + create.get(); + } else { + ec2Service.replaceRoute(ctx.region(), routeTableId, destinationCidr, destinationIpv6Cidr, + destinationPrefixListId, gatewayId, natGatewayId, vpcPeeringConnectionId); + } + }); + } else { + create.get(); + } + r.setPhysicalId(physicalId); + if (destination != null) { + r.getAttributes().put("CidrBlock", destination); + } + } + + private void provisionNatGateway(StackResource r, JsonNode props, ProvisionContext ctx) { + String subnetId = ctx.resolveOptional(props, "SubnetId"); + String allocationId = ctx.resolveOptional(props, "AllocationId"); + require(NAT_GATEWAY, "SubnetId", subnetId); + // ConnectivityType defaults to public in the schema; a public gateway needs an EIP, a + // private one must not have one, as AWS validates. + String connectivityType = ctx.resolveOptional(props, "ConnectivityType"); + connectivityType = connectivityType == null || connectivityType.isBlank() ? "public" : connectivityType.toLowerCase(); + if ("public".equals(connectivityType) && (allocationId == null || allocationId.isBlank())) { + throw new AwsException("ValidationError", "AWS::EC2::NatGateway requires AllocationId for a public gateway", 400); + } + if ("private".equals(connectivityType) && allocationId != null && !allocationId.isBlank()) { + throw new AwsException("ValidationError", "AWS::EC2::NatGateway with ConnectivityType private cannot have an AllocationId", 400); + } + // SubnetId, AllocationId and ConnectivityType are createOnly: the same triple keeps the + // gateway, a change replaces it. + NatGateway existing = ctx.isUpdate() ? findNatGateway(ctx.priorPhysicalId(), ctx.region()) : null; + boolean reuse = existing != null && Objects.equals(subnetId, existing.getSubnetId()) + && Objects.equals(allocationId, existing.getAllocationId()) + && connectivityType.equalsIgnoreCase(existing.getConnectivityType() == null ? "public" : existing.getConnectivityType()); + NatGateway nat = reuse ? existing + : ec2Service.createNatGateway(ctx.region(), subnetId, allocationId, connectivityType, tagList(props, ctx)); + if (reuse) { + guarded(r, ctx, false, () -> { }, () -> applyTags(r, true, nat.getNatGatewayId(), existing.getTags(), props, ctx)); + } + r.setPhysicalId(nat.getNatGatewayId()); + r.getAttributes().put("NatGatewayId", nat.getNatGatewayId()); + } + + private void provisionEip(StackResource r, JsonNode props, ProvisionContext ctx) { + // Nothing about an EIP that Floci emulates is mutable or create-only in a way a template can + // change, so an address that is still allocated is simply kept. + Address existing = ctx.isUpdate() ? findAddress(r.getAttributes().get("AllocationId"), ctx.priorPhysicalId(), ctx.region()) : null; + Address addr = existing != null ? existing : ec2Service.allocateAddress(ctx.region()); + // Ref on AWS::EC2::EIP returns the public IP; AllocationId is exposed via Fn::GetAtt. + r.setPhysicalId(addr.getPublicIp()); + r.getAttributes().put("AllocationId", addr.getAllocationId()); + r.getAttributes().put("PublicIp", addr.getPublicIp()); + guarded(r, ctx, existing == null, () -> ec2Service.releaseAddress(ctx.region(), addr.getAllocationId()), + () -> applyTags(r, existing != null, addr.getAllocationId(), existing != null ? existing.getTags() : List.of(), props, ctx)); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java index 8b1258c529..9ab3340944 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java @@ -30,7 +30,7 @@ import java.util.Map; * A provisioner calls {@link #record} at the end of a successful {@code provision} and delegates * the cleanup hooks and {@link #rollback} here. */ -final class ReplacementCleanup { +public final class ReplacementCleanup { private static final Logger LOG = Logger.getLogger(ReplacementCleanup.class); private static final ObjectMapper MAPPER = new ObjectMapper(); @@ -239,6 +239,55 @@ final class ReplacementCleanup { return displaced.isEmpty() ? null : displaced.get(0).path("physicalId").asText(null); } + /** + * Lists an entity this provision created and could not remove after a later step failed, so + * the next committed update or the stack delete removes it instead of nothing ever trying + * again. Never retainable: a failed update created it. + */ + static void recordOrphan(StackResource r, String physicalId, String resourceType, String region) { + ObjectNode cleanup = readOrEmpty(r); + if (region != null) { + cleanup.put("region", region); + } + addDisplaced(cleanup, physicalId, resourceType, region, false); + write(r, cleanup); + } + + /** + * Carries the entities {@code from} owes a delete onto {@code into}, keeping their attempt + * counts and regions and skipping ids {@code into} already lists or owns. The engine calls this + * through {@code mergeFailedUpdateResourceTracking} when it restores the previous resource + * after a failed update, so an orphan the attempt recorded is not lost with the attempt. + */ + public static void mergeDisplaced(StackResource into, StackResource from) { + ObjectNode source = read(from); + if (source == null || source.path("displaced").size() == 0) { + return; + } + ObjectNode target = readOrEmpty(into); + if (target.path("region").asText(null) == null && source.path("region").asText(null) != null) { + target.put("region", source.path("region").asText()); + } + ArrayNode displaced = target.withArray("displaced"); + for (JsonNode entry : source.path("displaced")) { + String physicalId = entry.path("physicalId").asText(null); + if (physicalId == null || physicalId.equals(into.getPhysicalId())) { + continue; + } + boolean present = false; + for (JsonNode existing : displaced) { + if (physicalId.equals(existing.path("physicalId").asText(null))) { + present = true; + break; + } + } + if (!present) { + displaced.add(entry.deepCopy()); + } + } + write(into, target); + } + private static void addDisplaced(ObjectNode cleanup, String physicalId, String resourceType, String region, boolean retainable) { ArrayNode displaced = cleanup.withArray("displaced"); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java index 0d01ab1fe3..e4f427a107 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java @@ -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(); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index fdbc9c7001..7a20f61490 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -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)); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2NetworkingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2NetworkingIntegrationTest.java new file mode 100644 index 0000000000..96262fae6f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2NetworkingIntegrationTest.java @@ -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 |}, {@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")), "", ""); + cloudFormation(ROLLBACK_STACK, "CreateStack", rollbackTemplate(vpcId, false)); + Map out = XmlParser.extractPairs(describeStacks(ROLLBACK_STACK, "CREATE_COMPLETE"), "Outputs", "OutputKey", "OutputValue"); + assertTrue(ec2("DescribeRouteTables").contains("before")); + assertTrue(subnetXml(out.get("SubnetId")).contains("true")); + + cloudFormation(ROLLBACK_STACK, "UpdateStack", rollbackTemplate(vpcId, true)); + + describeStacks(ROLLBACK_STACK, "UPDATE_ROLLBACK_COMPLETE"); + String routeTables = ec2("DescribeRouteTables"); + assertTrue(routeTables.contains("before") && !routeTables.contains("after"), + "the route table's prior tag must be back: " + routeTables); + assertTrue(subnetXml(out.get("SubnetId")).contains("true"), + "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")), "", ""); + cloudFormation("CreateStack", template(vpcId, "10.40.0.0/24")); + + String stacks = describeStacks("CREATE_COMPLETE"); + Map 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("tier") && subnets.contains("web"), "subnet tags must reach EC2: " + subnets); + String routeTables = ec2("DescribeRouteTables"); + assertTrue(routeTables.contains("public-rt"), "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 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("env"), "the new tag must be written"); + assertFalse(retagged.contains("tier"), "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 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("" + expectedStatus + "")) + .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("DELETE_FAILED")) { + 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 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(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisionerTest.java new file mode 100644 index 0000000000..f2c60997c1 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisionerTest.java @@ -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 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 pairs(List tags) { + return tags.stream().map(t -> t.getKey() + "=" + t.getValue()).toList(); + } + + @SuppressWarnings("unchecked") + private List tagsWritten(String resourceId) { + ArgumentCaptor> 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> 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> 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> 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> 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 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> 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> 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> 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> 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())); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanupTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanupTest.java new file mode 100644 index 0000000000..7a2891621e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanupTest.java @@ -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 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 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)); + } +} diff --git a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv index 4de066c11c..470712c55d 100644 --- a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv +++ b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv @@ -1,6 +1,13 @@ AWS::CodeBuild::Project Id schema gives no description; AWS's Id may differ from the project name Floci uses AWS::CodePipeline::CustomActionType Id schema gives no description; the custom action has no separate id in Floci AWS::CodePipeline::Webhook Id schema gives no description; Floci keys webhooks by name +AWS::EC2::NatGateway AutoProvisionZones availability-mode NAT gateways are not emulated +AWS::EC2::NatGateway AutoScalingIps availability-mode NAT gateways are not emulated +AWS::EC2::NatGateway EniId the NAT gateway's network interface is not created +AWS::EC2::NatGateway RouteTableId availability-mode NAT gateways are not emulated +AWS::EC2::Subnet BlockPublicAccessStates VPC block public access is not emulated +AWS::EC2::Subnet Ipv6CidrBlocks IPv6 CIDR association is not emulated +AWS::EC2::Subnet NetworkAclAssociationId the subnet's default network ACL association is not created with the subnet AWS::EC2::VPC CidrBlockAssociations needs association ids Floci's VPC model does not track AWS::EC2::VPC DefaultNetworkAcl needs a default network ACL Floci does not create with the VPC AWS::EC2::VPC Ipv6CidrBlocks IPv6 CIDR association is not emulated diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index b404f437d1..a29e5e930e 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -39,22 +39,22 @@ AWS::Cognito::UserPoolDomain CognitoCfnProvisioner AWS::Config::ConfigRule ConfigCfnProvisioner AWS::DynamoDB::GlobalTable LEGACY_SWITCH AWS::DynamoDB::Table LEGACY_SWITCH -AWS::EC2::EIP LEGACY_SWITCH +AWS::EC2::EIP Ec2NetworkCfnProvisioner AWS::EC2::FlowLog Ec2FlowLogCfnProvisioner AWS::EC2::Instance LEGACY_SWITCH -AWS::EC2::InternetGateway LEGACY_SWITCH +AWS::EC2::InternetGateway Ec2NetworkCfnProvisioner AWS::EC2::LaunchTemplate Ec2LaunchTemplateCfnProvisioner -AWS::EC2::NatGateway LEGACY_SWITCH +AWS::EC2::NatGateway Ec2NetworkCfnProvisioner AWS::EC2::NetworkAcl Ec2NetworkAclCfnProvisioner AWS::EC2::NetworkAclEntry Ec2NetworkAclCfnProvisioner -AWS::EC2::Route LEGACY_SWITCH -AWS::EC2::RouteTable LEGACY_SWITCH +AWS::EC2::Route Ec2NetworkCfnProvisioner +AWS::EC2::RouteTable Ec2NetworkCfnProvisioner AWS::EC2::SecurityGroup LEGACY_SWITCH AWS::EC2::SecurityGroupEgress Ec2SecurityGroupRuleCfnProvisioner AWS::EC2::SecurityGroupIngress Ec2SecurityGroupRuleCfnProvisioner -AWS::EC2::Subnet LEGACY_SWITCH +AWS::EC2::Subnet Ec2NetworkCfnProvisioner AWS::EC2::SubnetNetworkAclAssociation Ec2NetworkAclCfnProvisioner -AWS::EC2::SubnetRouteTableAssociation LEGACY_SWITCH +AWS::EC2::SubnetRouteTableAssociation Ec2NetworkCfnProvisioner AWS::EC2::VPC Ec2VpcCfnProvisioner AWS::EC2::VPCEndpoint Ec2VpcEndpointCfnProvisioner AWS::EC2::VPCGatewayAttachment Ec2VpcGatewayAttachmentCfnProvisioner