feat(cloudformation): support WAFv2 logging configuration (#6194)

* feat(cloudformation): support WAFv2 logging configuration

* fix(cloudformation): honor WAFv2 logging replacement and rollback
This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-10-21 21:23:13 -04:00
1 parent 42fd858311
commit a8e49fbbaa
11 files changed
+607 -51

No files matched your search

+1 -1
View File
@@ -216,7 +216,7 @@ cross-resource references.
| CloudFront | `CachePolicy`, `Distribution`, `Function` (`KeyValueStoreAssociations` is ignored), `KeyGroup`, `OriginAccessControl`, `OriginRequestPolicy`, `PublicKey`, `ResponseHeadersPolicy` |
| CloudWatch | `Alarm`, `Dashboard` |
| CloudWatch Logs | `LogGroup`, `LogStream`, `MetricFilter` |
| WAFv2 | `IPSet`, `WebACL`, `WebACLAssociation` |
| WAFv2 | `IPSet`, `LoggingConfiguration`, `WebACL`, `WebACLAssociation` |
| Config | `ConfigRule` |
| Bedrock AgentCore | `Runtime` (Ref returns the AgentRuntimeId; CapacityProviderConfiguration, FilesystemConfigurations, LifecycleConfiguration, PlatformVersion and RequestHeaderConfiguration are accepted and not stored), `RuntimeEndpoint` (Ref returns the endpoint ARN; Tags are accepted and not stored), `Memory` (Ref returns the memory ARN; MemoryStrategies, IndexedKeys, NamespaceKeys and StreamDeliveryResources are accepted and not stored) |
| CloudFormation | `CustomResource`, `Custom::DynamoDBReplica` (applied natively against DynamoDB, not via a provider Lambda), `Stack` (nested stacks), `Custom::*` (Lambda-backed) |
@@ -79,6 +79,12 @@ public final class CfnRollback {
*/
public static final String EVENT_INVOKE_CONFIG_SNAPSHOT_ATTR = "__FlociEventInvokeConfigSnapshot";
/** The prior WAFv2 logging configuration for an in-place update that may need rollback. */
public static final String WAF_LOGGING_UPDATE_SNAPSHOT_ATTR = "__FlociWafLoggingUpdateSnapshot";
/** Marks an absent WAFv2 logging configuration that an in-place update recreated. */
public static final String WAF_LOGGING_UPDATE_ABSENT_ATTR = "__FlociWafLoggingUpdateAbsent";
/**
* Holds what a custom resource had before an update sent its handler an {@code Update}: the
* physical id, the old and the attempted properties, the region and the {@code Data} attributes,
@@ -24,6 +24,7 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
private static final String WEB_ACL = "AWS::WAFv2::WebACL";
private static final String WEB_ACL_ASSOCIATION = "AWS::WAFv2::WebACLAssociation";
private static final String IP_SET = "AWS::WAFv2::IPSet";
private static final String LOGGING_CONFIGURATION = "AWS::WAFv2::LoggingConfiguration";
private final WafV2Service wafV2Service;
@@ -34,7 +35,7 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
@Override
public Set<String> resourceTypes() {
return Set.of(WEB_ACL, WEB_ACL_ASSOCIATION, IP_SET);
return Set.of(WEB_ACL, WEB_ACL_ASSOCIATION, IP_SET, LOGGING_CONFIGURATION);
}
/**
@@ -56,6 +57,10 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
provisionIpSet(resource, props, ctx);
return;
}
if (LOGGING_CONFIGURATION.equals(resource.getResourceType())) {
provisionLoggingConfiguration(resource, props, ctx);
return;
}
JsonNode resolved = ctx.engine().resolveNode(props);
String scope = required(text(resolved, "Scope"), WEB_ACL, "Scope");
required(raw(resolved, "DefaultAction"), WEB_ACL, "DefaultAction");
@@ -147,6 +152,54 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
ReplacementCleanup.record(resource, ctx, attributesBefore);
}
private void provisionLoggingConfiguration(StackResource resource, JsonNode props, ProvisionContext ctx) {
resource.getAttributes().remove(CfnRollback.WAF_LOGGING_UPDATE_SNAPSHOT_ATTR);
resource.getAttributes().remove(CfnRollback.WAF_LOGGING_UPDATE_ABSENT_ATTR);
JsonNode resolved = ctx.engine().resolveNode(props);
String resourceArn = required(text(resolved, "ResourceArn"), LOGGING_CONFIGURATION, "ResourceArn");
JsonNode destinations = resolved.path("LogDestinationConfigs");
if (!destinations.isArray() || destinations.isEmpty()) {
throw new AwsException("ValidationError", LOGGING_CONFIGURATION + " requires LogDestinationConfigs", 400);
}
Map<String, String> attributesBefore = new HashMap<>(resource.getAttributes());
if (ctx.isUpdate() && resourceArn.equals(ctx.priorPhysicalId())) {
try {
String previous = wafV2Service.getLoggingConfiguration(resourceArn);
if (previous == null) {
resource.getAttributes().put(CfnRollback.WAF_LOGGING_UPDATE_ABSENT_ATTR, "true");
} else {
resource.getAttributes().put(CfnRollback.WAF_LOGGING_UPDATE_SNAPSHOT_ATTR, previous);
}
} catch (AwsException e) {
if (!"WAFNonexistentItemException".equals(e.getErrorCode())) {
throw e;
}
resource.getAttributes().put(CfnRollback.WAF_LOGGING_UPDATE_ABSENT_ATTR, "true");
}
} else {
rejectExistingLoggingConfiguration(resourceArn);
}
wafV2Service.putLoggingConfiguration(resourceArn, resolved.toString());
resource.setPhysicalId(resourceArn);
resource.getAttributes().put("ManagedByFirewallManager", "false");
ReplacementCleanup.record(resource, ctx, attributesBefore);
}
private void rejectExistingLoggingConfiguration(String resourceArn) {
try {
if (wafV2Service.getLoggingConfiguration(resourceArn) == null) {
return;
}
} catch (AwsException e) {
if ("WAFNonexistentItemException".equals(e.getErrorCode())) {
return;
}
throw e;
}
throw new AwsException("WAFDuplicateItemException",
"Logging configuration already exists for " + resourceArn, 400);
}
@Override
public void delete(String resourceType, String physicalId, String region) {
if (WEB_ACL_ASSOCIATION.equals(resourceType)) {
@@ -157,6 +210,10 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
deleteIpSet(physicalId);
return;
}
if (LOGGING_CONFIGURATION.equals(resourceType)) {
wafV2Service.deleteLoggingConfiguration(physicalId);
return;
}
WebAcl existing = findExisting(physicalId);
if (existing != null) {
wafV2Service.deleteWebAcl(existing.getScope(), existing.getId(), existing.getName(),
@@ -203,11 +260,18 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
return ReplacementCleanup.complete(resource, this::delete);
UpdateCleanupResult cleanup = ReplacementCleanup.complete(resource, this::delete);
if (!cleanup.applicable() && (resource.getAttributes().containsKey(CfnRollback.WAF_LOGGING_UPDATE_SNAPSHOT_ATTR)
|| resource.getAttributes().containsKey(CfnRollback.WAF_LOGGING_UPDATE_ABSENT_ATTR))) {
return new UpdateCleanupResult(true, true, null, 0, null);
}
return cleanup;
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.WAF_LOGGING_UPDATE_SNAPSHOT_ATTR);
resource.getAttributes().remove(CfnRollback.WAF_LOGGING_UPDATE_ABSENT_ATTR);
ReplacementCleanup.clear(resource);
}
@@ -226,6 +290,22 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
if (IP_SET.equals(resource.getResourceType())) {
return ReplacementCleanup.rollback(resource, this::delete);
}
if (LOGGING_CONFIGURATION.equals(resource.getResourceType())) {
if (ReplacementCleanup.rollback(resource, this::delete)) {
return true;
}
if (resource.getAttributes().containsKey(CfnRollback.WAF_LOGGING_UPDATE_ABSENT_ATTR)) {
wafV2Service.deleteLoggingConfiguration(resource.getPhysicalId());
resource.getAttributes().remove(CfnRollback.WAF_LOGGING_UPDATE_ABSENT_ATTR);
return true;
}
String previous = resource.getAttributes().get(CfnRollback.WAF_LOGGING_UPDATE_SNAPSHOT_ATTR);
if (previous != null) {
wafV2Service.putLoggingConfiguration(resource.getPhysicalId(), previous);
resource.getAttributes().remove(CfnRollback.WAF_LOGGING_UPDATE_SNAPSHOT_ATTR);
}
return true;
}
return false;
}
@@ -770,6 +770,9 @@
"Name",
"Scope"
],
"AWS::WAFv2::LoggingConfiguration": [
"ResourceArn"
],
"AWS::WAFv2::WebACL": [
"Name",
"Scope"
@@ -76,6 +76,15 @@ class CfnCreateOnlyPropertiesTest {
assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "Tags"));
}
@Test
void isCreateOnly_loggingConfigurationReplacesOnlyForResourceArn() {
String type = "AWS::WAFv2::LoggingConfiguration";
assertTrue(CfnCreateOnlyProperties.isCreateOnly(type, "ResourceArn"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "LogDestinationConfigs"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "RedactedFields"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "LoggingFilter"));
}
@Test
void isCreateOnly_treatsEmptySchemaListAsAuthoritative() {
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGateway::RestApi", "Name"));
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.CfnRequests;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
@@ -8,7 +9,7 @@ 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 io.github.hectorvent.floci.testing.WafV2Requests.waf;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
@@ -29,8 +30,6 @@ class CloudFormationWafV2IpSetIntegrationTest {
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() {
@@ -184,11 +183,7 @@ class CloudFormationWafV2IpSetIntegrationTest {
}
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);
RequestSpecification request = CfnRequests.cfn(action, stackName).header("Authorization", CFN_AUTH);
if (template != null) {
request.formParam("TemplateBody", template);
}
@@ -196,11 +191,8 @@ class CloudFormationWafV2IpSetIntegrationTest {
}
private ValidatableResponse describeStack(String stackName) {
return given()
.contentType("application/x-www-form-urlencoded")
return CfnRequests.cfn("DescribeStacks", stackName)
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
@@ -208,11 +200,8 @@ class CloudFormationWafV2IpSetIntegrationTest {
}
private ValidatableResponse describeStackEvents(String stackName) {
return given()
.contentType("application/x-www-form-urlencoded")
return CfnRequests.cfn("DescribeStackEvents", stackName)
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackEvents")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
@@ -227,14 +216,4 @@ class CloudFormationWafV2IpSetIntegrationTest {
private ValidatableResponse listIpSets() {
return waf("ListIPSets", "{\"Scope\":\"REGIONAL\"}").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();
}
}
@@ -0,0 +1,292 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.CfnRequests;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.github.hectorvent.floci.testing.CloudFormationSettingsProfile;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
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.github.hectorvent.floci.testing.WafV2Requests.waf;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(CloudFormationSettingsProfile.class)
class CloudFormationWafV2LoggingConfigurationIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void loggingConfigurationCreatesWithAwsRefAndGetAttAndIsDeletedWithItsStack() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-wafv2-logging-" + suffix;
cfn("CreateStack", stackName, template(suffix, "AclA", "LogGroupA", false));
CfnStackWaits.StackState created = CfnStackWaits.awaitTerminal(stackName, CFN_AUTH);
assertEquals("CREATE_COMPLETE", created.status(),
() -> CfnStackWaits.failedResourceReason(stackName, CFN_AUTH));
String describeXml = describeStack(stackName);
String aclArn = output(describeXml, "AclAArn");
String destinationArn = output(describeXml, "LogGroupAArn");
assertEquals(aclArn, output(describeXml, "LoggingRef"));
assertEquals("false", output(describeXml, "ManagedByFirewallManager"));
loggingConfiguration(aclArn)
.statusCode(200)
.body("LoggingConfiguration.ResourceArn", equalTo(aclArn))
.body("LoggingConfiguration.LogDestinationConfigs", contains(destinationArn));
assertNestedSettings(aclArn, "authorization", "KEEP");
cfn("DeleteStack", stackName, null);
CfnStackWaits.awaitStackDeleted(stackName, CFN_AUTH);
loggingConfiguration(aclArn)
.statusCode(400)
.body("__type", equalTo("WAFNonexistentItemException"));
}
@Test
void loggingConfigurationUpdatesInPlaceAndReplacesOnlyAfterCommit() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-wafv2-logging-update-" + suffix;
cfn("CreateStack", stackName, template(suffix, "AclA", "LogGroupA", false));
assertStatus(stackName, "CREATE_COMPLETE");
String created = describeStack(stackName);
String aclA = output(created, "AclAArn");
String aclB = output(created, "AclBArn");
String logA = output(created, "LogGroupAArn");
String logB = output(created, "LogGroupBArn");
assertStored(aclA, logA);
String changeSetName = "wafv2-logging-replacement-" + suffix;
CfnRequests.cfn("CreateChangeSet", stackName)
.header("Authorization", CFN_AUTH)
.formParam("ChangeSetName", changeSetName)
.formParam("ChangeSetType", "UPDATE")
.formParam("TemplateBody", template(suffix, "AclB", "LogGroupB", false))
.when().post("/").then().statusCode(200);
String changeSetXml = CfnRequests.cfn("DescribeChangeSet", stackName)
.header("Authorization", CFN_AUTH)
.formParam("ChangeSetName", changeSetName)
.when().post("/").then().statusCode(200).extract().asString();
assertEquals("True", XmlPath.from(changeSetXml).getString(
"DescribeChangeSetResponse.DescribeChangeSetResult.Changes.member"
+ ".find { it.ResourceChange.LogicalResourceId == 'Logging' }.ResourceChange.Replacement"));
cfn("UpdateStack", stackName, template(suffix, "AclA", "LogGroupB", false));
assertStatus(stackName, "UPDATE_COMPLETE");
assertEquals(aclA, output(describeStack(stackName), "LoggingRef"));
assertStored(aclA, logB);
assertNestedSettings(aclA, "cookie", "DROP");
cfn("UpdateStack", stackName, template(suffix, "AclA", "LogGroupA", true));
assertStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
assertStored(aclA, logB);
assertNestedSettings(aclA, "cookie", "DROP");
cfn("UpdateStack", stackName, template(suffix, "AclB", "LogGroupB", false));
assertStatus(stackName, "UPDATE_COMPLETE");
assertEquals(aclB, output(describeStack(stackName), "LoggingRef"));
assertStored(aclB, logB);
assertMissing(aclA);
cfn("UpdateStack", stackName, template(suffix, "AclA", "LogGroupA", true));
assertStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
assertEquals(aclB, output(describeStack(stackName), "LoggingRef"));
assertStored(aclB, logB);
assertMissing(aclA);
deleteLoggingConfiguration(aclB).statusCode(200);
assertMissing(aclB);
cfn("UpdateStack", stackName, template(suffix, "AclB", "LogGroupA", true));
assertStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
assertTrue(CfnStackWaits.failedResourceReason(stackName, CFN_AUTH).contains("AWS::Fake::Thing"));
assertMissing(aclB);
cfn("DeleteStack", stackName, null);
CfnStackWaits.awaitStackDeleted(stackName, CFN_AUTH);
assertMissing(aclB);
}
@Test
void replacementDoesNotOverwriteLoggingConfigurationOnTargetAcl() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-wafv2-logging-collision-" + suffix;
cfn("CreateStack", stackName, template(suffix, "AclA", "LogGroupA", false));
assertStatus(stackName, "CREATE_COMPLETE");
String created = describeStack(stackName);
String aclA = output(created, "AclAArn");
String aclB = output(created, "AclBArn");
String logA = output(created, "LogGroupAArn");
putLoggingConfiguration(aclB, logA).statusCode(200);
cfn("UpdateStack", stackName, template(suffix, "AclB", "LogGroupB", false));
assertStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
assertEquals(aclA, output(describeStack(stackName), "LoggingRef"));
assertStored(aclA, logA);
assertStored(aclB, logA);
deleteLoggingConfiguration(aclB).statusCode(200);
cfn("DeleteStack", stackName, null);
CfnStackWaits.awaitStackDeleted(stackName, CFN_AUTH);
}
private static String template(String suffix, String acl, String logGroup, boolean failAfterLogging) {
String redactedHeader = "LogGroupA".equals(logGroup) ? "authorization" : "cookie";
String defaultBehavior = "LogGroupA".equals(logGroup) ? "KEEP" : "DROP";
String failingResource = failAfterLogging
? """
,
"ZFail": {
"Type": "AWS::Fake::Thing",
"DependsOn": "Logging",
"Properties": {}
}
"""
: "";
return """
{
"Resources": {
"AclA": {
"Type": "AWS::WAFv2::WebACL",
"Properties": {
"Name": "cfn-wafv2-logging-a-%1$s",
"Scope": "REGIONAL",
"DefaultAction": {"Allow": {}},
"VisibilityConfig": {
"SampledRequestsEnabled": false,
"CloudWatchMetricsEnabled": false,
"MetricName": "cfn-wafv2-logging-a-%1$s"
}
}
},
"AclB": {
"Type": "AWS::WAFv2::WebACL",
"Properties": {
"Name": "cfn-wafv2-logging-b-%1$s",
"Scope": "REGIONAL",
"DefaultAction": {"Allow": {}},
"VisibilityConfig": {
"SampledRequestsEnabled": false,
"CloudWatchMetricsEnabled": false,
"MetricName": "cfn-wafv2-logging-b-%1$s"
}
}
},
"LogGroupA": {
"Type": "AWS::Logs::LogGroup",
"Properties": {"LogGroupName": "aws-waf-logs-cfn-%1$s-a"}
},
"LogGroupB": {
"Type": "AWS::Logs::LogGroup",
"Properties": {"LogGroupName": "aws-waf-logs-cfn-%1$s-b"}
},
"Logging": {
"Type": "AWS::WAFv2::LoggingConfiguration",
"Properties": {
"ResourceArn": {"Fn::GetAtt": ["%2$s", "Arn"]},
"LogDestinationConfigs": [{"Fn::GetAtt": ["%3$s", "Arn"]}],
"RedactedFields": [{"SingleHeader": {"Name": "%5$s"}}],
"LoggingFilter": {
"DefaultBehavior": "%6$s",
"Filters": [{
"Behavior": "KEEP",
"Requirement": "MEETS_ANY",
"Conditions": [{"ActionCondition": {"Action": "BLOCK"}}]
}]
}
}
}%4$s
},
"Outputs": {
"AclAArn": {"Value": {"Fn::GetAtt": ["AclA", "Arn"]}},
"AclBArn": {"Value": {"Fn::GetAtt": ["AclB", "Arn"]}},
"LogGroupAArn": {"Value": {"Fn::GetAtt": ["LogGroupA", "Arn"]}},
"LogGroupBArn": {"Value": {"Fn::GetAtt": ["LogGroupB", "Arn"]}},
"LoggingRef": {"Value": {"Ref": "Logging"}},
"ManagedByFirewallManager": {
"Value": {"Fn::GetAtt": ["Logging", "ManagedByFirewallManager"]}
}
}
}
""".formatted(suffix, acl, logGroup, failingResource, redactedHeader, defaultBehavior);
}
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 assertStatus(String stackName, String expected) {
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName, CFN_AUTH);
assertEquals(expected, state.status(), state.reason());
}
private void assertStored(String resourceArn, String destinationArn) {
loggingConfiguration(resourceArn)
.statusCode(200)
.body("LoggingConfiguration.ResourceArn", equalTo(resourceArn))
.body("LoggingConfiguration.LogDestinationConfigs", contains(destinationArn));
}
private void assertNestedSettings(String resourceArn, String redactedHeader, String defaultBehavior) {
loggingConfiguration(resourceArn)
.statusCode(200)
.body("LoggingConfiguration.RedactedFields[0].SingleHeader.Name", equalTo(redactedHeader))
.body("LoggingConfiguration.LoggingFilter.DefaultBehavior", equalTo(defaultBehavior))
.body("LoggingConfiguration.LoggingFilter.Filters[0].Conditions[0].ActionCondition.Action",
equalTo("BLOCK"));
}
private void assertMissing(String resourceArn) {
loggingConfiguration(resourceArn)
.statusCode(400)
.body("__type", equalTo("WAFNonexistentItemException"));
}
private ValidatableResponse loggingConfiguration(String resourceArn) {
return waf("GetLoggingConfiguration", "{\"ResourceArn\":\"" + resourceArn + "\"}");
}
private ValidatableResponse putLoggingConfiguration(String resourceArn, String destinationArn) {
return waf("PutLoggingConfiguration", "{\"LoggingConfiguration\":{\"ResourceArn\":\""
+ resourceArn + "\",\"LogDestinationConfigs\":[\"" + destinationArn + "\"]}}");
}
private ValidatableResponse deleteLoggingConfiguration(String resourceArn) {
return waf("DeleteLoggingConfiguration", "{\"ResourceArn\":\"" + resourceArn + "\"}");
}
private void cfn(String action, String stackName, String template) {
RequestSpecification request = CfnRequests.cfn(action, stackName).header("Authorization", CFN_AUTH);
if (template != null) {
request.formParam("TemplateBody", template);
}
request.when().post("/").then().statusCode(200);
}
private String describeStack(String stackName) {
return CfnRequests.cfn("DescribeStacks", stackName)
.header("Authorization", CFN_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString();
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.CfnRequests;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
@@ -8,7 +9,7 @@ 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 io.github.hectorvent.floci.testing.WafV2Requests.waf;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
@@ -28,8 +29,6 @@ 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() {
@@ -131,11 +130,7 @@ class CloudFormationWafV2WebAclAssociationIntegrationTest {
}
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);
RequestSpecification request = CfnRequests.cfn(action, stackName).header("Authorization", CFN_AUTH);
if (template != null) {
request.formParam("TemplateBody", template);
}
@@ -143,11 +138,8 @@ class CloudFormationWafV2WebAclAssociationIntegrationTest {
}
private ValidatableResponse describeStack(String stackName) {
return given()
.contentType("application/x-www-form-urlencoded")
return CfnRequests.cfn("DescribeStacks", stackName)
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
@@ -162,14 +154,4 @@ class CloudFormationWafV2WebAclAssociationIntegrationTest {
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();
}
}
@@ -19,6 +19,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;
@@ -37,6 +38,7 @@ class WafV2CfnProvisionerTest {
private static final String ASSOCIATION = "AWS::WAFv2::WebACLAssociation";
private static final String IP_SET_TYPE = "AWS::WAFv2::IPSet";
private static final String LOGGING_CONFIGURATION = "AWS::WAFv2::LoggingConfiguration";
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";
@@ -574,6 +576,189 @@ class WafV2CfnProvisionerTest {
assertFalse(provisioner.rollbackUpdate(resource));
}
@Test
void loggingConfigurationCreatesWithResourceArnAsRef() {
StackResource resource = loggingResource();
ObjectNode props = loggingProps(ACL_A, "arn:logs:a");
provisioner.provision(resource, props, context());
verify(wafV2).putLoggingConfiguration(ACL_A, props.toString());
assertEquals(ACL_A, resource.getPhysicalId());
assertEquals("false", resource.getAttributes().get("ManagedByFirewallManager"));
}
@Test
void loggingConfigurationRequiresResourceArnAndDestinations() {
ObjectNode withoutArn = loggingProps(ACL_A, "arn:logs:a");
withoutArn.remove("ResourceArn");
AwsException missingArn = assertThrows(AwsException.class,
() -> provisioner.provision(loggingResource(), withoutArn, context()));
assertEquals("AWS::WAFv2::LoggingConfiguration requires ResourceArn", missingArn.getMessage());
ObjectNode withoutDestinations = loggingProps(ACL_A, "arn:logs:a");
withoutDestinations.remove("LogDestinationConfigs");
AwsException missingDestinations = assertThrows(AwsException.class,
() -> provisioner.provision(loggingResource(), withoutDestinations, context()));
assertEquals("AWS::WAFv2::LoggingConfiguration requires LogDestinationConfigs",
missingDestinations.getMessage());
verifyNoInteractions(wafV2);
}
@Test
void loggingConfigurationCreateDoesNotOverwriteExistingConfiguration() {
String existing = loggingProps(ACL_A, "arn:logs:external").toString();
when(wafV2.getLoggingConfiguration(ACL_A)).thenReturn(existing);
StackResource resource = loggingResource();
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.provision(resource, loggingProps(ACL_A, "arn:logs:new"), context()));
assertEquals("WAFDuplicateItemException", failure.getErrorCode());
assertNull(resource.getPhysicalId());
verify(wafV2, never()).putLoggingConfiguration(anyString(), anyString());
verify(wafV2, never()).deleteLoggingConfiguration(anyString());
}
@Test
void loggingConfigurationSameArnUpdateRestoresPreviousSettingsOnRollback() {
String previous = loggingProps(ACL_A, "arn:logs:old").toString();
when(wafV2.getLoggingConfiguration(ACL_A)).thenReturn(previous);
StackResource resource = loggingResource();
resource.setPhysicalId(ACL_A);
ObjectNode updated = loggingProps(ACL_A, "arn:logs:new");
provisioner.provision(resource, updated, updateContext(ACL_A));
assertEquals(ACL_A, resource.getPhysicalId());
assertFalse(provisioner.hasReplacementUpdate(resource));
assertEquals(previous, resource.getAttributes().get(CfnRollback.WAF_LOGGING_UPDATE_SNAPSHOT_ATTR));
assertTrue(provisioner.rollbackUpdate(resource));
InOrder order = inOrder(wafV2);
order.verify(wafV2).putLoggingConfiguration(ACL_A, updated.toString());
order.verify(wafV2).putLoggingConfiguration(ACL_A, previous);
assertFalse(resource.getAttributes().containsKey(CfnRollback.WAF_LOGGING_UPDATE_SNAPSHOT_ATTR));
}
@Test
void loggingConfigurationSameArnUpdateAfterExternalDeletionRemovesRecreatedConfigOnRollback() {
when(wafV2.getLoggingConfiguration(ACL_A)).thenThrow(
new AwsException("WAFNonexistentItemException", "No logging configuration", 400));
StackResource resource = loggingResource();
resource.setPhysicalId(ACL_A);
ObjectNode updated = loggingProps(ACL_A, "arn:logs:new");
provisioner.provision(resource, updated, updateContext(ACL_A));
assertEquals(ACL_A, resource.getPhysicalId());
assertFalse(provisioner.hasReplacementUpdate(resource));
assertEquals("true", resource.getAttributes().get(CfnRollback.WAF_LOGGING_UPDATE_ABSENT_ATTR));
assertTrue(provisioner.rollbackUpdate(resource));
verify(wafV2).putLoggingConfiguration(ACL_A, updated.toString());
verify(wafV2).deleteLoggingConfiguration(ACL_A);
assertFalse(resource.getAttributes().containsKey(CfnRollback.WAF_LOGGING_UPDATE_ABSENT_ATTR));
}
@Test
void loggingConfigurationSameArnUpdateAfterExternalDeletionClearsMarkerOnCommit() {
when(wafV2.getLoggingConfiguration(ACL_A)).thenThrow(
new AwsException("WAFNonexistentItemException", "No logging configuration", 400));
StackResource resource = loggingResource();
resource.setPhysicalId(ACL_A);
provisioner.provision(resource, loggingProps(ACL_A, "arn:logs:new"), updateContext(ACL_A));
assertTrue(provisioner.completeUpdate(resource).applicable());
provisioner.clearUpdate(resource);
assertFalse(resource.getAttributes().containsKey(CfnRollback.WAF_LOGGING_UPDATE_ABSENT_ATTR));
verify(wafV2, never()).deleteLoggingConfiguration(anyString());
}
@Test
void loggingConfigurationSameArnUpdateClearsSnapshotAfterCommit() {
String previous = loggingProps(ACL_A, "arn:logs:old").toString();
when(wafV2.getLoggingConfiguration(ACL_A)).thenReturn(previous);
StackResource resource = loggingResource();
resource.setPhysicalId(ACL_A);
provisioner.provision(resource, loggingProps(ACL_A, "arn:logs:new"), updateContext(ACL_A));
assertTrue(provisioner.completeUpdate(resource).applicable());
provisioner.clearUpdate(resource);
assertFalse(resource.getAttributes().containsKey(CfnRollback.WAF_LOGGING_UPDATE_SNAPSHOT_ATTR));
}
@Test
void loggingConfigurationReplacementDoesNotOverwriteExistingTarget() {
String existing = loggingProps(ACL_B, "arn:logs:external").toString();
when(wafV2.getLoggingConfiguration(ACL_B)).thenReturn(existing);
StackResource resource = loggingResource();
resource.setPhysicalId(ACL_A);
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.provision(resource, loggingProps(ACL_B, "arn:logs:new"), updateContext(ACL_A)));
assertEquals("WAFDuplicateItemException", failure.getErrorCode());
assertEquals(ACL_A, resource.getPhysicalId());
assertFalse(provisioner.hasReplacementUpdate(resource));
verify(wafV2, never()).putLoggingConfiguration(anyString(), anyString());
verify(wafV2, never()).deleteLoggingConfiguration(anyString());
}
@Test
void loggingConfigurationReplacementDeletesOldArnOnlyAfterCommit() {
StackResource resource = loggingResource();
resource.setPhysicalId(ACL_A);
provisioner.provision(resource, loggingProps(ACL_B, "arn:logs:b"), updateContext(ACL_A));
assertEquals(ACL_B, resource.getPhysicalId());
assertTrue(provisioner.hasReplacementUpdate(resource));
assertEquals(ACL_A, provisioner.updateCleanupPhysicalId(resource));
verify(wafV2, never()).deleteLoggingConfiguration(anyString());
assertTrue(provisioner.completeUpdate(resource).complete());
verify(wafV2).deleteLoggingConfiguration(ACL_A);
verify(wafV2, never()).deleteLoggingConfiguration(ACL_B);
}
@Test
void loggingConfigurationReplacementRollbackKeepsOldArn() {
StackResource resource = loggingResource();
resource.setPhysicalId(ACL_A);
resource.getAttributes().put("ManagedByFirewallManager", "false");
provisioner.provision(resource, loggingProps(ACL_B, "arn:logs:b"), updateContext(ACL_A));
assertTrue(provisioner.rollbackUpdate(resource));
assertEquals(ACL_A, resource.getPhysicalId());
assertEquals("false", resource.getAttributes().get("ManagedByFirewallManager"));
assertFalse(provisioner.hasReplacementUpdate(resource));
verify(wafV2).deleteLoggingConfiguration(ACL_B);
verify(wafV2, never()).deleteLoggingConfiguration(ACL_A);
}
@Test
void loggingConfigurationDeleteRemovesStoredConfiguration() {
provisioner.delete(LOGGING_CONFIGURATION, ACL_A, "us-east-1");
verify(wafV2).deleteLoggingConfiguration(ACL_A);
}
private ObjectNode loggingProps(String resourceArn, String destinationArn) {
ObjectNode props = mapper.createObjectNode().put("ResourceArn", resourceArn);
props.set("LogDestinationConfigs", mapper.createArrayNode().add(destinationArn));
return props;
}
private StackResource loggingResource() {
StackResource resource = new StackResource();
resource.setLogicalId("Logging");
resource.setResourceType(LOGGING_CONFIGURATION);
resource.setAttributes(new HashMap<>());
return resource;
}
private void assertMissingIpSetPropertyFails(String property) {
ObjectNode props = ipSetProps("blocklist");
props.remove(property);
@@ -0,0 +1,19 @@
package io.github.hectorvent.floci.testing;
import io.restassured.response.ValidatableResponse;
import static io.restassured.RestAssured.given;
public final class WafV2Requests {
private WafV2Requests() {}
public static ValidatableResponse waf(String action, String body) {
return given()
.contentType("application/x-amz-json-1.1")
.header("X-Amz-Target", "AWSWAF_20190729." + action)
.body(body)
.when()
.post("/")
.then();
}
}
@@ -185,6 +185,7 @@ AWS::StepFunctions::StateMachine StepFunctionsCfnProvisioner
AWS::Transfer::Server TransferCfnProvisioner
AWS::Transfer::User TransferCfnProvisioner
AWS::WAFv2::IPSet WafV2CfnProvisioner
AWS::WAFv2::LoggingConfiguration WafV2CfnProvisioner
AWS::WAFv2::WebACL WafV2CfnProvisioner
AWS::WAFv2::WebACLAssociation WafV2CfnProvisioner
Custom::DynamoDBReplica DynamoDbCfnProvisioner
1 AWS::ApiGateway::Account ApiGatewayAccountCfnProvisioner
185 AWS::Transfer::Server TransferCfnProvisioner
186 AWS::Transfer::User TransferCfnProvisioner
187 AWS::WAFv2::IPSet WafV2CfnProvisioner
188 AWS::WAFv2::LoggingConfiguration WafV2CfnProvisioner
189 AWS::WAFv2::WebACL WafV2CfnProvisioner
190 AWS::WAFv2::WebACLAssociation WafV2CfnProvisioner
191 Custom::DynamoDBReplica DynamoDbCfnProvisioner