Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudformation): provision AWS::EC2::PrefixList (#6481)
Jackson Price6acd90640d95
diff --git a/compatibility-tests/sdk-test-python/tests/test_cloudformation_prefix_list.py b/compatibility-tests/sdk-test-python/tests/test_cloudformation_prefix_list.pynew file mode 100644index 0000000000..0189519491--- /dev/null+++ b/compatibility-tests/sdk-test-python/tests/test_cloudformation_prefix_list.py@@ -0,0 +1,75 @@+"""CloudFormation AWS::EC2::PrefixList creates, updates and deletes the prefix list EC2 serves."""++import json++import pytest+from botocore.exceptions import ClientError++WAITER = {"Delay": 1, "MaxAttempts": 60}+++def _template(properties):+ outputs = {name: {"Value": {"Fn::GetAtt": ["Firewall", name]}} for name in ("PrefixListId", "Arn", "OwnerId")}+ outputs["Ref"] = {"Value": {"Ref": "Firewall"}}+ return json.dumps({+ "Resources": {"Firewall": {"Type": "AWS::EC2::PrefixList", "Properties": properties}},+ "Outputs": outputs,+ })+++def _prefix_list(ec2_client, prefix_list_id):+ return ec2_client.describe_managed_prefix_lists(PrefixListIds=[prefix_list_id])["PrefixLists"][0]+++def test_prefix_list_lifecycle(cloudformation_client, ec2_client, unique_name):+ stack = "prefix-list-" + unique_name+ properties = {+ "PrefixListName": stack,+ "AddressFamily": "IPv4",+ "MaxEntries": 1,+ "Entries": [{"Cidr": "192.0.2.0/24", "Description": "office"}],+ "Tags": [{"Key": "fixture", "Value": unique_name}],+ }+ cloudformation_client.create_stack(StackName=stack, TemplateBody=_template(properties))+ prefix_list_id = None+ try:+ cloudformation_client.get_waiter("stack_create_complete").wait(StackName=stack, WaiterConfig=WAITER)+ outputs = {+ row["OutputKey"]: row["OutputValue"]+ for row in cloudformation_client.describe_stacks(StackName=stack)["Stacks"][0]["Outputs"]+ }+ prefix_list_id = outputs["Ref"]+ created = _prefix_list(ec2_client, prefix_list_id)+ assert outputs["PrefixListId"] == prefix_list_id+ assert outputs["Arn"] == created["PrefixListArn"]+ assert outputs["OwnerId"] == created["OwnerId"]+ assert created["Version"] == 1+ assert {"Key": "fixture", "Value": unique_name} in created["Tags"]+ assert ec2_client.get_managed_prefix_list_entries(PrefixListId=prefix_list_id)["Entries"] == properties["Entries"]++ # Capacity alone changes in place and makes no new version.+ properties["MaxEntries"] = 2+ cloudformation_client.update_stack(StackName=stack, TemplateBody=_template(properties))+ cloudformation_client.get_waiter("stack_update_complete").wait(StackName=stack, WaiterConfig=WAITER)+ resized = _prefix_list(ec2_client, prefix_list_id)+ assert (resized["MaxEntries"], resized["Version"]) == (2, 1)++ # New entries make a new version of the same list; dropping Tags removes them.+ properties["Entries"] = [{"Cidr": "198.51.100.0/24", "Description": "branch"}]+ del properties["Tags"]+ cloudformation_client.update_stack(StackName=stack, TemplateBody=_template(properties))+ cloudformation_client.get_waiter("stack_update_complete").wait(StackName=stack, WaiterConfig=WAITER)+ physical_id = cloudformation_client.describe_stack_resource(+ StackName=stack, LogicalResourceId="Firewall")["StackResourceDetail"]["PhysicalResourceId"]+ assert physical_id == prefix_list_id+ changed = _prefix_list(ec2_client, prefix_list_id)+ assert (changed["MaxEntries"], changed["Version"]) == (2, 2)+ assert all(tag["Key"] != "fixture" for tag in changed.get("Tags", []))+ assert ec2_client.get_managed_prefix_list_entries(PrefixListId=prefix_list_id)["Entries"] == properties["Entries"]+ finally:+ cloudformation_client.delete_stack(StackName=stack)+ cloudformation_client.get_waiter("stack_delete_complete").wait(StackName=stack, WaiterConfig=WAITER)++ with pytest.raises(ClientError) as missing:+ ec2_client.get_managed_prefix_list_entries(PrefixListId=prefix_list_id)+ assert missing.value.response["Error"]["Code"] == "InvalidPrefixListID.NotFound"diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.mdindex 3dacff3737..70152830af 100644--- a/docs/services/cloudformation.md+++ b/docs/services/cloudformation.md@@ -189,7 +189,7 @@ cross-resource references.| ElastiCache | `CacheCluster` (starts a real container; modifying an existing cluster in place is not supported), `SubnetGroup`, `User` (Tags are ignored), `UserGroup` (Tags are ignored), `ServerlessCache` (GetAtt uses the dotted Endpoint.* and ReaderEndpoint.* form) || Redshift | `Cluster` (single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported), `ClusterParameterGroup`, `ClusterSubnetGroup`, `ClusterSecurityGroup` (accepted; no EC2-Classic security group model) || Redshift Serverless | `Namespace` (ManageAdminPassword is accepted and not applied; GetAtt uses the dotted Namespace.* form), `Workgroup` (starts a real container; one workgroup per namespace; capacity, VPC and price-performance settings are stored only; snapshot restore properties are ignored; GetAtt uses the dotted Workgroup.* form) |-| EC2 | `VPC` (deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS), `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` |+| EC2 | `VPC` (deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS), `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog`, `PrefixList` (updated in place; an update that changes `AddressFamily`, or `MaxEntries` together with `Entries`, fails) || Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` || Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook`, `ScalingPolicy` || Application Auto Scaling | `ScalableTarget` (`ScheduledActions` are accepted and not run; Floci has no scheduled scaling), `ScalingPolicy` |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.javaindex 4998f4c482..159946e41a 100644--- 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@@ -11,7 +11,9 @@ 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.ManagedPrefixList;import io.github.hectorvent.floci.services.ec2.model.NatGateway;+import io.github.hectorvent.floci.services.ec2.model.PrefixListEntry;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;@@ -22,16 +24,18 @@ import jakarta.inject.Inject;import org.jboss.logging.Logger;import java.util.ArrayList;+import java.util.Arrays;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;+import java.util.stream.Collectors;/*** CloudFormation provisioning for the EC2 networking types: {@code AWS::EC2::Subnet},- * {@code InternetGateway}, {@code RouteTable}, {@code Route}, {@code NatGateway}, {@code EIP} and+ * {@code InternetGateway}, {@code RouteTable}, {@code Route}, {@code NatGateway}, {@code EIP}, {@code PrefixList} and* {@code SubnetRouteTableAssociation}. Extracted from the former CloudFormation monolith 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 <RouteTableId>|<destination>} (what@@ -56,13 +60,15 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {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 PREFIX_LIST = "AWS::EC2::PrefixList";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.+ * MapPublicIpOnLaunch, a route's prior target, a prefix list's prior name, capacity and entries.+ * Internal, like the other {@code __Floci} attributes.*/static final String IN_PLACE_PRIOR_ATTR = "__FlociEc2NetworkPrior";private static final ObjectMapper MAPPER = new ObjectMapper();@@ -76,7 +82,8 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {@Overridepublic Set<String> resourceTypes() {- return Set.of(SUBNET, INTERNET_GATEWAY, ROUTE_TABLE, ROUTE, NAT_GATEWAY, EIP, SUBNET_ROUTE_TABLE_ASSOCIATION);+ return Set.of(SUBNET, INTERNET_GATEWAY, ROUTE_TABLE, ROUTE, NAT_GATEWAY, EIP, PREFIX_LIST,+ SUBNET_ROUTE_TABLE_ASSOCIATION);}@Override@@ -89,6 +96,7 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {case ROUTE -> provisionRoute(r, props, ctx);case NAT_GATEWAY -> provisionNatGateway(r, props, ctx);case EIP -> provisionEip(r, props, ctx);+ case PREFIX_LIST -> provisionPrefixList(r, props, ctx);case SUBNET_ROUTE_TABLE_ASSOCIATION -> provisionSubnetRouteTableAssociation(r, props, ctx);default -> throw new IllegalStateException("Ec2NetworkCfnProvisioner cannot handle " + r.getResourceType());}@@ -122,9 +130,10 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {/*** 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; the snapshot is- * removed only after the restore succeeds, so a restore that throws keeps it for a- * ContinueUpdateRollback retry. Without either, the update changed nothing about the entity.+ * route's target, a prefix list's name, capacity or entries) is put back from the snapshot+ * taken before the change; the snapshot is removed only after the restore succeeds, so a+ * restore that throws keeps it for a ContinueUpdateRollback retry. 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.@@ -171,6 +180,19 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {if (prior.has("mapPublicIpOnLaunch")) {ec2Service.modifySubnetAttribute(region, entityId, "mapPublicIpOnLaunch", prior.get("mapPublicIpOnLaunch").asText());}+ if (prior.has("prefixList")) {+ // Putting the entries back is a modification like any other, so the list moves on to a+ // new version rather than returning to the old one, and Fn::GetAtt Version follows it.+ JsonNode before = prior.get("prefixList");+ List<PrefixListEntry> entries = new ArrayList<>();+ before.path("entries").forEach(entry -> entries.add(+ new PrefixListEntry(entry.path("cidr").asText(), entry.path("description").asText(null))));+ ManagedPrefixList current = ec2Service.describeManagedPrefixLists(region, List.of(entityId), Map.of())+ .getFirst();+ ManagedPrefixList restored = modifyPrefixList(region, current, before.path("name").asText(),+ before.path("maxEntries").asInt(), EntryChanges.between(current.currentEntries(), entries));+ resource.getAttributes().put("Version", Long.toString(restored.getVersion()));+ }if (prior.has("route")) {ObjectNode target = (ObjectNode) prior.get("route");String routeTableId = target.path("routeTableId").asText();@@ -239,6 +261,8 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {case NAT_GATEWAY -> CfnDeletes.safeDelete("NAT gateway", physicalId,() -> ec2Service.deleteNatGateway(region, physicalId), "NatGatewayNotFound");case EIP -> releaseByPublicIp(physicalId, region);+ case PREFIX_LIST -> CfnDeletes.safeDelete("prefix list", physicalId,+ () -> ec2Service.deleteManagedPrefixList(region, physicalId), "InvalidPrefixListID.NotFound");case SUBNET_ROUTE_TABLE_ASSOCIATION -> CfnDeletes.safeDelete("route table association", physicalId,() -> ec2Service.disassociateRouteTable(region, physicalId), "InvalidAssociationID.NotFound");default -> { }@@ -344,6 +368,11 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {.findFirst().orElse(null), "NatGatewayNotFound", natGatewayId);}+ private ManagedPrefixList findPrefixList(String prefixListId, String region) {+ return tolerateNotFound(() -> ec2Service.describeManagedPrefixLists(region, List.of(prefixListId), Map.of())+ .stream().findFirst().orElse(null), "InvalidPrefixListID.NotFound", prefixListId);+ }+private Address findAddress(String allocationId, String publicIp, String region) {List<Address> matches = allocationId != null? ec2Service.describeAddresses(region, List.of(allocationId), Map.of())@@ -609,4 +638,209 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {() -> ec2Service.releaseAddress(ctx.region(), addr.getAllocationId()), () -> undoInPlace(r),() -> applyTags(r, existing != null, addr.getAllocationId(), existing != null ? existing.getTags() : List.of(), props, ctx));}++ /**+ * A customer-managed prefix list. Its schema has no create-only property, so an update changes+ * the list it already has in place, and only a list gone out of band is created anew. MaxEntries+ * is required to create a list; an update that leaves it out keeps the list's capacity.+ */+ private void provisionPrefixList(StackResource r, JsonNode props, ProvisionContext ctx) {+ String name = ctx.resolveOptional(props, "PrefixListName");+ String family = ctx.resolveOptional(props, "AddressFamily");+ require(PREFIX_LIST, "PrefixListName", name);+ require(PREFIX_LIST, "AddressFamily", family);+ Integer maxEntries = ctx.resolveOptionalInt(props, "MaxEntries");+ List<PrefixListEntry> entries = prefixListEntries(props, ctx);+ ManagedPrefixList existing = ctx.isUpdate() ? findPrefixList(ctx.priorPhysicalId(), ctx.region()) : null;+ if (existing == null) {+ if (maxEntries == null) {+ throw new AwsException("ValidationError", PREFIX_LIST + " requires MaxEntries", 400);+ }+ ManagedPrefixList created = ec2Service.createManagedPrefixList(ctx.region(), name, family, maxEntries,+ entries == null ? List.of() : entries, List.of());+ setPrefixListAttributes(r, created);+ // Tags go through CreateTags, as on the other types here, so EC2 checks them all; a tag it+ // refuses removes the new list again.+ CfnRollback.guarded(r, ctx, true,+ () -> ec2Service.deleteManagedPrefixList(ctx.region(), created.getPrefixListId()),+ () -> undoInPlace(r), () -> applyTags(r, false, created.getPrefixListId(), List.of(), props, ctx));+ } else {+ updatePrefixList(r, existing, name, family,+ maxEntries != null ? maxEntries : existing.getMaxEntries(), entries, props, ctx);+ setPrefixListAttributes(r, ec2Service.describeManagedPrefixLists(ctx.region(),+ List.of(existing.getPrefixListId()), Map.of()).getFirst());+ }+ }++ private static void setPrefixListAttributes(StackResource r, ManagedPrefixList list) {+ r.setPhysicalId(list.getPrefixListId());+ r.getAttributes().put("PrefixListId", list.getPrefixListId());+ r.getAttributes().put("Arn", list.getPrefixListArn());+ r.getAttributes().put("OwnerId", list.getOwnerId());+ r.getAttributes().put("Version", Long.toString(list.getVersion()));+ }++ /**+ * Applies an update to a kept prefix list. Two changes fail it before anything is touched: another+ * AddressFamily, which EC2 has no way to change on an existing list, and a new MaxEntries together+ * with changed Entries, which CloudFormation does not apply in one update. The tags go first and+ * the ModifyManagedPrefixList calls last, so a failure undoes at most the tags and leaves the+ * list on the version it had.+ *+ * <p>Entries and Tags are each brought to the template only when it declares them, or the+ * previous template did: a template that drops them clears them, and entries or tags no template+ * ever declared are left alone. The other types here keep their tags when Tags is dropped.+ */+ private void updatePrefixList(StackResource r, ManagedPrefixList existing, String name, String family,+ int maxEntries, List<PrefixListEntry> entries, JsonNode props, ProvisionContext ctx) {+ if (!family.equals(existing.getAddressFamily())) {+ throw new AwsException("ValidationError", PREFIX_LIST + " cannot change the AddressFamily of prefix list "+ + existing.getPrefixListId() + " from " + existing.getAddressFamily() + " to " + family, 400);+ }+ List<PrefixListEntry> desired = entries != null ? entries+ : ctx.previouslyDeclared("Entries") ? List.of() : existing.currentEntries();+ EntryChanges changes = EntryChanges.between(existing.currentEntries(), desired);+ boolean resized = !Objects.equals(maxEntries, existing.getMaxEntries());+ if (!changes.isEmpty() && resized) {+ throw new AwsException("ValidationError", PREFIX_LIST + " cannot change MaxEntries (from "+ + existing.getMaxEntries() + " to " + maxEntries + ") and Entries ("+ + (changes.add().size() + changes.readd().size()) + " to add, "+ + (changes.remove().size() + changes.redescribe().size()) + " to remove) in the same update", 400);+ }+ String prefixListId = existing.getPrefixListId();+ if (!changes.isEmpty() || resized || !name.equals(existing.getPrefixListName())) {+ ObjectNode prior = inPlacePrior(r, prefixListId, ctx);+ ObjectNode before = prior.putObject("prefixList");+ before.put("name", existing.getPrefixListName());+ before.put("maxEntries", existing.getMaxEntries());+ ArrayNode saved = before.putArray("entries");+ for (PrefixListEntry entry : existing.currentEntries()) {+ ObjectNode row = saved.addObject().put("cidr", entry.getCidr());+ if (entry.getDescription() != null) {+ row.put("description", entry.getDescription());+ }+ }+ writeInPlacePrior(r, prior);+ }+ JsonNode desiredTags = !props.has("Tags") && ctx.previouslyDeclared("Tags") ? untagged(props) : props;+ CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> {+ applyTags(r, true, prefixListId, existing.getTags(), desiredTags, ctx);+ modifyPrefixList(ctx.region(), existing, name, maxEntries, changes);+ });+ }++ /** {@code props} with an empty Tags list, which removes the tags a previous template declared. */+ private static JsonNode untagged(JsonNode props) {+ ObjectNode copy = props.deepCopy();+ copy.putArray("Tags");+ return copy;+ }++ /**+ * Gives a prefix list {@code name} and {@code maxEntries} and applies {@code changes}, or does+ * nothing when none of them changes it. EC2 refuses a request that removes and adds the same CIDR,+ * which is how an entry's description changes, so such an entry is added back by a second call.+ * The first call carries everything EC2 could refuse, and the capacity the second needs is checked+ * before the first, so a change EC2 refuses leaves the list as it was; only another change to the+ * list landing between the two calls can still fail the second. Each call that changes entries+ * makes a version.+ */+ private ManagedPrefixList modifyPrefixList(String region, ManagedPrefixList list, String name, int maxEntries,+ EntryChanges changes) {+ boolean resized = !Objects.equals(maxEntries, list.getMaxEntries());+ if (changes.isEmpty() && !resized && name.equals(list.getPrefixListName())) {+ return list;+ }+ if (!changes.readd().isEmpty()) {+ int capacity = resized ? maxEntries : list.getMaxEntries();+ int after = list.currentEntries().size() - changes.remove().size() - changes.redescribe().size()+ + changes.add().size() + changes.readd().size();+ if (after > capacity) {+ throw new AwsException("InvalidParameterValue",+ "The number of entries exceeds the maximum of " + capacity + ".", 400);+ }+ }+ List<String> removals = new ArrayList<>(changes.remove());+ removals.addAll(changes.redescribe());+ ManagedPrefixList current = ec2Service.modifyManagedPrefixList(region, list.getPrefixListId(),+ list.getVersion(), name, resized ? maxEntries : null, changes.add(), removals);+ if (!changes.readd().isEmpty()) {+ current = ec2Service.modifyManagedPrefixList(region, current.getPrefixListId(), current.getVersion(),+ null, null, changes.readd(), List.of());+ }+ return current;+ }++ /**+ * The template's Entries, with what {@code AWS::NoValue} stands for left out, or null when it does+ * not declare them. A CIDR is passed on as written, as Floci's CreateManagedPrefixList takes it.+ */+ private static List<PrefixListEntry> prefixListEntries(JsonNode props, ProvisionContext ctx) {+ JsonNode rows = props.has("Entries") ? ctx.engine().resolveNodeOmittingNoValue(props.get("Entries")) : null;+ if (rows == null || rows.isNull() || rows.isMissingNode()) {+ return null;+ }+ if (!rows.isArray()) {+ throw new AwsException("ValidationError", PREFIX_LIST + " Entries must be a list", 400);+ }+ List<PrefixListEntry> entries = new ArrayList<>();+ for (JsonNode row : rows) {+ String cidr = row.path("Cidr").asText(null);+ require(PREFIX_LIST, "Entries.Cidr", cidr);+ entries.add(new PrefixListEntry(cidr, row.path("Description").asText(null)));+ }+ return entries;+ }++ /**+ * What takes a prefix list from its current entries to the desired ones: the entries to add and the+ * CIDRs to remove, with an entry whose block is both removed and added back (a changed description)+ * kept apart as a CIDR to {@code redescribe} and an entry to {@code readd}. An entry matches when its+ * CIDR is the same block and its description is the same, so a CIDR written with host bits does not+ * read as a change.+ */+ private record EntryChanges(List<PrefixListEntry> add, List<String> remove, List<String> redescribe,+ List<PrefixListEntry> readd) {++ static EntryChanges between(List<PrefixListEntry> current, List<PrefixListEntry> desired) {+ Set<List<String>> held = current.stream().map(EntryChanges::key).collect(Collectors.toSet());+ Set<List<String>> wanted = desired.stream().map(EntryChanges::key).collect(Collectors.toSet());+ List<PrefixListEntry> leaving = current.stream().filter(entry -> !wanted.contains(key(entry))).toList();+ List<PrefixListEntry> arriving = desired.stream().filter(entry -> !held.contains(key(entry))).toList();+ Set<String> leavingBlocks = leaving.stream().map(entry -> block(entry.getCidr())).collect(Collectors.toSet());+ Set<String> arrivingBlocks = arriving.stream().map(entry -> block(entry.getCidr())).collect(Collectors.toSet());+ List<PrefixListEntry> add = new ArrayList<>();+ List<PrefixListEntry> readd = new ArrayList<>();+ for (PrefixListEntry entry : arriving) {+ if (leavingBlocks.contains(block(entry.getCidr()))) {+ readd.add(entry);+ } else {+ add.add(entry);+ }+ }+ List<String> remove = new ArrayList<>();+ List<String> redescribe = new ArrayList<>();+ for (PrefixListEntry entry : leaving) {+ if (arrivingBlocks.contains(block(entry.getCidr()))) {+ redescribe.add(entry.getCidr());+ } else {+ remove.add(entry.getCidr());+ }+ }+ return new EntryChanges(add, remove, redescribe, readd);+ }++ boolean isEmpty() {+ return add.isEmpty() && remove.isEmpty() && redescribe.isEmpty() && readd.isEmpty();+ }++ /** An entry's block and description; a list, which unlike {@code List.of} holds a null description. */+ private static List<String> key(PrefixListEntry entry) {+ return Arrays.asList(block(entry.getCidr()), entry.getDescription());+ }++ private static String block(String cidr) {+ return CidrCanonicalizer.canonicalize(cidr).orElse(cidr);+ }+ }}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisioner.javaindex 7fa413e23f..1871d30024 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisioner.java@@ -262,17 +262,17 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {ctx, r.getLogicalId());String protocol = ctx.resolveOptional(props, "Protocol");String protocolVersion = ctx.resolveOptional(props, "ProtocolVersion");- Integer port = optionalInt(props, ctx, "Port");+ Integer port = ctx.resolveOptionalInt(props, "Port");String vpcId = ctx.resolveOptional(props, "VpcId");String targetType = ctx.resolveOptional(props, "TargetType");String hcProtocol = ctx.resolveOptional(props, "HealthCheckProtocol");String hcPort = ctx.resolveOptional(props, "HealthCheckPort");Boolean hcEnabled = parseBooleanOrNull(ctx.resolveOptional(props, "HealthCheckEnabled"));String hcPath = ctx.resolveOptional(props, "HealthCheckPath");- Integer hcInterval = optionalInt(props, ctx, "HealthCheckIntervalSeconds");- Integer hcTimeout = optionalInt(props, ctx, "HealthCheckTimeoutSeconds");- Integer healthyThreshold = optionalInt(props, ctx, "HealthyThresholdCount");- Integer unhealthyThreshold = optionalInt(props, ctx, "UnhealthyThresholdCount");+ Integer hcInterval = ctx.resolveOptionalInt(props, "HealthCheckIntervalSeconds");+ Integer hcTimeout = ctx.resolveOptionalInt(props, "HealthCheckTimeoutSeconds");+ Integer healthyThreshold = ctx.resolveOptionalInt(props, "HealthyThresholdCount");+ Integer unhealthyThreshold = ctx.resolveOptionalInt(props, "UnhealthyThresholdCount");String matcher = parseMatcher(props, ctx);String ipAddressType = ctx.resolveOptional(props, "IpAddressType");Map<String, String> tags = ctx.resolveTags(props, "Tags");@@ -313,7 +313,7 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {boolean gateway = lb != null && "gateway".equals(lb.getType());String protocol = gateway ? ctx.resolveOptional(props, "Protocol"): ctx.resolveOrDefault(props, "Protocol", "HTTP");- Integer port = gateway ? optionalInt(props, ctx, "Port")+ Integer port = gateway ? ctx.resolveOptionalInt(props, "Port"): Integer.valueOf(parseInt(ctx.resolveOptional(props, "Port"), "Port", 80));String sslPolicy = ctx.resolveOptional(props, "SslPolicy");List<String> certificates = parseCertificates(props, ctx);@@ -581,26 +581,6 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {}}- /**- * An omitted property stays unset for the service to default, and so does one an intrinsic resolves- * to nothing: the engine resolves {@code AWS::NoValue} to blank, which is how the common- * {@code Fn::If [cond, value, AWS::NoValue]} drops a property. A value written into the template- * has to be an integer, a literal blank included, as CloudFormation's schema type check requires.- * A {@code Ref} to a parameter whose value is blank cannot be told apart from {@code AWS::NoValue}- * here, so it stays unset too.- */- private static Integer optionalInt(JsonNode props, ProvisionContext ctx, String property) {- String value = ctx.resolveOptional(props, property);- if (value == null || (value.isBlank() && !props.get(property).isTextual())) {- return null;- }- try {- return Integer.parseInt(value.trim());- } catch (NumberFormatException e) {- throw notAnInteger(property);- }- }-private static AwsException notAnInteger(String property) {return new AwsException("ValidationError", "Value of property " + property + " must be an integer.", 400);}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.javaindex 31784aa80e..f718e86843 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.cloudformation.provisioners;import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;@@ -122,6 +123,26 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regioreturn engine.resolve(props.get(name));}+ /**+ * Resolves an optional integer property, or null when it is absent or explicitly null. One an+ * intrinsic resolves to nothing stays null too: the engine resolves {@code AWS::NoValue} to blank,+ * which is how the common {@code Fn::If [cond, value, AWS::NoValue]} drops a property. A value+ * written into the template has to be an integer, a literal blank included, as CloudFormation's+ * schema type check requires. A {@code Ref} to a parameter whose value is blank cannot be told+ * apart from {@code AWS::NoValue} here, so it stays null as well.+ */+ public Integer resolveOptionalInt(JsonNode props, String name) {+ String value = resolveOptional(props, name);+ if (value == null || (value.isBlank() && !props.get(name).isTextual())) {+ return null;+ }+ try {+ return Integer.valueOf(value.trim());+ } catch (NumberFormatException e) {+ throw new AwsException("ValidationError", "Value of property " + name + " must be an integer.", 400);+ }+ }+/*** Resolves an optional property through the engine, falling back to {@code defaultValue} when it* is absent or resolves to blank. Shared by the per-service provisioners so none carries its owndiff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.jsonindex 69b1905f98..4d5d6d10ed 100644--- a/src/main/resources/cloudformation/create-only-properties.json+++ b/src/main/resources/cloudformation/create-only-properties.json@@ -279,6 +279,7 @@"RuleNumber","NetworkAclId"],+ "AWS::EC2::PrefixList": [],"AWS::EC2::Route": ["RouteTableId","DestinationCidrBlock",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.javaindex e66cd52957..79867d3b7f 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2NetworkingIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2NetworkingIntegrationTest.java@@ -27,7 +27,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;* 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+ * fails, and asserts the rollback puts both back. A third provisions a prefix list that a route+ * targets, updates it in place and rolls a change 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.*/@@ -113,6 +114,213 @@ class CloudFormationEc2NetworkingIntegrationTest {return ec2("DescribeSubnets", Map.of("SubnetId.1", subnetId));}+ private static final String PREFIX_LIST_STACK = "ec2-prefix-list-it";++ /**+ * A prefix list and a route to it through an internet gateway, the way a template sends a set of+ * CIDRs out of a VPC. {@code tags} is the Tags list, or empty for none; {@code failing} adds a+ * resource that cannot be created once the prefix list is done.+ */+ private static String prefixListTemplate(String vpcId, String family, int maxEntries, String entries,+ String tags, boolean failing) {+ String boom = failing+ ? ",\n \"Boom\": {\"Type\": \"AWS::SecretsManager::Secret\", \"DependsOn\": \"Firewall\","+ + " \"Properties\": {\"SecretString\": \"x\", \"GenerateSecretString\": {\"SecretStringTemplate\": \"{}\", \"GenerateStringKey\": \"p\"}}}"+ : "";+ return """+ {+ "Resources": {+ "Firewall": {"Type": "AWS::EC2::PrefixList",+ "Properties": {"PrefixListName": "office-egress", "AddressFamily": "%2$s",+ "MaxEntries": %3$d, "Entries": %4$s%5$s}},+ "Igw": {"Type": "AWS::EC2::InternetGateway"},+ "Attach": {"Type": "AWS::EC2::VPCGatewayAttachment",+ "Properties": {"VpcId": "%1$s", "InternetGatewayId": {"Ref": "Igw"}}},+ "Rt": {"Type": "AWS::EC2::RouteTable", "Properties": {"VpcId": "%1$s"}},+ "OfficeRoute": {"Type": "AWS::EC2::Route", "DependsOn": "Attach",+ "Properties": {"RouteTableId": {"Ref": "Rt"}, "DestinationPrefixListId": {"Ref": "Firewall"},+ "GatewayId": {"Ref": "Igw"}}}%6$s+ },+ "Outputs": {+ "Ref": {"Value": {"Ref": "Firewall"}},+ "PrefixListId": {"Value": {"Fn::GetAtt": ["Firewall", "PrefixListId"]}},+ "Arn": {"Value": {"Fn::GetAtt": ["Firewall", "Arn"]}},+ "OwnerId": {"Value": {"Fn::GetAtt": ["Firewall", "OwnerId"]}},+ "RtId": {"Value": {"Ref": "Rt"}},+ "RouteRef": {"Value": {"Ref": "OfficeRoute"}}+ }+ }+ """.formatted(vpcId, family, maxEntries, entries, tags.isEmpty() ? "" : ", \"Tags\": " + tags, boom);+ }++ @Test+ void aPrefixListIsARealListThatARouteCanTargetAndUpdatesInPlace() {+ String vpcId = between(ec2("CreateVpc", Map.of("CidrBlock", "10.43.0.0/16")), "<vpcId>", "</vpcId>");+ String office = "[{\"Cidr\": \"192.0.2.0/24\", \"Description\": \"office\"}]";+ String offices = "[{\"Cidr\": \"192.0.2.0/24\", \"Description\": \"head office\"},"+ + " {\"Cidr\": \"198.51.100.0/24\", \"Description\": \"branch\"}]";+ String team = "[{\"Key\": \"team\", \"Value\": \"network\"}]";+ cloudFormation(PREFIX_LIST_STACK, "CreateStack", prefixListTemplate(vpcId, "IPv4", 2, office, team, false));++ Map<String, String> out = XmlParser.extractPairs(describeStacks(PREFIX_LIST_STACK, "CREATE_COMPLETE"),+ "Outputs", "OutputKey", "OutputValue");+ String id = out.get("Ref");+ assertTrue(id.startsWith("pl-"), "Ref of a prefix list is its EC2 id: " + id);+ assertEquals(id, out.get("PrefixListId"));+ assertEquals("arn:aws:ec2:us-east-1:" + out.get("OwnerId") + ":prefix-list/" + id, out.get("Arn"));+ String list = prefixListXml(id);+ assertTrue(list.contains("<prefixListName>office-egress</prefixListName>") && list.contains("<version>1</version>")+ && list.contains("<maxEntries>2</maxEntries>"), list);+ assertTrue(list.contains("<key>team</key>") && list.contains("<value>network</value>"), "tags must reach EC2: " + list);+ assertTrue(entriesXml(id).contains("<cidr>192.0.2.0/24</cidr>"));+ assertEquals(out.get("RtId") + "|" + id, out.get("RouteRef"), "the route is keyed by the list it targets");+ String routes = ec2("DescribeRouteTables", Map.of("RouteTableId.1", out.get("RtId")));+ assertTrue(routes.contains("<destinationPrefixListId>" + id + "</destinationPrefixListId>"), routes);++ // Entries change in place. A changed description is a removal and then an addition, two+ // EC2 calls because EC2 refuses one that removes and adds the same CIDR, so version 3.+ cloudFormation(PREFIX_LIST_STACK, "UpdateStack", prefixListTemplate(vpcId, "IPv4", 2, offices, team, false));+ assertEquals(id, XmlParser.extractPairs(describeStacks(PREFIX_LIST_STACK, "UPDATE_COMPLETE"),+ "Outputs", "OutputKey", "OutputValue").get("Ref"));+ assertTrue(prefixListXml(id).contains("<version>3</version>"));+ String entries = entriesXml(id);+ assertTrue(entries.contains("<description>head office</description>") && entries.contains("198.51.100.0/24"), entries);++ // Capacity alone changes in place and makes no new version.+ cloudFormation(PREFIX_LIST_STACK, "UpdateStack", prefixListTemplate(vpcId, "IPv4", 3, offices, team, false));+ describeStacks(PREFIX_LIST_STACK, "UPDATE_COMPLETE");+ list = prefixListXml(id);+ assertTrue(list.contains("<maxEntries>3</maxEntries>") && list.contains("<version>3</version>"), list);++ // Capacity and entries together, and another address family, fail the update and change nothing.+ cloudFormation(PREFIX_LIST_STACK, "UpdateStack", prefixListTemplate(vpcId, "IPv4", 4, office, team, false));+ describeStacks(PREFIX_LIST_STACK, "UPDATE_ROLLBACK_COMPLETE");+ String reason = CfnStackWaits.failedResourceReason(PREFIX_LIST_STACK, CFN_AUTH);+ assertTrue(reason.contains("cannot change MaxEntries (from 3 to 4) and Entries"), reason);+ cloudFormation(PREFIX_LIST_STACK, "UpdateStack", prefixListTemplate(vpcId, "IPv6", 3, offices, team, false));+ describeStacks(PREFIX_LIST_STACK, "UPDATE_ROLLBACK_COMPLETE");+ reason = CfnStackWaits.failedResourceReason(PREFIX_LIST_STACK, CFN_AUTH);+ assertTrue(reason.contains("cannot change the AddressFamily of prefix list " + id + " from IPv4 to IPv6"), reason);+ list = prefixListXml(id);+ assertTrue(list.contains("<maxEntries>3</maxEntries>") && list.contains("<version>3</version>")+ && list.contains("<addressFamily>IPv4</addressFamily>"), list);++ // An entry and tag change next to a resource that fails is put back.+ cloudFormation(PREFIX_LIST_STACK, "UpdateStack", prefixListTemplate(vpcId, "IPv4", 3, office,+ "[{\"Key\": \"team\", \"Value\": \"platform\"}]", true));+ describeStacks(PREFIX_LIST_STACK, "UPDATE_ROLLBACK_COMPLETE");+ entries = entriesXml(id);+ assertTrue(entries.contains("<description>head office</description>") && entries.contains("198.51.100.0/24"),+ "the prior entries must be back: " + entries);+ list = prefixListXml(id);+ assertTrue(list.contains("<value>network</value>") && !list.contains("<value>platform</value>"),+ "the prior tags must be back: " + list);++ // A rename is no replacement: the change set modifies the list alone, and the route that+ // targets it is left as it is.+ String renamed = prefixListTemplate(vpcId, "IPv4", 3, offices, team, false)+ .replace("\"office-egress\"", "\"office-egress-renamed\"");+ changeSet("CreateChangeSet", "rename", renamed);+ String preview = changeSet("DescribeChangeSet", "rename", null);+ assertTrue(preview.contains("<LogicalResourceId>Firewall</LogicalResourceId>")+ && preview.contains("<Replacement>False</Replacement>") && !preview.contains("<Replacement>True</Replacement>")+ && !preview.contains("<LogicalResourceId>OfficeRoute</LogicalResourceId>"), preview);+ changeSet("ExecuteChangeSet", "rename", null);+ assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(PREFIX_LIST_STACK, CFN_AUTH).status());+ assertEquals(id, XmlParser.extractPairs(describeStacks(PREFIX_LIST_STACK, "UPDATE_COMPLETE"),+ "Outputs", "OutputKey", "OutputValue").get("Ref"));+ assertTrue(prefixListXml(id).contains("<prefixListName>office-egress-renamed</prefixListName>"));++ // A template that drops Tags removes them.+ cloudFormation(PREFIX_LIST_STACK, "UpdateStack", prefixListTemplate(vpcId, "IPv4", 3, offices, "", false)+ .replace("\"office-egress\"", "\"office-egress-renamed\""));+ describeStacks(PREFIX_LIST_STACK, "UPDATE_COMPLETE");+ assertFalse(prefixListXml(id).contains("<key>team</key>"), "the dropped tags must be removed");++ cloudFormation(PREFIX_LIST_STACK, "DeleteStack", null);+ CfnStackWaits.awaitStackDeleted(PREFIX_LIST_STACK);+ given().contentType("application/x-www-form-urlencoded").header("Authorization", EC2_AUTH)+ .formParam("Action", "GetManagedPrefixListEntries").formParam("Version", "2016-11-15")+ .formParam("PrefixListId", id)+ .when().post("/").then().statusCode(400).body(containsString("InvalidPrefixListID.NotFound"));+ ec2("DeleteVpc", Map.of("VpcId", vpcId));+ }++ /**+ * {@code Fn::GetAtt Version} is the list's version, and a resource whose integer property reads+ * it follows the list: here a second list sized by the first one's version.+ */+ @Test+ void aPrefixListVersionCanSizeAnotherList() {+ String stack = "ec2-prefix-list-version-it";+ String template = """+ {+ "Resources": {+ "First": {"Type": "AWS::EC2::PrefixList",+ "Properties": {"PrefixListName": "version-source", "AddressFamily": "IPv4", "MaxEntries": 2,+ "Entries": %s}},+ "Second": {"Type": "AWS::EC2::PrefixList",+ "Properties": {"PrefixListName": "version-sized", "AddressFamily": "IPv4",+ "MaxEntries": {"Fn::GetAtt": ["First", "Version"]}}}+ },+ "Outputs": {"SecondId": {"Value": {"Ref": "Second"}}}+ }+ """;+ cloudFormation(stack, "CreateStack", template.formatted("[{\"Cidr\": \"192.0.2.0/24\"}]"));+ String second = XmlParser.extractPairs(describeStacks(stack, "CREATE_COMPLETE"),+ "Outputs", "OutputKey", "OutputValue").get("SecondId");+ assertTrue(prefixListXml(second).contains("<maxEntries>1</maxEntries>"), prefixListXml(second));++ cloudFormation(stack, "UpdateStack",+ template.formatted("[{\"Cidr\": \"192.0.2.0/24\"}, {\"Cidr\": \"198.51.100.0/24\"}]"));+ describeStacks(stack, "UPDATE_COMPLETE");+ assertTrue(prefixListXml(second).contains("<maxEntries>2</maxEntries>"),+ "the first list's new version resizes the second: " + prefixListXml(second));++ cloudFormation(stack, "DeleteStack", null);+ CfnStackWaits.awaitStackDeleted(stack);+ }++ /** EC2 checks a prefix list's tags; one it refuses fails the create and leaves no list behind. */+ @Test+ void aTagEc2RefusesFailsThePrefixListAndLeavesNoList() {+ String stack = "ec2-prefix-list-bad-tag-it";+ cloudFormation(stack, "CreateStack", """+ {"Resources": {"Firewall": {"Type": "AWS::EC2::PrefixList",+ "Properties": {"PrefixListName": "bad-tag-list", "AddressFamily": "IPv4", "MaxEntries": 1,+ "Tags": [{"Key": "%s", "Value": "x"}]}}}}+ """.formatted("k".repeat(129)));++ describeStacks(stack, "ROLLBACK_COMPLETE");+ String reason = CfnStackWaits.failedResourceReason(stack, CFN_AUTH);+ assertTrue(reason.contains("Tag key exceeds the maximum length of 128 characters"), reason);+ assertFalse(ec2("DescribeManagedPrefixLists").contains("bad-tag-list"), "the new list is removed again");+ cloudFormation(stack, "DeleteStack", null);+ CfnStackWaits.awaitStackDeleted(stack);+ }++ /** A change set action on the prefix list stack; {@code templateBody} only for CreateChangeSet. */+ private static String changeSet(String action, String changeSetName, String templateBody) {+ RequestSpecification request = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", action)+ .formParam("StackName", PREFIX_LIST_STACK)+ .formParam("ChangeSetName", changeSetName);+ if (templateBody != null) {+ request.formParam("ChangeSetType", "UPDATE").formParam("TemplateBody", templateBody);+ }+ return request.when().post("/").then().statusCode(200).extract().asString();+ }++ private static String prefixListXml(String prefixListId) {+ return ec2("DescribeManagedPrefixLists", Map.of("PrefixListId.1", prefixListId));+ }++ private static String entriesXml(String prefixListId) {+ return ec2("GetManagedPrefixListEntries", Map.of("PrefixListId", prefixListId));+ }+private static String template(String vpcId, String publicSubnetCidr, String extraSubnetTag) {return """{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.javaindex 2978acd4ee..8e4964a173 100644--- 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@@ -10,7 +10,9 @@ 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.ManagedPrefixList;import io.github.hectorvent.floci.services.ec2.model.NatGateway;+import io.github.hectorvent.floci.services.ec2.model.PrefixListEntry;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;@@ -18,7 +20,10 @@ import io.github.hectorvent.floci.services.ec2.model.Subnet;import io.github.hectorvent.floci.services.ec2.model.Tag;import org.junit.jupiter.api.Test;import org.mockito.ArgumentCaptor;+import org.mockito.invocation.Invocation;+import org.mockito.stubbing.OngoingStubbing;+import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;@@ -35,7 +40,9 @@ import static org.mockito.ArgumentMatchers.eq;import static org.mockito.ArgumentMatchers.isNull;import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.mockingDetails;import static org.mockito.Mockito.never;+import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;@@ -55,6 +62,8 @@ class Ec2NetworkCfnProvisionerTest {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 static final String PREFIX_LIST_ID = "pl-0123456789abcdef0";+ private static final PrefixListEntry OFFICE = new PrefixListEntry("192.0.2.0/24", "office");private final Ec2Service ec2 = mock(Ec2Service.class);private final Ec2NetworkCfnProvisioner provisioner = new Ec2NetworkCfnProvisioner(ec2);@@ -65,14 +74,20 @@ class Ec2NetworkCfnProvisionerTest {}private ProvisionContext ctx(String priorPhysicalId) {+ return ctx(priorPhysicalId, null);+ }++ private ProvisionContext ctx(String priorPhysicalId, JsonNode priorProperties) {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.resolveNodeOmittingNoValue(any())).thenAnswer(inv -> inv.getArgument(0));when(engine.resolveStringList(any())).thenCallRealMethod();- return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);+ return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId, event -> { },+ priorProperties);}private static StackResource resource(String type, String logicalId) {@@ -1004,6 +1019,414 @@ class Ec2NetworkCfnProvisionerTest {verify(ec2, never()).deleteSubnet(any(), any());}+ private static ManagedPrefixList prefixList(long version, int maxEntries, PrefixListEntry... entries) {+ ManagedPrefixList list = new ManagedPrefixList();+ list.setPrefixListId(PREFIX_LIST_ID);+ list.setPrefixListName("firewall");+ list.setPrefixListArn("arn:aws:ec2:us-east-1:000000000000:prefix-list/" + PREFIX_LIST_ID);+ list.setOwnerId("000000000000");+ list.setAddressFamily("IPv4");+ list.setMaxEntries(maxEntries);+ list.setVersion(version);+ list.getEntriesByVersion().put(String.valueOf(version), List.of(entries));+ return list;+ }++ /** PrefixList properties with the given capacity and entries, each a CIDR followed by its description. */+ private ObjectNode prefixListProps(int maxEntries, String... cidrsAndDescriptions) {+ ObjectNode props = mapper.createObjectNode().put("PrefixListName", "firewall").put("AddressFamily", "IPv4")+ .put("MaxEntries", maxEntries);+ ArrayNode entries = props.putArray("Entries");+ for (int i = 0; i + 1 < cidrsAndDescriptions.length; i += 2) {+ entries.addObject().put("Cidr", cidrsAndDescriptions[i]).put("Description", cidrsAndDescriptions[i + 1]);+ }+ return props;+ }++ private static List<String> entryPairs(List<PrefixListEntry> entries) {+ return entries.stream().map(entry -> entry.getCidr() + "=" + entry.getDescription()).toList();+ }++ /** DescribeManagedPrefixLists answers with each state in turn, then keeps answering with the last. */+ private void describesPrefixList(ManagedPrefixList first, ManagedPrefixList... then) {+ OngoingStubbing<List<ManagedPrefixList>> answers =+ when(ec2.describeManagedPrefixLists(REGION, List.of(PREFIX_LIST_ID), Map.of())).thenReturn(List.of(first));+ for (ManagedPrefixList next : then) {+ answers = answers.thenReturn(List.of(next));+ }+ }++ @Test+ void prefixListUsesTheEc2IdAndItsFourRegistryAttributes() {+ ManagedPrefixList created = prefixList(1, 2, new PrefixListEntry("192.0.2.19/24", "office"));+ when(ec2.createManagedPrefixList(eq(REGION), eq("firewall"), eq("IPv4"), eq(2), any(), any())).thenReturn(created);+ StackResource r = resource("AWS::EC2::PrefixList", "Firewall");++ provisioner.provision(r, withTags(prefixListProps(2, "192.0.2.19/24", "office"), "team", "network"), ctx());++ assertEquals(PREFIX_LIST_ID, r.getPhysicalId());+ assertEquals(Map.of("PrefixListId", PREFIX_LIST_ID, "Arn", created.getPrefixListArn(),+ "OwnerId", "000000000000", "Version", "1"), r.getAttributes());+ ArgumentCaptor<List<PrefixListEntry>> entries = ArgumentCaptor.captor();+ verify(ec2).createManagedPrefixList(eq(REGION), eq("firewall"), eq("IPv4"), eq(2), entries.capture(), eq(List.of()));+ assertEquals(List.of("192.0.2.19/24=office"), entryPairs(entries.getValue()), "a CIDR is passed on as written");+ assertEquals(List.of("team=network"), tagsWritten(PREFIX_LIST_ID), "tags go through CreateTags, which checks them");+ }++ @Test+ void prefixListRequiredPropertiesAreValidatedBeforeAnyServiceCall() {+ record Case(ObjectNode props, String expected) { }+ List<Case> cases = List.of(+ new Case(prefixListProps(1).without("PrefixListName"), "AWS::EC2::PrefixList requires PrefixListName"),+ new Case(prefixListProps(1).without("AddressFamily"), "AWS::EC2::PrefixList requires AddressFamily"),+ new Case(prefixListProps(1).without("MaxEntries"), "AWS::EC2::PrefixList requires MaxEntries"),+ new Case(prefixListProps(1).put("MaxEntries", "ten"), "Value of property MaxEntries must be an integer."),+ new Case(prefixListProps(1).put("MaxEntries", ""), "Value of property MaxEntries must be an integer."),+ new Case(withEntry(prefixListProps(1), mapper.createObjectNode().put("Description", "no cidr")),+ "AWS::EC2::PrefixList requires Entries.Cidr"));+ for (Case c : cases) {+ AwsException e = assertThrows(AwsException.class,+ () -> provisioner.provision(resource("AWS::EC2::PrefixList", "Firewall"), c.props(), ctx()), c.expected());+ assertEquals("ValidationError", e.getErrorCode());+ assertEquals(c.expected(), e.getMessage());+ }+ verify(ec2, never()).createManagedPrefixList(any(), any(), any(), any(), any(), any());+ }++ private static ObjectNode withEntry(ObjectNode props, ObjectNode entry) {+ ((ArrayNode) props.get("Entries")).add(entry);+ return props;+ }++ @Test+ void prefixListDeleteToleratesOnlyItsOwnNotFoundCode() {+ provisioner.delete("AWS::EC2::PrefixList", PREFIX_LIST_ID, REGION);+ verify(ec2).deleteManagedPrefixList(REGION, PREFIX_LIST_ID);++ doThrow(new AwsException("InvalidPrefixListID.NotFound", "gone", 400)).when(ec2).deleteManagedPrefixList(REGION, "pl-gone");+ assertDoesNotThrow(() -> provisioner.delete("AWS::EC2::PrefixList", "pl-gone", REGION));+ doThrow(new AwsException("DependencyViolation", "in use", 400)).when(ec2).deleteManagedPrefixList(REGION, "pl-busy");+ AwsException e = assertThrows(AwsException.class, () -> provisioner.delete("AWS::EC2::PrefixList", "pl-busy", REGION));+ assertEquals("DependencyViolation", e.getErrorCode());+ }++ @Test+ void aChangedDescriptionIsAddedBackByASecondCallAfterTheFirstCarriesTheRestAndARollbackDoesTheSame() {+ ManagedPrefixList changed = prefixList(3, 3, new PrefixListEntry("192.0.2.0/24", "head office"),+ new PrefixListEntry("198.51.100.0/24", "branch"));+ describesPrefixList(prefixList(1, 3, OFFICE), changed, changed);+ when(ec2.modifyManagedPrefixList(eq(REGION), eq(PREFIX_LIST_ID), any(), any(), any(), any(), any()))+ .thenReturn(prefixList(2, 3), changed, prefixList(4, 3), prefixList(5, 3, OFFICE));+ StackResource r = prior("AWS::EC2::PrefixList", "Firewall", PREFIX_LIST_ID,+ Map.of("PrefixListId", PREFIX_LIST_ID, "Version", "1"));++ provisioner.provision(r, prefixListProps(3, "192.0.2.0/24", "head office", "198.51.100.0/24", "branch"),+ ctx(PREFIX_LIST_ID));++ assertEquals(PREFIX_LIST_ID, r.getPhysicalId());+ assertEquals("3", r.getAttributes().get("Version"));+ assertEquals(List.of(+ "version=1 name=firewall max=null add=[198.51.100.0/24=branch] remove=[192.0.2.0/24]",+ "version=2 name=null max=null add=[192.0.2.0/24=head office] remove=[]"),+ modifyCalls(), "EC2 refuses one call that removes and adds the same CIDR");++ assertTrue(provisioner.rollbackUpdate(r));++ assertEquals(List.of(+ "version=3 name=firewall max=null add=[] remove=[198.51.100.0/24, 192.0.2.0/24]",+ "version=4 name=null max=null add=[192.0.2.0/24=office] remove=[]"),+ modifyCalls().subList(2, 4));+ assertEquals("5", r.getAttributes().get("Version"), "the restore makes new versions, and Version follows them");+ assertFalse(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));+ }++ @Test+ void aCidrWrittenWithHostBitsIsMatchedByBlockWhenItsDescriptionChanges() {+ describesPrefixList(prefixList(1, 2, new PrefixListEntry("192.0.2.19/24", "office")));+ StackResource r = prior("AWS::EC2::PrefixList", "Firewall", PREFIX_LIST_ID, Map.of("PrefixListId", PREFIX_LIST_ID));+ when(ec2.modifyManagedPrefixList(eq(REGION), eq(PREFIX_LIST_ID), any(), any(), any(), any(), any()))+ .thenReturn(prefixList(2, 2), prefixList(3, 2, new PrefixListEntry("192.0.2.0/24", "head office")));++ provisioner.provision(r, prefixListProps(2, "192.0.2.0/24", "head office"), ctx(PREFIX_LIST_ID));++ assertEquals(List.of(+ "version=1 name=firewall max=null add=[] remove=[192.0.2.19/24]",+ "version=2 name=null max=null add=[192.0.2.0/24=head office] remove=[]"), modifyCalls());+ }++ @Test+ void aDescriptionChangeThatWouldOverflowTheCapacityFailsBeforeAnyCall() {+ ManagedPrefixList current = prefixList(1, 2, OFFICE);+ current.setTags(List.of(new Tag("team", "network")));+ describesPrefixList(current);+ // What EC2 would answer: a removal goes through, an addition past the capacity does not.+ when(ec2.modifyManagedPrefixList(eq(REGION), eq(PREFIX_LIST_ID), any(), any(), any(), any(), any()))+ .thenReturn(prefixList(2, 2))+ .thenThrow(new AwsException("InvalidParameterValue", "The number of entries exceeds the maximum of 2.", 400));+ StackResource r = prior("AWS::EC2::PrefixList", "Firewall", PREFIX_LIST_ID, Map.of("PrefixListId", PREFIX_LIST_ID));+ ObjectNode props = withTags(prefixListProps(2, "192.0.2.0/24", "head office", "198.51.100.0/24", "branch",+ "203.0.113.0/24", "lab"), "team", "platform");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx(PREFIX_LIST_ID)));++ assertEquals("InvalidParameterValue", e.getErrorCode());+ assertEquals("The number of entries exceeds the maximum of 2.", e.getMessage());+ assertEquals(List.of(), modifyCalls(), "the list is never left half changed");+ ArgumentCaptor<List<Tag>> written = ArgumentCaptor.captor();+ verify(ec2, times(2)).createTags(eq(REGION), eq(List.of(PREFIX_LIST_ID)), written.capture());+ assertEquals(List.of("team=network"), pairs(written.getAllValues().get(1)), "the prior tags are written back");+ }++ @Test+ void aRenameKeepsTheVersionAndARollbackPutsTheNameBack() {+ ManagedPrefixList renamed = prefixList(1, 2, OFFICE);+ renamed.setPrefixListName("firewall-renamed");+ describesPrefixList(prefixList(1, 2, OFFICE), renamed, renamed);+ when(ec2.modifyManagedPrefixList(eq(REGION), eq(PREFIX_LIST_ID), any(), any(), any(), any(), any()))+ .thenReturn(renamed, prefixList(1, 2, OFFICE));+ StackResource r = prior("AWS::EC2::PrefixList", "Firewall", PREFIX_LIST_ID, Map.of("PrefixListId", PREFIX_LIST_ID));++ provisioner.provision(r, prefixListProps(2, "192.0.2.0/24", "office").put("PrefixListName", "firewall-renamed"),+ ctx(PREFIX_LIST_ID));++ assertEquals("1", r.getAttributes().get("Version"), "a rename makes no new version");+ assertTrue(provisioner.rollbackUpdate(r));+ assertEquals(List.of("version=1 name=firewall-renamed max=null add=[] remove=[]",+ "version=1 name=firewall max=null add=[] remove=[]"), modifyCalls());+ }++ @Test+ void anUnchangedPrefixListIsKeptWithoutAModifyOrASnapshot() {+ describesPrefixList(prefixList(1, 2, OFFICE));+ StackResource r = prior("AWS::EC2::PrefixList", "Firewall", PREFIX_LIST_ID, Map.of("PrefixListId", PREFIX_LIST_ID));++ provisioner.provision(r, prefixListProps(2, "192.0.2.19/24", "office"), ctx(PREFIX_LIST_ID));++ assertEquals(PREFIX_LIST_ID, r.getPhysicalId());+ assertEquals("1", r.getAttributes().get("Version"));+ assertFalse(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR),+ "a CIDR written with host bits is the same block, not a change");+ verify(ec2, never()).modifyManagedPrefixList(any(), any(), any(), any(), any(), any(), any());+ verify(ec2, never()).createManagedPrefixList(any(), any(), any(), any(), any(), any());+ }++ @Test+ void aResizeAloneChangesOnlyMaxEntriesAndARollbackPutsTheCapacityBack() {+ ManagedPrefixList resized = prefixList(1, 5, OFFICE);+ describesPrefixList(prefixList(1, 2, OFFICE), resized, resized);+ when(ec2.modifyManagedPrefixList(eq(REGION), eq(PREFIX_LIST_ID), any(), any(), any(), any(), any()))+ .thenReturn(resized, prefixList(1, 2, OFFICE));+ StackResource r = prior("AWS::EC2::PrefixList", "Firewall", PREFIX_LIST_ID, Map.of("PrefixListId", PREFIX_LIST_ID));++ provisioner.provision(r, prefixListProps(5, "192.0.2.0/24", "office"), ctx(PREFIX_LIST_ID));+ assertEquals("1", r.getAttributes().get("Version"), "only an entry change makes a new version");+ assertTrue(provisioner.rollbackUpdate(r));++ assertEquals(List.of("version=1 name=firewall max=5 add=[] remove=[]",+ "version=1 name=firewall max=2 add=[] remove=[]"), modifyCalls());+ }++ @Test+ void anUpdateWithoutMaxEntriesKeepsTheCapacity() {+ describesPrefixList(prefixList(1, 5, OFFICE));+ StackResource r = prior("AWS::EC2::PrefixList", "Firewall", PREFIX_LIST_ID, Map.of("PrefixListId", PREFIX_LIST_ID));++ provisioner.provision(r, prefixListProps(5, "192.0.2.0/24", "office").without("MaxEntries"), ctx(PREFIX_LIST_ID));++ verify(ec2, never()).modifyManagedPrefixList(any(), any(), any(), any(), any(), any(), any());+ }++ @Test+ void anAddressFamilyChangeFailsTheUpdateBeforeAnythingChanges() {+ describesPrefixList(prefixList(1, 2, OFFICE));+ StackResource r = prior("AWS::EC2::PrefixList", "Firewall", PREFIX_LIST_ID, Map.of("PrefixListId", PREFIX_LIST_ID));+ ObjectNode props = withTags(prefixListProps(2), "team", "network").put("AddressFamily", "IPv6");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx(PREFIX_LIST_ID)));++ assertEquals("ValidationError", e.getErrorCode());+ assertEquals("AWS::EC2::PrefixList cannot change the AddressFamily of prefix list " + PREFIX_LIST_ID+ + " from IPv4 to IPv6", e.getMessage());+ verify(ec2, never()).modifyManagedPrefixList(any(), any(), any(), any(), any(), any(), any());+ verify(ec2, never()).createTags(any(), any(), any());+ verify(ec2, never()).createManagedPrefixList(any(), any(), any(), any(), any(), any());+ assertFalse(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));+ }++ @Test+ void changingMaxEntriesAndEntriesTogetherFailsTheUpdateBeforeAnythingChanges() {+ describesPrefixList(prefixList(1, 2, OFFICE));+ StackResource r = prior("AWS::EC2::PrefixList", "Firewall", PREFIX_LIST_ID, Map.of("PrefixListId", PREFIX_LIST_ID));+ ObjectNode props = withTags(prefixListProps(3, "192.0.2.0/24", "office", "198.51.100.0/24", "branch"),+ "team", "network");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx(PREFIX_LIST_ID)));++ assertEquals("ValidationError", e.getErrorCode());+ assertEquals("AWS::EC2::PrefixList cannot change MaxEntries (from 2 to 3) and Entries (1 to add, 0 to remove)"+ + " in the same update", e.getMessage());+ verify(ec2, never()).modifyManagedPrefixList(any(), any(), any(), any(), any(), any(), any());+ verify(ec2, never()).createTags(any(), any(), any());+ assertFalse(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));+ }++ @Test+ void aPrefixListGoneOutOfBandIsCreatedAnewAndThePriorIdIsOwedToCleanup() {+ when(ec2.describeManagedPrefixLists(REGION, List.of("pl-gone"), Map.of()))+ .thenThrow(new AwsException("InvalidPrefixListID.NotFound", "gone", 400));+ when(ec2.createManagedPrefixList(eq(REGION), eq("firewall"), eq("IPv4"), eq(2), any(), any()))+ .thenReturn(prefixList(1, 2, OFFICE));+ StackResource r = prior("AWS::EC2::PrefixList", "Firewall", "pl-gone", Map.of("PrefixListId", "pl-gone"));++ provisioner.provision(r, prefixListProps(2, "192.0.2.0/24", "office"), ctx("pl-gone"));++ assertEquals(PREFIX_LIST_ID, r.getPhysicalId());+ assertEquals("pl-gone", provisioner.updateCleanupPhysicalId(r));+ }++ @Test+ void droppingTheTagsThePreviousTemplateDeclaredRemovesThem() {+ ManagedPrefixList current = prefixList(1, 2, OFFICE);+ current.setTags(List.of(new Tag("team", "network"), new Tag("aws:cloudformation:stack-id", "stack")));+ describesPrefixList(current);+ StackResource r = prior("AWS::EC2::PrefixList", "Firewall", PREFIX_LIST_ID, Map.of("PrefixListId", PREFIX_LIST_ID));+ JsonNode previous = withTags(prefixListProps(2, "192.0.2.0/24", "office"), "team", "network");++ provisioner.provision(r, prefixListProps(2, "192.0.2.0/24", "office"), ctx(PREFIX_LIST_ID, previous));++ ArgumentCaptor<List<Tag>> removed = ArgumentCaptor.captor();+ verify(ec2).deleteTags(eq(REGION), eq(List.of(PREFIX_LIST_ID)), removed.capture());+ assertEquals(List.of("team=null"), pairs(removed.getValue()));+ verify(ec2, never()).createTags(any(), any(), any());+ }++ @Test+ void aPrefixListWhoseTemplatesNeverDeclaredTagsKeepsTheTagsItCarries() {+ ManagedPrefixList current = prefixList(1, 2, OFFICE);+ current.setTags(List.of(new Tag("owner", "ops")));+ describesPrefixList(current);+ StackResource r = prior("AWS::EC2::PrefixList", "Firewall", PREFIX_LIST_ID, Map.of("PrefixListId", PREFIX_LIST_ID));++ provisioner.provision(r, prefixListProps(2, "192.0.2.0/24", "office"),+ ctx(PREFIX_LIST_ID, prefixListProps(2, "192.0.2.0/24", "office")));++ verify(ec2, never()).deleteTags(any(), any(), any());+ verify(ec2, never()).createTags(any(), any(), any());+ }++ @Test+ void aRejectedModifyPutsThePriorTagsBackAndLeavesTheListOnItsVersion() {+ ManagedPrefixList current = prefixList(1, 1, OFFICE);+ current.setTags(List.of(new Tag("team", "network")));+ describesPrefixList(current);+ doThrow(new AwsException("InvalidParameterValue", "The number of entries exceeds the maximum of 1.", 400))+ .when(ec2).modifyManagedPrefixList(any(), any(), any(), any(), any(), any(), any());+ StackResource r = prior("AWS::EC2::PrefixList", "Firewall", PREFIX_LIST_ID, Map.of("PrefixListId", PREFIX_LIST_ID));+ ObjectNode props = withTags(prefixListProps(1, "192.0.2.0/24", "office", "198.51.100.0/24", "branch"),+ "team", "platform");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx(PREFIX_LIST_ID)));++ assertEquals("InvalidParameterValue", e.getErrorCode());+ ArgumentCaptor<List<Tag>> written = ArgumentCaptor.captor();+ verify(ec2, times(2)).createTags(eq(REGION), eq(List.of(PREFIX_LIST_ID)), written.capture());+ assertEquals(List.of("team=platform"), pairs(written.getAllValues().get(0)));+ assertEquals(List.of("team=network"), pairs(written.getAllValues().get(1)), "the prior tags are written back");+ verify(ec2, times(1)).modifyManagedPrefixList(any(), any(), any(), any(), any(), any(), any());+ assertFalse(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));+ }++ @Test+ void aStubLeftByAnOlderFlociBecomesARealListAndARollbackPutsTheStubBack() {+ when(ec2.describeManagedPrefixLists(REGION, List.of("Firewall-1a2b3c4d"), Map.of()))+ .thenThrow(new AwsException("InvalidPrefixListID.NotFound", "gone", 400));+ when(ec2.createManagedPrefixList(eq(REGION), eq("firewall"), eq("IPv4"), eq(2), any(), any()))+ .thenReturn(prefixList(1, 2, OFFICE));+ StackResource r = prior("AWS::EC2::PrefixList", "Firewall", "Firewall-1a2b3c4d",+ Map.of("Arn", "arn:aws:stub:::Firewall"));++ provisioner.provision(r, prefixListProps(2, "192.0.2.0/24", "office"), ctx("Firewall-1a2b3c4d"));++ assertEquals(PREFIX_LIST_ID, r.getPhysicalId());+ assertTrue(provisioner.rollbackUpdate(r));+ verify(ec2).deleteManagedPrefixList(REGION, PREFIX_LIST_ID);+ assertEquals("Firewall-1a2b3c4d", r.getPhysicalId());+ assertEquals("arn:aws:stub:::Firewall", r.getAttributes().get("Arn"));+ }++ @Test+ void entriesNoTemplateDeclaredAreLeftAloneAndDoNotBlockAResize() {+ PrefixListEntry outside = new PrefixListEntry("203.0.113.0/24", "added outside the stack");+ ManagedPrefixList resized = prefixList(2, 6, outside);+ describesPrefixList(prefixList(2, 5, outside), resized);+ when(ec2.modifyManagedPrefixList(eq(REGION), eq(PREFIX_LIST_ID), any(), any(), any(), any(), any()))+ .thenReturn(resized);+ StackResource r = prior("AWS::EC2::PrefixList", "Firewall", PREFIX_LIST_ID, Map.of("PrefixListId", PREFIX_LIST_ID));++ provisioner.provision(r, prefixListProps(6).without("Entries"), ctx(PREFIX_LIST_ID, prefixListProps(5).without("Entries")));++ assertEquals(List.of("version=2 name=firewall max=6 add=[] remove=[]"), modifyCalls());+ }++ @Test+ void droppingTheEntriesThePreviousTemplateDeclaredClearsThem() {+ describesPrefixList(prefixList(1, 2, OFFICE), prefixList(2, 2));+ when(ec2.modifyManagedPrefixList(eq(REGION), eq(PREFIX_LIST_ID), any(), any(), any(), any(), any()))+ .thenReturn(prefixList(2, 2));+ StackResource r = prior("AWS::EC2::PrefixList", "Firewall", PREFIX_LIST_ID, Map.of("PrefixListId", PREFIX_LIST_ID));++ provisioner.provision(r, prefixListProps(2).without("Entries"),+ ctx(PREFIX_LIST_ID, prefixListProps(2, "192.0.2.0/24", "office")));++ assertEquals(List.of("version=1 name=firewall max=null add=[] remove=[192.0.2.0/24]"), modifyCalls());+ }++ @Test+ void aTagEc2RefusesFailsTheCreateAndRemovesTheNewList() {+ when(ec2.createManagedPrefixList(eq(REGION), eq("firewall"), eq("IPv4"), eq(2), any(), any()))+ .thenReturn(prefixList(1, 2, OFFICE));+ doThrow(new AwsException("InvalidParameterValue", "Tag key exceeds the maximum length of 128 characters", 400))+ .when(ec2).createTags(any(), any(), any());+ StackResource r = resource("AWS::EC2::PrefixList", "Firewall");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r,+ withTags(prefixListProps(2, "192.0.2.0/24", "office"), "k".repeat(129), "x"), ctx()));++ assertEquals("InvalidParameterValue", e.getErrorCode());+ verify(ec2).deleteManagedPrefixList(REGION, PREFIX_LIST_ID);+ assertFalse(r.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR), "the list was removed again");+ }++ @Test+ void aCreateWhoseTagsAndUndoBothFailLeavesTheNewListOwnedAndNamed() {+ when(ec2.createManagedPrefixList(eq(REGION), eq("firewall"), eq("IPv4"), eq(2), any(), any()))+ .thenReturn(prefixList(1, 2, OFFICE));+ doThrow(new AwsException("InvalidParameterValue", "refused tag", 400)).when(ec2).createTags(any(), any(), any());+ doThrow(new AwsException("InternalError", "delete failed", 500)).when(ec2).deleteManagedPrefixList(REGION, PREFIX_LIST_ID);+ StackResource r = resource("AWS::EC2::PrefixList", "Firewall");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r,+ withTags(prefixListProps(2, "192.0.2.0/24", "office"), "team", "network"), ctx()));++ assertEquals("InvalidParameterValue", e.getErrorCode());+ assertEquals(PREFIX_LIST_ID, r.getPhysicalId(), "the list left behind is the one the resource names");+ assertEquals("true", r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR), "so the engine's rollback deletes it");+ assertTrue(r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR).contains(PREFIX_LIST_ID));+ }++ /** Every ModifyManagedPrefixList call so far: the version it named, the name, the capacity, the entries added and the CIDRs removed. */+ private List<String> modifyCalls() {+ List<String> calls = new ArrayList<>();+ for (Invocation call : mockingDetails(ec2).getInvocations()) {+ if ("modifyManagedPrefixList".equals(call.getMethod().getName())) {+ List<PrefixListEntry> added = call.getArgument(5);+ calls.add("version=" + call.getArgument(2) + " name=" + call.getArgument(3) + " max=" + call.getArgument(4)+ + " add=" + entryPairs(added) + " remove=" + call.getArgument(6));+ }+ }+ return calls;+ }+@Testvoid unknownTypeIsRejected() {StackResource r = resource("AWS::EC2::SecurityGroup", "Sg");diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.javaindex aaf8935c3f..44ad24e72b 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;@@ -12,6 +13,7 @@ import java.util.Map;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.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.Mockito.mock;@@ -112,6 +114,29 @@ class ProvisionContextTest {assertEquals("WEBSOCKET", ctx.resolveOrDefault(null, "ProtocolType", "WEBSOCKET"), "null props falls back");}+ @Test+ void resolveOptionalIntReadsAnIntegerAndLeavesWhatTheTemplateOmitsUnset() {+ ProvisionContext ctx = context(null);+ JsonNode size = props("{\"Ref\": \"Size\"}");+ when(engine.resolve(size)).thenReturn("3");++ assertEquals(42, ctx.resolveOptionalInt(props("{\"Port\": 42}"), "Port"), "a number");+ assertEquals(42, ctx.resolveOptionalInt(props("{\"Port\": \"42\"}"), "Port"), "a numeric string");+ assertEquals(7, ctx.resolveOptionalInt(props("{\"Port\": \" 7 \"}"), "Port"), "surrounding blanks are trimmed");+ assertEquals(3, ctx.resolveOptionalInt(props("{\"Port\": {\"Ref\": \"Size\"}}"), "Port"), "an intrinsic's result");+ assertNull(ctx.resolveOptionalInt(props("{}"), "Port"), "absent");+ assertNull(ctx.resolveOptionalInt(props("{\"Port\": null}"), "Port"), "explicitly null");+ assertNull(ctx.resolveOptionalInt(null, "Port"), "no properties at all");+ assertNull(ctx.resolveOptionalInt(props("{\"Port\": {\"Ref\": \"AWS::NoValue\"}}"), "Port"),+ "an intrinsic that resolves to blank, as AWS::NoValue does");+ for (String literal : List.of("\"\"", "\"ten\"", "\"4.5\"", "4.5", "true")) {+ AwsException e = assertThrows(AwsException.class,+ () -> ctx.resolveOptionalInt(props("{\"Port\": " + literal + "}"), "Port"), literal);+ assertEquals("ValidationError", e.getErrorCode(), literal);+ assertEquals("Value of property Port must be an integer.", e.getMessage(), literal);+ }+ }+@Testvoid stablePhysicalNamePrefersTheTemplatesName() {assertEquals("chosen",diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsvindex 26e0e86ea5..1cec1dc2cd 100644--- a/src/test/resources/cloudformation/supported-resource-types.tsv+++ b/src/test/resources/cloudformation/supported-resource-types.tsv@@ -77,6 +77,7 @@ AWS::EC2::LaunchTemplate Ec2LaunchTemplateCfnProvisionerAWS::EC2::NatGateway Ec2NetworkCfnProvisionerAWS::EC2::NetworkAcl Ec2NetworkAclCfnProvisionerAWS::EC2::NetworkAclEntry Ec2NetworkAclCfnProvisioner+AWS::EC2::PrefixList Ec2NetworkCfnProvisionerAWS::EC2::Route Ec2NetworkCfnProvisionerAWS::EC2::RouteTable Ec2NetworkCfnProvisionerAWS::EC2::SecurityGroup Ec2SecurityGroupCfnProvisionerdiff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yamlindex d7e65dc303..f49131acba 100644--- a/tools/docs/cfn_resource_types.yaml+++ b/tools/docs/cfn_resource_types.yaml@@ -187,6 +187,7 @@ notes:AWS::Lambda::WebFunctionEndpoint: '`RegionalEndpoints` is not exposed to `Fn::GetAtt` yet'AWS::EC2::VPC: 'deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS'AWS::EC2::SecurityGroup: inline `SecurityGroupIngress`/`SecurityGroupEgress` supported+ AWS::EC2::PrefixList: 'updated in place; an update that changes `AddressFamily`, or `MaxEntries` together with `Entries`, fails'AWS::ApplicationAutoScaling::ScalableTarget: '`ScheduledActions` are accepted and not run; Floci has no scheduled scaling'AWS::RDS::DBInstance: starts a real containerAWS::RDS::DBCluster: starts a real container