Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cloudformation): provision the network ACL family (#2001)

lex005e01c07b33e5
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index e06368b920..67b3e6d943 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -67,7 +67,7 @@ cross-resource references.
| ECS | `Cluster`, `TaskDefinition`, `Service` |
| EKS | `Cluster`, `Nodegroup` |
| RDS | `DBInstance`, `DBCluster`, `DBSubnetGroup`, `DBParameterGroup`, `DBClusterParameterGroup` (DBInstance/DBCluster start real containers) |
-| EC2 | `VPC`, `Subnet`, `SecurityGroup`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment` |
+| EC2 | `VPC`, `Subnet`, `SecurityGroup`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation` |
| Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` |
| Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup` |
| Route 53 | `HostedZone`, `RecordSet` |
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkAclCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkAclCfnProvisioner.java
new file mode 100644
index 0000000000..00a13b0ef0
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkAclCfnProvisioner.java
@@ -0,0 +1,167 @@
+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.model.StackResource;
+import io.github.hectorvent.floci.services.ec2.Ec2Service;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * CloudFormation provisioning for the EC2 network ACL family: {@code AWS::EC2::NetworkAcl},
+ * {@code AWS::EC2::NetworkAclEntry} and {@code AWS::EC2::SubnetNetworkAclAssociation}.
+ * All scalar entry properties (including {@code RuleNumber}, {@code Egress} and the
+ * {@code PortRange} bounds) resolve through the template engine, so intrinsics like
+ * {@code Ref}/{@code Fn::Sub} in any of them work.
+ */
+@ApplicationScoped
+public class Ec2NetworkAclCfnProvisioner implements CfnResourceProvisioner {
+
+ private final Ec2Service ec2Service;
+
+ @Inject
+ public Ec2NetworkAclCfnProvisioner(Ec2Service ec2Service) {
+ this.ec2Service = ec2Service;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of("AWS::EC2::NetworkAcl", "AWS::EC2::NetworkAclEntry",
+ "AWS::EC2::SubnetNetworkAclAssociation");
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ switch (r.getResourceType()) {
+ case "AWS::EC2::NetworkAcl" -> provisionNetworkAcl(r, props, ctx);
+ case "AWS::EC2::NetworkAclEntry" -> provisionNetworkAclEntry(r, props, ctx);
+ case "AWS::EC2::SubnetNetworkAclAssociation" -> provisionSubnetNetworkAclAssociation(r, props, ctx);
+ default -> throw new IllegalStateException(
+ "Ec2NetworkAclCfnProvisioner cannot handle " + r.getResourceType());
+ }
+ }
+
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ try {
+ switch (resourceType) {
+ case "AWS::EC2::NetworkAcl" -> ec2Service.deleteNetworkAcl(region, physicalId);
+ case "AWS::EC2::NetworkAclEntry" -> deleteNetworkAclEntry(physicalId, region);
+ case "AWS::EC2::SubnetNetworkAclAssociation" -> deleteSubnetNetworkAclAssociation(physicalId, region);
+ default -> { }
+ }
+ } catch (AwsException e) {
+ // Already gone (or already moved back): deleting a deleted resource is not an error.
+ if (!e.getErrorCode().contains("NotFound")) {
+ throw e;
+ }
+ }
+ }
+
+ private void provisionNetworkAcl(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String vpcId = ctx.resolveOptional(props, "VpcId");
+ // An update re-invokes provision with the prior physical id. Creating unconditionally
+ // would mint a second ACL and orphan the first permanently, so reuse the one this stack
+ // already made; only create when it is absent, meaning a first execution or one removed
+ // out of band.
+ String existingId = r.getPhysicalId();
+ var existing = existingId == null || existingId.isBlank() ? null
+ : ec2Service.describeNetworkAcls(ctx.region(), List.of(existingId), Map.of())
+ .stream().findFirst().orElse(null);
+ if (existing != null) {
+ // VpcId is createOnly, so a change is a replacement. Report it rather than leave the
+ // ACL silently attached to the original VPC, matching how EcsCapacityCfnProvisioner
+ // treats Name.
+ if (vpcId != null && !vpcId.equals(existing.getVpcId())) {
+ throw new AwsException("ValidationError",
+ "Updating VpcId requires resource replacement, which is not supported.", 400);
+ }
+ r.getAttributes().put("Id", existingId);
+ return;
+ }
+ var acl = ec2Service.createNetworkAcl(ctx.region(), vpcId);
+ r.setPhysicalId(acl.getNetworkAclId());
+ r.getAttributes().put("Id", acl.getNetworkAclId());
+ }
+
+ private void provisionNetworkAclEntry(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String aclId = ctx.resolveOptional(props, "NetworkAclId");
+ String ruleNumberValue = ctx.resolveOptional(props, "RuleNumber");
+ int ruleNumber = ruleNumberValue != null ? Integer.parseInt(ruleNumberValue) : 100;
+ boolean egress = Boolean.parseBoolean(ctx.resolveOptional(props, "Egress"));
+ JsonNode portRange = props != null && props.hasNonNull("PortRange") ? props.get("PortRange") : null;
+ String fromValue = ctx.resolveOptional(portRange, "From");
+ String toValue = ctx.resolveOptional(portRange, "To");
+ Integer from = fromValue != null ? Integer.valueOf(fromValue) : null;
+ Integer to = toValue != null ? Integer.valueOf(toValue) : null;
+ String protocol = ctx.resolveOptional(props, "Protocol");
+ ec2Service.createNetworkAclEntry(ctx.region(), aclId, ruleNumber,
+ protocol != null ? protocol : "-1",
+ ctx.resolveOptional(props, "RuleAction"),
+ egress,
+ ctx.resolveOptional(props, "CidrBlock"),
+ // RuleNumber, Egress and NetworkAclId are the createOnly key, so re-provisioning
+ // the same key is an update. replace=false would raise NetworkAclEntryAlreadyExists
+ // on every stack update.
+ from, to, true);
+ r.setPhysicalId(aclId + "|" + ruleNumber + "|" + (egress ? "egress" : "ingress"));
+ }
+
+ private void provisionSubnetNetworkAclAssociation(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String subnetId = ctx.resolveOptional(props, "SubnetId");
+ String aclId = ctx.resolveOptional(props, "NetworkAclId");
+ // CFN semantics: move the subnet from its current (default) ACL onto the
+ // given one. Find the subnet's live association, then replace it.
+ String associationId = ec2Service.describeNetworkAcls(ctx.region(), List.of(), Map.of()).stream()
+ .flatMap(acl -> acl.getAssociations().stream())
+ .filter(a -> subnetId != null && subnetId.equals(a.getSubnetId()))
+ .map(a -> a.getNetworkAclAssociationId())
+ .findFirst()
+ .orElse(null);
+ if (associationId == null) {
+ throw new IllegalStateException(
+ "No network ACL association found for subnet " + subnetId);
+ }
+ var assoc = ec2Service.replaceNetworkAclAssociation(ctx.region(), associationId, aclId);
+ r.setPhysicalId(assoc.getNetworkAclAssociationId());
+ r.getAttributes().put("AssociationId", assoc.getNetworkAclAssociationId());
+ }
+
+ /** Physical id format: {@code <aclId>|<ruleNumber>|<egress|ingress>} (set in provision). */
+ private void deleteNetworkAclEntry(String physicalId, String region) {
+ String[] parts = physicalId != null ? physicalId.split("\\|") : new String[0];
+ if (parts.length != 3) {
+ return;
+ }
+ ec2Service.deleteNetworkAclEntry(region, parts[0], Integer.parseInt(parts[1]),
+ "egress".equals(parts[2]));
+ }
+
+ /**
+ * CFN semantics for deleting a SubnetNetworkAclAssociation: the subnet reverts to its
+ * VPC's default network ACL. Locate the ACL currently holding the association, then
+ * replace the association with the default ACL of the same VPC.
+ */
+ private void deleteSubnetNetworkAclAssociation(String physicalId, String region) {
+ var holder = ec2Service.describeNetworkAcls(region, List.of(),
+ Map.of("association.network-acl-association-id", List.of(physicalId)))
+ .stream().findFirst().orElse(null);
+ if (holder == null) {
+ return; // association already gone
+ }
+ if (holder.isDefault()) {
+ return; // already on the default ACL, nothing to revert
+ }
+ var defaultAcl = ec2Service.describeNetworkAcls(region, List.of(),
+ Map.of("vpc-id", List.of(holder.getVpcId()), "default", List.of("true")))
+ .stream().findFirst().orElse(null);
+ if (defaultAcl == null) {
+ return;
+ }
+ ec2Service.replaceNetworkAclAssociation(region, physicalId, defaultAcl.getNetworkAclId());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationNetworkAclIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationNetworkAclIntegrationTest.java
new file mode 100644
index 0000000000..96d48fdf21
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationNetworkAclIntegrationTest.java
@@ -0,0 +1,141 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+
+/**
+ * End-to-end check that CloudFormation provisions the network ACL family
+ * (issue #2000): a custom ACL with an entry, and a subnet moved onto it via
+ * SubnetNetworkAclAssociation. Metadata-only — Docker-free.
+ */
+@QuarkusTest
+class CloudFormationNetworkAclIntegrationTest {
+
+ private static final String CFN_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
+ private static final String EC2_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
+
+ @Test
+ void aclEntryAndSubnetAssociationProvision() throws InterruptedException {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-nacl-stack-" + suffix;
+
+ String template = """
+ {
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.70.0.0/16"}},
+ "Subnet": {
+ "Type": "AWS::EC2::Subnet",
+ "Properties": {"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.70.1.0/24"}
+ },
+ "Acl": {"Type": "AWS::EC2::NetworkAcl", "Properties": {"VpcId": {"Ref": "Vpc"}}},
+ "DenyAllInbound": {
+ "Type": "AWS::EC2::NetworkAclEntry",
+ "Properties": {
+ "NetworkAclId": {"Ref": "Acl"},
+ "RuleNumber": 100,
+ "Protocol": "6",
+ "RuleAction": "deny",
+ "CidrBlock": "0.0.0.0/0",
+ "PortRange": {"From": 22, "To": 22}
+ }
+ },
+ "Assoc": {
+ "Type": "AWS::EC2::SubnetNetworkAclAssociation",
+ "Properties": {
+ "SubnetId": {"Ref": "Subnet"},
+ "NetworkAclId": {"Ref": "Acl"}
+ }
+ }
+ },
+ "Outputs": {
+ "AclId": {"Value": {"Ref": "Acl"}},
+ "SubnetId": {"Value": {"Ref": "Subnet"}}
+ }
+ }
+ """;
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ String describe = given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
+ .extract().asString();
+
+ String aclId = between(describe, "<OutputKey>AclId</OutputKey>", "</member>");
+ aclId = between(aclId, "<OutputValue>", "</OutputValue>");
+ String subnetId = between(describe, "<OutputKey>SubnetId</OutputKey>", "</member>");
+ subnetId = between(subnetId, "<OutputValue>", "</OutputValue>");
+
+ // The custom ACL carries the deny entry and the subnet's association.
+ given()
+ .formParam("Action", "DescribeNetworkAcls")
+ .formParam("NetworkAclId.1", aclId)
+ .header("Authorization", EC2_AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<ruleNumber>100</ruleNumber>"))
+ .body(containsString("deny"))
+ .body(containsString(subnetId));
+
+ // Deleting the stack reverts the subnet to the default ACL and removes the custom one.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DeleteStack")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ awaitNetworkAclGone(aclId);
+ }
+
+ /** DeleteStack runs asynchronously; poll until the custom ACL disappears. */
+ private static void awaitNetworkAclGone(String aclId) throws InterruptedException {
+ for (int i = 0; i < 100; i++) {
+ String acls = given()
+ .formParam("Action", "DescribeNetworkAcls")
+ .header("Authorization", EC2_AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().asString();
+ if (!acls.contains(aclId)) {
+ return;
+ }
+ Thread.sleep(50);
+ }
+ throw new AssertionError("Timed out waiting for network ACL " + aclId + " to be deleted");
+ }
+
+ private static String between(String haystack, String open, String close) {
+ int i = haystack.indexOf(open);
+ int j = haystack.indexOf(close, i + open.length());
+ return haystack.substring(i + open.length(), j);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkAclCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkAclCfnProvisionerTest.java
new file mode 100644
index 0000000000..0985b6f4dd
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkAclCfnProvisionerTest.java
@@ -0,0 +1,238 @@
+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.core.common.AwsException;
+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.NetworkAcl;
+import io.github.hectorvent.floci.services.ec2.model.NetworkAclAssociation;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.eq;
+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 network ACL family provisioner in isolation: one mocked service instead of the
+ * ~30 the monolithic provisioner needed.
+ */
+class Ec2NetworkAclCfnProvisionerTest {
+
+ private final Ec2Service ec2 = mock(Ec2Service.class);
+ private final Ec2NetworkAclCfnProvisioner provisioner = new Ec2NetworkAclCfnProvisioner(ec2);
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ private ProvisionContext ctx() {
+ // The engine is a collaborator; scalars resolve to their text and {"Ref": "X"} nodes
+ // resolve to "resolved-X", enough to prove every property goes through the engine.
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ if (node == null) {
+ return null;
+ }
+ if (node.isObject() && node.has("Ref")) {
+ return "resolved-" + node.get("Ref").asText();
+ }
+ return node.asText();
+ });
+ return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
+ }
+
+ private StackResource resource(String type, String logicalId) {
+ StackResource r = new StackResource();
+ r.setLogicalId(logicalId);
+ r.setResourceType(type);
+ r.setAttributes(new HashMap<>());
+ return r;
+ }
+
+ private static NetworkAcl acl(String aclId, String vpcId, boolean isDefault, NetworkAclAssociation... assocs) {
+ NetworkAcl acl = new NetworkAcl();
+ acl.setNetworkAclId(aclId);
+ acl.setVpcId(vpcId);
+ acl.setDefault(isDefault);
+ acl.setAssociations(List.of(assocs));
+ return acl;
+ }
+
+ private static NetworkAclAssociation assoc(String assocId, String aclId, String subnetId) {
+ NetworkAclAssociation a = new NetworkAclAssociation();
+ a.setNetworkAclAssociationId(assocId);
+ a.setNetworkAclId(aclId);
+ a.setSubnetId(subnetId);
+ return a;
+ }
+
+ @Test
+ void networkAclSetsPhysicalIdAndIdAttribute() {
+ when(ec2.createNetworkAcl("us-east-1", "vpc-123")).thenReturn(acl("acl-abc", "vpc-123", false));
+ StackResource r = resource("AWS::EC2::NetworkAcl", "Acl");
+ ObjectNode props = mapper.createObjectNode().put("VpcId", "vpc-123");
+
+ provisioner.provision(r, props, ctx());
+
+ assertEquals("acl-abc", r.getPhysicalId());
+ assertEquals("acl-abc", r.getAttributes().get("Id"));
+ }
+
+ @Test
+ void aclEntryResolvesEveryPropertyThroughTheEngine() {
+ StackResource r = resource("AWS::EC2::NetworkAclEntry", "Entry");
+ ObjectNode props = mapper.createObjectNode();
+ props.set("NetworkAclId", mapper.createObjectNode().put("Ref", "Acl"));
+ // RuleNumber/Egress/PortRange arrive as intrinsics too: they must resolve, not be read raw.
+ props.set("RuleNumber", mapper.createObjectNode().put("Ref", "Rule"));
+ props.put("Protocol", "6");
+ props.put("RuleAction", "deny");
+ props.put("Egress", true);
+ props.put("CidrBlock", "0.0.0.0/0");
+ ObjectNode portRange = mapper.createObjectNode();
+ portRange.set("From", mapper.createObjectNode().put("Ref", "Port"));
+ portRange.put("To", 22);
+ props.set("PortRange", portRange);
+
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ if (node.isObject() && node.has("Ref")) {
+ return switch (node.get("Ref").asText()) {
+ case "Acl" -> "acl-abc";
+ case "Rule" -> "150";
+ case "Port" -> "22";
+ default -> "";
+ };
+ }
+ return node.asText();
+ });
+ provisioner.provision(r, props, new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack"));
+
+ verify(ec2).createNetworkAclEntry("us-east-1", "acl-abc", 150, "6", "deny", true,
+ "0.0.0.0/0", 22, 22, true);
+ assertEquals("acl-abc|150|egress", r.getPhysicalId());
+ }
+
+ @Test
+ void aclEntryDefaultsMatchPriorBehavior() {
+ StackResource r = resource("AWS::EC2::NetworkAclEntry", "Entry");
+ ObjectNode props = mapper.createObjectNode().put("NetworkAclId", "acl-abc");
+
+ provisioner.provision(r, props, ctx());
+
+ verify(ec2).createNetworkAclEntry("us-east-1", "acl-abc", 100, "-1", null, false,
+ null, null, null, true);
+ assertEquals("acl-abc|100|ingress", r.getPhysicalId());
+ }
+
+ @Test
+ void updateReusesTheAclThisStackAlreadyCreated() {
+ StackResource r = resource("AWS::EC2::NetworkAcl", "Acl");
+ r.setPhysicalId("acl-abc");
+ when(ec2.describeNetworkAcls("us-east-1", List.of("acl-abc"), Map.of()))
+ .thenReturn(List.of(acl("acl-abc", "vpc-123", false)));
+ ObjectNode props = mapper.createObjectNode().put("VpcId", "vpc-123");
+
+ provisioner.provision(r, props, ctx());
+
+ // A second ACL here would orphan the first permanently: nothing else references it.
+ verify(ec2, never()).createNetworkAcl(any(), any());
+ assertEquals("acl-abc", r.getPhysicalId());
+ assertEquals("acl-abc", r.getAttributes().get("Id"));
+ }
+
+ @Test
+ void updateRecreatesAnAclRemovedOutOfBand() {
+ StackResource r = resource("AWS::EC2::NetworkAcl", "Acl");
+ r.setPhysicalId("acl-gone");
+ when(ec2.describeNetworkAcls("us-east-1", List.of("acl-gone"), Map.of()))
+ .thenReturn(List.of());
+ when(ec2.createNetworkAcl("us-east-1", "vpc-123")).thenReturn(acl("acl-new", "vpc-123", false));
+ ObjectNode props = mapper.createObjectNode().put("VpcId", "vpc-123");
+
+ provisioner.provision(r, props, ctx());
+
+ assertEquals("acl-new", r.getPhysicalId());
+ assertEquals("acl-new", r.getAttributes().get("Id"));
+ }
+
+ @Test
+ void changingVpcIdReportsAnUnsupportedReplacement() {
+ StackResource r = resource("AWS::EC2::NetworkAcl", "Acl");
+ r.setPhysicalId("acl-abc");
+ when(ec2.describeNetworkAcls("us-east-1", List.of("acl-abc"), Map.of()))
+ .thenReturn(List.of(acl("acl-abc", "vpc-123", false)));
+ ObjectNode props = mapper.createObjectNode().put("VpcId", "vpc-456");
+
+ // VpcId is createOnly. Reusing silently would leave the ACL on the original VPC.
+ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
+ assertEquals("ValidationError", e.getErrorCode());
+ verify(ec2, never()).createNetworkAcl(any(), any());
+ }
+
+ @Test
+ void subnetAssociationReplacesTheSubnetsLiveAssociation() {
+ when(ec2.describeNetworkAcls(eq("us-east-1"), eq(List.of()), anyMap()))
+ .thenReturn(List.of(acl("acl-default", "vpc-123", true,
+ assoc("aclassoc-1", "acl-default", "subnet-1"))));
+ when(ec2.replaceNetworkAclAssociation("us-east-1", "aclassoc-1", "acl-abc"))
+ .thenReturn(assoc("aclassoc-2", "acl-abc", "subnet-1"));
+ StackResource r = resource("AWS::EC2::SubnetNetworkAclAssociation", "Assoc");
+ ObjectNode props = mapper.createObjectNode()
+ .put("SubnetId", "subnet-1")
+ .put("NetworkAclId", "acl-abc");
+
+ provisioner.provision(r, props, ctx());
+
+ assertEquals("aclassoc-2", r.getPhysicalId());
+ assertEquals("aclassoc-2", r.getAttributes().get("AssociationId"));
+ }
+
+ @Test
+ void deleteNetworkAclDelegatesToService() {
+ provisioner.delete("AWS::EC2::NetworkAcl", "acl-abc", "us-east-1");
+ verify(ec2).deleteNetworkAcl("us-east-1", "acl-abc");
+ }
+
+ @Test
+ void deleteAclEntryParsesThePhysicalId() {
+ provisioner.delete("AWS::EC2::NetworkAclEntry", "acl-abc|150|egress", "us-east-1");
+ verify(ec2).deleteNetworkAclEntry("us-east-1", "acl-abc", 150, true);
+ }
+
+ @Test
+ void deleteSubnetAssociationRevertsToTheDefaultAcl() {
+ when(ec2.describeNetworkAcls("us-east-1", List.of(),
+ Map.of("association.network-acl-association-id", List.of("aclassoc-2"))))
+ .thenReturn(List.of(acl("acl-abc", "vpc-123", false,
+ assoc("aclassoc-2", "acl-abc", "subnet-1"))));
+ when(ec2.describeNetworkAcls("us-east-1", List.of(),
+ Map.of("vpc-id", List.of("vpc-123"), "default", List.of("true"))))
+ .thenReturn(List.of(acl("acl-default", "vpc-123", true)));
+
+ provisioner.delete("AWS::EC2::SubnetNetworkAclAssociation", "aclassoc-2", "us-east-1");
+
+ verify(ec2).replaceNetworkAclAssociation("us-east-1", "aclassoc-2", "acl-default");
+ }
+
+ @Test
+ void deleteSubnetAssociationIsANoOpWhenAlreadyGone() {
+ when(ec2.describeNetworkAcls(eq("us-east-1"), eq(List.of()), anyMap())).thenReturn(List.of());
+
+ provisioner.delete("AWS::EC2::SubnetNetworkAclAssociation", "aclassoc-2", "us-east-1");
+
+ verify(ec2, never()).replaceNetworkAclAssociation(any(), any(), any());
+ }
+}