From 9e178d77a0ceac47cc40dc7a677f14a020a32590 Mon Sep 17 00:00:00 2001 From: Mario Toffia Date: Sat, 3 Oct 2026 22:01:18 +0200 Subject: [PATCH] feat(wafv2): provision web ACL associations (#4804) * feat(wafv2): provision web ACL associations WafV2CfnProvisioner now serves AWS::WAFv2::WebACLAssociation with Ref ResourceArn|WebACLArn, as measured on AWS. Any property change replaces the pair through ReplacementCleanup. Delete disassociates only while the resource still uses that ACL, so cleanup of an old pair keeps the new one. Rollback re-associates the restored pair. * test(wafv2): cover ResourceArn replacement and read stack outputs with XmlPath --- ...udFormationWafV2WebAclAssociationTest.java | 185 +++++++++++++++++ docs/services/cloudformation.md | 2 +- .../provisioners/WafV2CfnProvisioner.java | 95 ++++++++- ...WafV2WebAclAssociationIntegrationTest.java | 175 ++++++++++++++++ .../provisioners/WafV2CfnProvisionerTest.java | 193 ++++++++++++++++++ .../supported-resource-types.tsv | 1 + 6 files changed, 644 insertions(+), 7 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationWafV2WebAclAssociationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationWafV2WebAclAssociationIntegrationTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationWafV2WebAclAssociationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationWafV2WebAclAssociationTest.java new file mode 100644 index 0000000000..ef68e61b81 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationWafV2WebAclAssociationTest.java @@ -0,0 +1,185 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudformation.model.CloudFormationException; +import software.amazon.awssdk.services.cloudformation.model.Output; +import software.amazon.awssdk.services.cloudformation.model.Stack; +import software.amazon.awssdk.services.wafv2.Wafv2Client; +import software.amazon.awssdk.services.wafv2.model.ResourceType; +import software.amazon.awssdk.services.wafv2.model.WebACL; + +import java.util.List; +import java.util.Map; +import java.util.function.BooleanSupplier; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; + +@DisplayName("CloudFormation AWS::WAFv2::WebACLAssociation") +class CloudFormationWafV2WebAclAssociationTest { + + private static final Logger LOG = Logger.getLogger(CloudFormationWafV2WebAclAssociationTest.class.getName()); + + private static CloudFormationClient cfn; + private static Wafv2Client waf; + private static String stackName; + + @BeforeAll + static void setup() { + cfn = TestFixtures.cloudFormationClient(); + waf = TestFixtures.wafv2Client(); + stackName = TestFixtures.uniqueName("compat-cfn-waf-assoc"); + } + + @AfterAll + static void cleanup() { + try { + cfn.deleteStack(r -> r.stackName(stackName)); + } catch (Exception e) { + LOG.log(Level.WARNING, "Failed to delete WAFv2 association test stack: " + stackName, e); + } + cfn.close(); + waf.close(); + } + + @Test + void associationFollowsTheTemplateAcrossReplacementAndStackDelete() throws InterruptedException { + cfn.createStack(r -> r.stackName(stackName).templateBody(template("AclA"))); + awaitStatus("CREATE_COMPLETE"); + Map created = outputs(); + String poolArn = created.get("PoolArn"); + String aclAArn = created.get("AclAArn"); + String aclBArn = created.get("AclBArn"); + + assertThat(created.get("AssocRef")).as("Ref is ResourceArn|WebACLArn").isEqualTo(poolArn + "|" + aclAArn); + assertThat(cfn.describeStackResource(r -> r.stackName(stackName).logicalResourceId("Assoc")) + .stackResourceDetail().physicalResourceId()).isEqualTo(poolArn + "|" + aclAArn); + assertThat(webAclArnFor(poolArn)).isEqualTo(aclAArn); + + cfn.updateStack(r -> r.stackName(stackName).templateBody(template("AclB"))); + awaitStatus("UPDATE_COMPLETE"); + + assertThat(outputs().get("AssocRef")).isEqualTo(poolArn + "|" + aclBArn); + assertThat(webAclArnFor(poolArn)) + .as("cleaning up the old pair keeps the pool associated with the new ACL") + .isEqualTo(aclBArn); + assertThat(resourcesFor(aclAArn)).isEmpty(); + assertThat(resourcesFor(aclBArn)).containsExactly(poolArn); + + deleteStack(); + assertThat(webAclArnFor(poolArn)).as("the stack delete disassociates the pool").isNull(); + } + + private static String template(String associatedAcl) { + return """ + { + "Resources": { + "Pool": { + "Type": "AWS::Cognito::UserPool", + "Properties": {"UserPoolName": "%1$s-pool"} + }, + "AclA": { + "Type": "AWS::WAFv2::WebACL", + "Properties": { + "Name": "%1$s-a", + "Scope": "REGIONAL", + "DefaultAction": {"Allow": {}}, + "VisibilityConfig": { + "SampledRequestsEnabled": false, + "CloudWatchMetricsEnabled": false, + "MetricName": "%1$s-a" + } + } + }, + "AclB": { + "Type": "AWS::WAFv2::WebACL", + "Properties": { + "Name": "%1$s-b", + "Scope": "REGIONAL", + "DefaultAction": {"Block": {}}, + "VisibilityConfig": { + "SampledRequestsEnabled": false, + "CloudWatchMetricsEnabled": false, + "MetricName": "%1$s-b" + } + } + }, + "Assoc": { + "Type": "AWS::WAFv2::WebACLAssociation", + "Properties": { + "ResourceArn": {"Fn::GetAtt": ["Pool", "Arn"]}, + "WebACLArn": {"Fn::GetAtt": ["%2$s", "Arn"]} + } + } + }, + "Outputs": { + "AssocRef": {"Value": {"Ref": "Assoc"}}, + "PoolArn": {"Value": {"Fn::GetAtt": ["Pool", "Arn"]}}, + "AclAArn": {"Value": {"Fn::GetAtt": ["AclA", "Arn"]}}, + "AclBArn": {"Value": {"Fn::GetAtt": ["AclB", "Arn"]}} + } + } + """.formatted(stackName, associatedAcl); + } + + private static Map outputs() { + return cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0).outputs().stream() + .collect(Collectors.toMap(Output::outputKey, Output::outputValue)); + } + + private static String webAclArnFor(String resourceArn) { + WebACL acl = waf.getWebACLForResource(r -> r.resourceArn(resourceArn)).webACL(); + return acl == null ? null : acl.arn(); + } + + private static List resourcesFor(String webAclArn) { + return waf.listResourcesForWebACL(r -> r.webACLArn(webAclArn).resourceType(ResourceType.COGNITO_USER_POOL)) + .resourceArns(); + } + + private static void awaitStatus(String expected) throws InterruptedException { + await(() -> { + Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0); + String status = stack.stackStatusAsString(); + if (status.endsWith("_FAILED") || status.contains("ROLLBACK")) { + throw new AssertionError(stackName + " reached " + status + ": " + stack.stackStatusReason()); + } + return expected.equals(status); + }, expected); + } + + private static void deleteStack() throws InterruptedException { + cfn.deleteStack(r -> r.stackName(stackName)); + await(() -> { + try { + Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0); + if ("DELETE_FAILED".equals(stack.stackStatusAsString())) { + throw new AssertionError(stackName + " deletion failed: " + stack.stackStatusReason()); + } + return "DELETE_COMPLETE".equals(stack.stackStatusAsString()); + } catch (CloudFormationException e) { + if (e.getMessage().contains("does not exist")) { + return true; + } + throw e; + } + }, "stack deletion"); + } + + private static void await(BooleanSupplier condition, String expected) throws InterruptedException { + long deadline = System.nanoTime() + 300_000_000_000L; + while (System.nanoTime() < deadline) { + if (condition.getAsBoolean()) { + return; + } + Thread.sleep(250); + } + throw new AssertionError(stackName + " timed out waiting for " + expected); + } +} diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 8ba4b205ce..6649ba5f40 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -164,7 +164,7 @@ cross-resource references. | CloudFront | `CachePolicy`, `Distribution`, `OriginAccessControl`, `OriginRequestPolicy`, `ResponseHeadersPolicy` | | CloudWatch | `Alarm`, `Dashboard` | | CloudWatch Logs | `LogGroup`, `LogStream`, `MetricFilter` | -| WAFv2 | `WebACL` | +| WAFv2 | `WebACL`, `WebACLAssociation` | | Config | `ConfigRule` | | CloudFormation | `CustomResource`, `Custom::DynamoDBReplica` (applied natively against DynamoDB, not via a provider Lambda), `Stack` (nested stacks), `Custom::*` (Lambda-backed) | | CloudTrail | `Trail` | diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/WafV2CfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/WafV2CfnProvisioner.java index 36fa825ed1..8f112855a3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/WafV2CfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/WafV2CfnProvisioner.java @@ -10,6 +10,7 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.util.ArrayList; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -20,6 +21,7 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner { private static final Logger LOG = Logger.getLogger(WafV2CfnProvisioner.class); private static final String WEB_ACL = "AWS::WAFv2::WebACL"; + private static final String WEB_ACL_ASSOCIATION = "AWS::WAFv2::WebACLAssociation"; private final WafV2Service wafV2Service; @@ -30,15 +32,19 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner { @Override public Set resourceTypes() { - return Set.of(WEB_ACL); + return Set.of(WEB_ACL, WEB_ACL_ASSOCIATION); } @Override public void provision(StackResource resource, JsonNode props, ProvisionContext ctx) { + if (WEB_ACL_ASSOCIATION.equals(resource.getResourceType())) { + provisionAssociation(resource, props, ctx); + return; + } JsonNode resolved = ctx.engine().resolveNode(props); - String scope = required(text(resolved, "Scope"), "Scope"); - required(raw(resolved, "DefaultAction"), "DefaultAction"); - required(raw(resolved, "VisibilityConfig"), "VisibilityConfig"); + String scope = required(text(resolved, "Scope"), WEB_ACL, "Scope"); + required(raw(resolved, "DefaultAction"), WEB_ACL, "DefaultAction"); + required(raw(resolved, "VisibilityConfig"), WEB_ACL, "VisibilityConfig"); String name = text(resolved, "Name"); WebAcl existing = findExisting(resource.getPhysicalId()); if (name == null || name.isBlank()) { @@ -70,8 +76,29 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner { setReferences(resource, acl); } + /** + * Every property is createOnly, so a changed one leaves a new {@code ResourceArn|WebACLArn} id + * and the prior pair is cleaned up or rolled back to through {@link ReplacementCleanup}. + */ + private void provisionAssociation(StackResource resource, JsonNode props, ProvisionContext ctx) { + JsonNode resolved = ctx.engine().resolveNode(props); + String resourceArn = required(text(resolved, "ResourceArn"), WEB_ACL_ASSOCIATION, "ResourceArn"); + String webAclArn = required(text(resolved, "WebACLArn"), WEB_ACL_ASSOCIATION, "WebACLArn"); + Map attributesBefore = new HashMap<>(resource.getAttributes()); + String physicalId = resourceArn + "|" + webAclArn; + if (!ctx.reusesPriorEntity(physicalId)) { + wafV2Service.associateWebAcl(webAclArn, resourceArn); + } + resource.setPhysicalId(physicalId); + ReplacementCleanup.record(resource, ctx, attributesBefore); + } + @Override public void delete(String resourceType, String physicalId, String region) { + if (WEB_ACL_ASSOCIATION.equals(resourceType)) { + deleteAssociation(physicalId); + return; + } WebAcl existing = findExisting(physicalId); if (existing != null) { wafV2Service.deleteWebAcl(existing.getScope(), existing.getId(), existing.getName(), @@ -79,6 +106,62 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner { } } + /** + * Disassociates only while the resource still uses this pair's ACL: a replacement on the same + * resource has already re-pointed it, and AWS keeps that newer association when the old pair is + * cleaned up. A resource already disassociated is a no-op. + */ + private void deleteAssociation(String physicalId) { + String[] pair = associationPair(physicalId); + if (pair == null) { + return; + } + WebAcl current = wafV2Service.getWebAclForResource(pair[0]); + if (current != null && pair[1].equals(current.getArn())) { + wafV2Service.disassociateWebAcl(pair[0]); + } + } + + @Override + public boolean hasReplacementUpdate(StackResource resource) { + return ReplacementCleanup.hasReplacement(resource); + } + + @Override + public String updateCleanupPhysicalId(StackResource resource) { + return ReplacementCleanup.cleanupPhysicalId(resource); + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + return ReplacementCleanup.complete(resource, this::delete); + } + + @Override + public void clearUpdate(StackResource resource) { + ReplacementCleanup.clear(resource); + } + + @Override + public boolean rollbackUpdate(StackResource resource) { + if (!WEB_ACL_ASSOCIATION.equals(resource.getResourceType())) { + return false; + } + if (ReplacementCleanup.rollback(resource, this::delete)) { + // The replacement overwrote this association on the same resource, then its delete disassociated it. + String[] pair = associationPair(resource.getPhysicalId()); + if (pair != null) { + wafV2Service.associateWebAcl(pair[1], pair[0]); + } + } + return true; + } + + private static String[] associationPair(String physicalId) { + String[] parts = physicalId == null ? new String[0] : physicalId.split("\\|", -1); + return parts.length == 2 ? parts : null; + } + private WebAcl fromProperties(JsonNode props) { WebAcl acl = new WebAcl(); acl.setDescription(text(props, "Description")); @@ -110,9 +193,9 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner { return acl; } - private static String required(String value, String property) { + private static String required(String value, String resourceType, String property) { if (value == null || value.isBlank()) { - throw new AwsException("ValidationError", WEB_ACL + " requires " + property, 400); + throw new AwsException("ValidationError", resourceType + " requires " + property, 400); } return value; } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationWafV2WebAclAssociationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationWafV2WebAclAssociationIntegrationTest.java new file mode 100644 index 0000000000..0a71fe0a08 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationWafV2WebAclAssociationIntegrationTest.java @@ -0,0 +1,175 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * AWS::WAFv2::WebACLAssociation through a stack: Ref is {@code ResourceArn|WebACLArn}, switching the + * ACL replaces the association without the cleanup of the old pair disassociating the resource, + * and deleting the stack disassociates it. Every assertion reads WAFv2 back, not only the stack. + */ +@QuarkusTest +class CloudFormationWafV2WebAclAssociationIntegrationTest { + + private static final String CFN_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request"; + private static final String WAF_JSON = "application/x-amz-json-1.1"; + private static final String WAF_TARGET_PREFIX = "AWSWAF_20190729."; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void associationFollowsTheTemplateAcrossReplacementAndStackDelete() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-wafv2-assoc-" + suffix; + + cfn("CreateStack", stackName, template(suffix, "AclA")); + String created = describeStack(stackName) + .body(containsString("CREATE_COMPLETE")) + .extract().asString(); + String poolArn = output(created, "PoolArn"); + String aclAArn = output(created, "AclAArn"); + String aclBArn = output(created, "AclBArn"); + + assertEquals(poolArn + "|" + aclAArn, output(created, "AssocRef")); + webAclForResource(poolArn).body("WebACL.ARN", equalTo(aclAArn)); + + cfn("UpdateStack", stackName, template(suffix, "AclB")); + String updated = describeStack(stackName) + .body(containsString("UPDATE_COMPLETE")) + .body(not(containsString("ROLLBACK"))) + .extract().asString(); + + assertEquals(poolArn + "|" + aclBArn, output(updated, "AssocRef")); + // The cleanup deleted the old pair, which must not have disassociated the pool from AclB. + webAclForResource(poolArn).body("WebACL.ARN", equalTo(aclBArn)); + resourcesForWebAcl(aclAArn).body("ResourceArns", empty()); + resourcesForWebAcl(aclBArn).body("ResourceArns", contains(poolArn)); + + cfn("DeleteStack", stackName, null); + + webAclForResource(poolArn).body("WebACL", nullValue()); + waf("ListWebACLs", "{\"Scope\":\"REGIONAL\"}") + .statusCode(200) + .body("WebACLs.ARN", not(hasItem(aclAArn))) + .body("WebACLs.ARN", not(hasItem(aclBArn))); + } + + private static String template(String suffix, String associatedAcl) { + return """ + { + "Resources": { + "Pool": { + "Type": "AWS::Cognito::UserPool", + "Properties": {"UserPoolName": "cfn-assoc-pool-%1$s"} + }, + "AclA": { + "Type": "AWS::WAFv2::WebACL", + "Properties": { + "Name": "cfn-assoc-a-%1$s", + "Scope": "REGIONAL", + "DefaultAction": {"Allow": {}}, + "VisibilityConfig": { + "SampledRequestsEnabled": false, + "CloudWatchMetricsEnabled": false, + "MetricName": "cfn-assoc-a-%1$s" + } + } + }, + "AclB": { + "Type": "AWS::WAFv2::WebACL", + "Properties": { + "Name": "cfn-assoc-b-%1$s", + "Scope": "REGIONAL", + "DefaultAction": {"Block": {}}, + "VisibilityConfig": { + "SampledRequestsEnabled": false, + "CloudWatchMetricsEnabled": false, + "MetricName": "cfn-assoc-b-%1$s" + } + } + }, + "Assoc": { + "Type": "AWS::WAFv2::WebACLAssociation", + "Properties": { + "ResourceArn": {"Fn::GetAtt": ["Pool", "Arn"]}, + "WebACLArn": {"Fn::GetAtt": ["%2$s", "Arn"]} + } + } + }, + "Outputs": { + "AssocRef": {"Value": {"Ref": "Assoc"}}, + "PoolArn": {"Value": {"Fn::GetAtt": ["Pool", "Arn"]}}, + "AclAArn": {"Value": {"Fn::GetAtt": ["AclA", "Arn"]}}, + "AclBArn": {"Value": {"Fn::GetAtt": ["AclB", "Arn"]}} + } + } + """.formatted(suffix, associatedAcl); + } + + private static String output(String describeXml, String key) { + return XmlPath.from(describeXml).getString("DescribeStacksResponse.DescribeStacksResult.Stacks.member" + + ".Outputs.member.find { it.OutputKey == '" + key + "' }.OutputValue"); + } + + private void cfn(String action, String stackName, String template) { + RequestSpecification request = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", action) + .formParam("StackName", stackName); + if (template != null) { + request.formParam("TemplateBody", template); + } + request.when().post("/").then().statusCode(200); + } + + private ValidatableResponse describeStack(String stackName) { + return given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200); + } + + private ValidatableResponse webAclForResource(String resourceArn) { + return waf("GetWebACLForResource", "{\"ResourceArn\":\"" + resourceArn + "\"}").statusCode(200); + } + + private ValidatableResponse resourcesForWebAcl(String webAclArn) { + return waf("ListResourcesForWebACL", + "{\"WebACLArn\":\"" + webAclArn + "\",\"ResourceType\":\"COGNITO_USER_POOL\"}").statusCode(200); + } + + private ValidatableResponse waf(String action, String body) { + return given() + .contentType(WAF_JSON) + .header("X-Amz-Target", WAF_TARGET_PREFIX + action) + .body(body) + .when() + .post("/") + .then(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/WafV2CfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/WafV2CfnProvisionerTest.java index cd712f21aa..e2596b0955 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/WafV2CfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/WafV2CfnProvisionerTest.java @@ -10,16 +10,20 @@ import io.github.hectorvent.floci.services.wafv2.WafV2Service; import io.github.hectorvent.floci.services.wafv2.model.WebAcl; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; 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.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -28,6 +32,12 @@ import static org.mockito.Mockito.when; class WafV2CfnProvisionerTest { + private static final String ASSOCIATION = "AWS::WAFv2::WebACLAssociation"; + private static final String POOL = "arn:aws:cognito-idp:us-east-1:111122223333:userpool/us-east-1_pool"; + private static final String POOL_2 = "arn:aws:cognito-idp:us-east-1:111122223333:userpool/us-east-1_pool2"; + private static final String ACL_A = "arn:aws:wafv2:us-east-1:111122223333:regional/webacl/a/acl-a"; + private static final String ACL_B = "arn:aws:wafv2:us-east-1:111122223333:regional/webacl/b/acl-b"; + private final WafV2Service wafV2 = mock(WafV2Service.class); private final WafV2CfnProvisioner provisioner = new WafV2CfnProvisioner(wafV2); private final ObjectMapper mapper = new ObjectMapper(); @@ -169,6 +179,189 @@ class WafV2CfnProvisionerTest { assertEquals("portal|acl-123|REGIONAL", resource.getPhysicalId()); } + @Test + void associationCreateAssociatesAndUsesResourceAndAclArnsAsPhysicalId() { + StackResource resource = associationResource(); + + provisioner.provision(resource, associationProps(ACL_A), context()); + + verify(wafV2).associateWebAcl(ACL_A, POOL); + assertEquals(POOL + "|" + ACL_A, resource.getPhysicalId()); + assertFalse(provisioner.hasReplacementUpdate(resource)); + } + + @Test + void unchangedUpdateKeepsIdAndDoesNotCallAssociateWebAcl() { + StackResource resource = associationResource(); + resource.setPhysicalId(POOL + "|" + ACL_A); + + provisioner.provision(resource, associationProps(ACL_A), updateContext(POOL + "|" + ACL_A)); + + assertEquals(POOL + "|" + ACL_A, resource.getPhysicalId()); + assertFalse(provisioner.hasReplacementUpdate(resource)); + verifyNoInteractions(wafV2); + } + + @Test + void associationWithoutResourceArnFailsBeforeCallingWafV2() { + ObjectNode props = associationProps(ACL_A); + props.remove("ResourceArn"); + + AwsException failure = assertThrows(AwsException.class, + () -> provisioner.provision(associationResource(), props, context())); + + assertEquals("ValidationError", failure.getErrorCode()); + assertEquals("AWS::WAFv2::WebACLAssociation requires ResourceArn", failure.getMessage()); + verifyNoInteractions(wafV2); + } + + @Test + void associationDeleteDisassociatesWhenResourceStillUsesThisAcl() { + when(wafV2.getWebAclForResource(POOL)).thenReturn(aclWithArn(ACL_A)); + + provisioner.delete(ASSOCIATION, POOL + "|" + ACL_A, "us-east-1"); + + verify(wafV2).disassociateWebAcl(POOL); + } + + @Test + void associationDeleteKeepsAnAssociationWithAnotherAcl() { + when(wafV2.getWebAclForResource(POOL)).thenReturn(aclWithArn(ACL_B)); + + provisioner.delete(ASSOCIATION, POOL + "|" + ACL_A, "us-east-1"); + + verify(wafV2, never()).disassociateWebAcl(anyString()); + } + + @Test + void associationDeleteIsNoOpWhenResourceHasNoAcl() { + provisioner.delete(ASSOCIATION, POOL + "|" + ACL_A, "us-east-1"); + + verify(wafV2).getWebAclForResource(POOL); + verify(wafV2, never()).disassociateWebAcl(anyString()); + } + + @Test + void replacingAssociationCleanupLeavesTheNewAssociationOnTheSameResource() { + StackResource resource = associationResource(); + resource.setPhysicalId(POOL + "|" + ACL_A); + + provisioner.provision(resource, associationProps(ACL_B), updateContext(POOL + "|" + ACL_A)); + + assertEquals(POOL + "|" + ACL_B, resource.getPhysicalId()); + assertTrue(provisioner.hasReplacementUpdate(resource)); + assertEquals(POOL + "|" + ACL_A, provisioner.updateCleanupPhysicalId(resource)); + when(wafV2.getWebAclForResource(POOL)).thenReturn(aclWithArn(ACL_B)); + + UpdateCleanupResult result = provisioner.completeUpdate(resource); + + assertTrue(result.complete()); + verify(wafV2).getWebAclForResource(POOL); + verify(wafV2, never()).disassociateWebAcl(anyString()); + } + + @Test + void rollbackUpdateRestoresThePriorAssociation() { + StackResource resource = associationResource(); + resource.setPhysicalId(POOL + "|" + ACL_A); + provisioner.provision(resource, associationProps(ACL_B), updateContext(POOL + "|" + ACL_A)); + when(wafV2.getWebAclForResource(POOL)).thenReturn(aclWithArn(ACL_B)); + + assertTrue(provisioner.rollbackUpdate(resource)); + + assertEquals(POOL + "|" + ACL_A, resource.getPhysicalId()); + assertFalse(provisioner.hasReplacementUpdate(resource)); + InOrder order = inOrder(wafV2); + order.verify(wafV2).associateWebAcl(ACL_B, POOL); + order.verify(wafV2).disassociateWebAcl(POOL); + order.verify(wafV2).associateWebAcl(ACL_A, POOL); + } + + @Test + void replacingResourceArnCleanupDisassociatesTheOldResource() { + StackResource resource = associationResource(); + resource.setPhysicalId(POOL + "|" + ACL_A); + + provisioner.provision(resource, associationProps(POOL_2, ACL_A), updateContext(POOL + "|" + ACL_A)); + + assertEquals(POOL_2 + "|" + ACL_A, resource.getPhysicalId()); + verify(wafV2).associateWebAcl(ACL_A, POOL_2); + assertTrue(provisioner.hasReplacementUpdate(resource)); + assertEquals(POOL + "|" + ACL_A, provisioner.updateCleanupPhysicalId(resource)); + when(wafV2.getWebAclForResource(POOL)).thenReturn(aclWithArn(ACL_A)); + + UpdateCleanupResult result = provisioner.completeUpdate(resource); + + assertTrue(result.complete()); + verify(wafV2).disassociateWebAcl(POOL); + verify(wafV2, never()).disassociateWebAcl(POOL_2); + } + + @Test + void rollbackOfResourceArnReplacementRestoresTheOldResource() { + StackResource resource = associationResource(); + resource.setPhysicalId(POOL + "|" + ACL_A); + provisioner.provision(resource, associationProps(POOL_2, ACL_A), updateContext(POOL + "|" + ACL_A)); + when(wafV2.getWebAclForResource(POOL_2)).thenReturn(aclWithArn(ACL_A)); + + assertTrue(provisioner.rollbackUpdate(resource)); + + assertEquals(POOL + "|" + ACL_A, resource.getPhysicalId()); + assertFalse(provisioner.hasReplacementUpdate(resource)); + InOrder order = inOrder(wafV2); + order.verify(wafV2).associateWebAcl(ACL_A, POOL_2); + order.verify(wafV2).disassociateWebAcl(POOL_2); + order.verify(wafV2).associateWebAcl(ACL_A, POOL); + verify(wafV2, never()).disassociateWebAcl(POOL); + } + + @Test + void rollbackUpdateWithoutReplacementSucceedsWithoutTouchingWafV2() { + StackResource resource = associationResource(); + resource.setPhysicalId(POOL + "|" + ACL_A); + + assertTrue(provisioner.rollbackUpdate(resource)); + + assertEquals(POOL + "|" + ACL_A, resource.getPhysicalId()); + verifyNoInteractions(wafV2); + } + + @Test + void webAclRollbackUpdateKeepsTheDefault() { + StackResource resource = resource(); + resource.setPhysicalId("portal|acl-123|REGIONAL"); + + assertFalse(provisioner.rollbackUpdate(resource)); + } + + private ObjectNode associationProps(String webAclArn) { + return associationProps(POOL, webAclArn); + } + + private ObjectNode associationProps(String resourceArn, String webAclArn) { + return mapper.createObjectNode().put("ResourceArn", resourceArn).put("WebACLArn", webAclArn); + } + + private ProvisionContext updateContext(String priorPhysicalId) { + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolveNode(any(JsonNode.class))).thenAnswer(inv -> inv.getArgument(0)); + return new ProvisionContext(engine, "us-east-1", "111122223333", "stack", priorPhysicalId); + } + + private StackResource associationResource() { + StackResource resource = new StackResource(); + resource.setLogicalId("Assoc"); + resource.setResourceType(ASSOCIATION); + resource.setAttributes(new HashMap<>()); + return resource; + } + + private WebAcl aclWithArn(String arn) { + WebAcl acl = new WebAcl(); + acl.setArn(arn); + return acl; + } + private void assertMissingRequiredPropertyFails(String property) { ObjectNode props = requiredProps("portal"); props.remove(property); diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 911395e3c9..982fe03fdd 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -151,4 +151,5 @@ AWS::ServiceDiscovery::Service CloudMapCfnProvisioner AWS::StepFunctions::StateMachine StepFunctionsCfnProvisioner AWS::Transfer::Server TransferCfnProvisioner AWS::WAFv2::WebACL WafV2CfnProvisioner +AWS::WAFv2::WebACLAssociation WafV2CfnProvisioner Custom::DynamoDBReplica DynamoDbCfnProvisioner