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
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-03 15:01:18 -05:00
1 parent 7ebbe868ca
commit 9e178d77a0
6 files changed
+644 -7

No files matched your search

@@ -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("<StackStatus>CREATE_COMPLETE</StackStatus>"))
.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("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
.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();
}
}
@@ -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);