Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(cloudformation): provision AWS::WAFv2::IPSet (#5950)

Matheus Oliveiraa57c20943a6b
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index 8fad335608..116c3693db 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -214,7 +214,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 | `WebACL`, `WebACLAssociation` |
+| WAFv2 | `IPSet`, `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) |
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 8f112855a3..8cfe9c6777 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
@@ -4,6 +4,7 @@ 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.wafv2.WafV2Service;
+import io.github.hectorvent.floci.services.wafv2.model.IpSet;
import io.github.hectorvent.floci.services.wafv2.model.WebAcl;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -22,6 +23,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 static final String IP_SET = "AWS::WAFv2::IPSet";
private final WafV2Service wafV2Service;
@@ -32,7 +34,7 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
@Override
public Set<String> resourceTypes() {
- return Set.of(WEB_ACL, WEB_ACL_ASSOCIATION);
+ return Set.of(WEB_ACL, WEB_ACL_ASSOCIATION, IP_SET);
}
@Override
@@ -41,6 +43,10 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
provisionAssociation(resource, props, ctx);
return;
}
+ if (IP_SET.equals(resource.getResourceType())) {
+ provisionIpSet(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");
@@ -57,7 +63,7 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
if (existing != null && existing.getName().equals(name) && existing.getScope().equals(scope)) {
wafV2Service.updateWebAcl(desired, scope, existing.getId(), name, existing.getLockToken());
acl = wafV2Service.getWebAcl(scope, existing.getId(), name);
- reconcileTags(acl, desired.getTags());
+ reconcileTags(acl.getArn(), desired.getTags());
} else {
acl = wafV2Service.createWebAcl(desired, scope, name, ctx.region());
setReferences(resource, acl);
@@ -93,12 +99,55 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
ReplacementCleanup.record(resource, ctx, attributesBefore);
}
+ /**
+ * {@code Name} is optional and AWS generates one when the template omits it, so the Web ACL arm's
+ * rule applies: reuse the existing set's name on an update, generate one only on a create.
+ * {@code Name} and {@code Scope} are create-only, so a changed one leaves a new
+ * {@code name|id|scope} id and the prior set goes to {@link ReplacementCleanup}, which deletes it
+ * once the update commits or points the resource back at it on a rollback. {@code Addresses},
+ * {@code Description} and {@code Tags} update in place, and {@code IPAddressVersion} is never
+ * passed to the update, which cannot change it on AWS either.
+ */
+ private void provisionIpSet(StackResource resource, JsonNode props, ProvisionContext ctx) {
+ JsonNode resolved = ctx.engine().resolveNode(props);
+ String scope = required(text(resolved, "Scope"), IP_SET, "Scope");
+ String ipAddressVersion = ipAddressVersion(resolved);
+ List<String> addresses = requiredAddresses(resolved);
+ Map<String, String> attributesBefore = new HashMap<>(resource.getAttributes());
+ IpSet existing = findExistingIpSet(resource.getPhysicalId());
+ String name = text(resolved, "Name");
+ if (name == null || name.isBlank()) {
+ name = existing == null
+ ? ctx.generatePhysicalName(resource.getLogicalId(), 128, false)
+ : existing.getName();
+ }
+ if (existing != null && existing.getName().equals(name) && existing.getScope().equals(scope)) {
+ wafV2Service.updateIpSet(scope, existing.getId(), text(resolved, "Description"), addresses,
+ name, existing.getLockToken());
+ IpSet updated = wafV2Service.getIpSet(scope, existing.getId(), name);
+ reconcileTags(updated.getArn(), tags(resolved));
+ setIpSetReferences(resource, updated);
+ return;
+ }
+ IpSet desired = new IpSet();
+ desired.setDescription(text(resolved, "Description"));
+ desired.setIpAddressVersion(ipAddressVersion);
+ desired.setAddresses(addresses);
+ desired.setTags(tags(resolved));
+ setIpSetReferences(resource, wafV2Service.createIpSet(desired, scope, name, ctx.region()));
+ ReplacementCleanup.record(resource, ctx, attributesBefore);
+ }
+
@Override
public void delete(String resourceType, String physicalId, String region) {
if (WEB_ACL_ASSOCIATION.equals(resourceType)) {
deleteAssociation(physicalId);
return;
}
+ if (IP_SET.equals(resourceType)) {
+ deleteIpSet(physicalId);
+ return;
+ }
WebAcl existing = findExisting(physicalId);
if (existing != null) {
wafV2Service.deleteWebAcl(existing.getScope(), existing.getId(), existing.getName(),
@@ -106,6 +155,17 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
}
}
+ private void deleteIpSet(String physicalId) {
+ IpSet existing = findExistingIpSet(physicalId);
+ if (existing == null) {
+ return;
+ }
+ CfnDeletes.safeDelete("WAFv2 IP set", physicalId,
+ () -> wafV2Service.deleteIpSet(existing.getScope(), existing.getId(), existing.getName(),
+ existing.getLockToken()),
+ "WAFNonexistentItemException");
+ }
+
/**
* 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
@@ -144,17 +204,20 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
@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]);
+ if (WEB_ACL_ASSOCIATION.equals(resource.getResourceType())) {
+ 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;
}
- return true;
+ if (IP_SET.equals(resource.getResourceType())) {
+ return ReplacementCleanup.rollback(resource, this::delete);
+ }
+ return false;
}
private static String[] associationPair(String physicalId) {
@@ -179,6 +242,11 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
tokens.forEach(token -> tokenDomains.add(token.asText()));
}
acl.setTokenDomains(tokenDomains);
+ acl.setTags(tags(props));
+ return acl;
+ }
+
+ private Map<String, String> tags(JsonNode props) {
Map<String, String> tags = new LinkedHashMap<>();
JsonNode tagNodes = props.path("Tags");
if (tagNodes.isArray()) {
@@ -189,8 +257,23 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
}
}
}
- acl.setTags(tags);
- return acl;
+ return tags;
+ }
+
+ private List<String> requiredAddresses(JsonNode props) {
+ JsonNode node = props.get("Addresses");
+ if (node == null || node.isNull() || !node.isArray()) {
+ throw new AwsException("ValidationError", IP_SET + " requires Addresses", 400);
+ }
+ List<String> addresses = new ArrayList<>();
+ node.forEach(address -> addresses.add(address.asText()));
+ return addresses;
+ }
+
+ private String ipAddressVersion(JsonNode props) {
+ String version = required(text(props, "IPAddressVersion"), IP_SET, "IPAddressVersion");
+ WafV2Service.requireIpAddressVersion(version);
+ return version;
}
private static String required(String value, String resourceType, String property) {
@@ -200,14 +283,14 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
return value;
}
- private void reconcileTags(WebAcl existing, Map<String, String> desired) {
- List<String> removed = wafV2Service.listTagsForResource(existing.getArn()).keySet().stream()
+ private void reconcileTags(String resourceArn, Map<String, String> desired) {
+ List<String> removed = wafV2Service.listTagsForResource(resourceArn).keySet().stream()
.filter(key -> !desired.containsKey(key)).toList();
if (!removed.isEmpty()) {
- wafV2Service.untagResource(existing.getArn(), removed);
+ wafV2Service.untagResource(resourceArn, removed);
}
if (!desired.isEmpty()) {
- wafV2Service.tagResource(existing.getArn(), desired);
+ wafV2Service.tagResource(resourceArn, desired);
}
}
@@ -222,6 +305,17 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
.orElse(null);
}
+ private IpSet findExistingIpSet(String physicalId) {
+ String[] parts = physicalId == null ? new String[0] : physicalId.split("\\|", -1);
+ if (parts.length != 3) {
+ return null;
+ }
+ return wafV2Service.listIpSets(parts[2]).stream()
+ .filter(ipSet -> parts[1].equals(ipSet.getId()))
+ .findFirst()
+ .orElse(null);
+ }
+
private void setReferences(StackResource resource, WebAcl acl) {
resource.setPhysicalId(acl.getName() + "|" + acl.getId() + "|" + acl.getScope());
resource.getAttributes().put("Arn", acl.getArn());
@@ -230,6 +324,12 @@ public class WafV2CfnProvisioner implements CfnResourceProvisioner {
resource.getAttributes().put("LabelNamespace", acl.getLabelNamespace());
}
+ private void setIpSetReferences(StackResource resource, IpSet ipSet) {
+ resource.setPhysicalId(ipSet.getName() + "|" + ipSet.getId() + "|" + ipSet.getScope());
+ resource.getAttributes().put("Arn", ipSet.getArn());
+ resource.getAttributes().put("Id", ipSet.getId());
+ }
+
private String text(JsonNode node, String field) {
JsonNode value = node == null ? null : node.get(field);
return value == null || value.isNull() ? null : value.asText();
diff --git a/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Service.java b/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Service.java
index 14e6d04299..16ec0eaeee 100644
--- a/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Service.java
@@ -548,6 +548,17 @@ public class WafV2Service {
}
}
+ /**
+ * The single IPV4/IPV6 rule for a set's {@code IPAddressVersion}, also called by
+ * {@code WafV2CfnProvisioner}: an in-place update never sends the member to
+ * {@code UpdateIPSet}, so the provisioner would otherwise accept a value WAFv2 never sees.
+ */
+ public static void requireIpAddressVersion(String ipAddressVersion) {
+ if (!"IPV4".equals(ipAddressVersion) && !"IPV6".equals(ipAddressVersion)) {
+ throw invalidParameter("IP_ADDRESS_VERSION", ipAddressVersion, "must be IPV4 or IPV6.");
+ }
+ }
+
/**
* Validates that every entry in an IPSet's {@code Addresses} is a CIDR block matching
* the declared {@code IPAddressVersion}, per the {@code CreateIPSet}/{@code UpdateIPSet}
@@ -555,10 +566,8 @@ public class WafV2Service {
* 1-32 for IPv4 or 1-128 for IPv6 (AWS WAF supports all CIDR ranges except {@code /0}).
*/
private void validateAddresses(List<String> addresses, String ipAddressVersion) {
+ requireIpAddressVersion(ipAddressVersion);
boolean ipv6 = "IPV6".equals(ipAddressVersion);
- if (!ipv6 && !"IPV4".equals(ipAddressVersion)) {
- throw invalidParameter("IP_ADDRESS_VERSION", ipAddressVersion, "must be IPV4 or IPV6.");
- }
if (addresses == null || addresses.isEmpty()) {
return;
}
@@ -607,7 +616,7 @@ public class WafV2Service {
* carried as structured extendedData, matching the real WAFV2 {@code ParameterExceptionField}
* enum (e.g. {@code IP_ADDRESS}, {@code IP_ADDRESS_VERSION}) rather than a free-text message.
*/
- private AwsException invalidParameter(String field, String parameter, String reason) {
+ private static AwsException invalidParameter(String field, String parameter, String reason) {
Map<String, Object> extendedData = new LinkedHashMap<>();
extendedData.put("Field", field);
extendedData.put("Parameter", parameter);
diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.json
index 39af4a7452..ef6bad78f5 100644
--- a/src/main/resources/cloudformation/create-only-properties.json
+++ b/src/main/resources/cloudformation/create-only-properties.json
@@ -752,6 +752,10 @@
"StateMachineName",
"StateMachineType"
],
+ "AWS::WAFv2::IPSet": [
+ "Name",
+ "Scope"
+ ],
"AWS::WAFv2::WebACL": [
"Name",
"Scope"
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCreateOnlyPropertiesTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCreateOnlyPropertiesTest.java
index f133739ce0..9cfd78d5ec 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCreateOnlyPropertiesTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCreateOnlyPropertiesTest.java
@@ -51,6 +51,17 @@ class CfnCreateOnlyPropertiesTest {
assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "Tags"));
}
+ @Test
+ void isCreateOnly_ipSetReplacesOnlyForNameAndScope() {
+ String type = "AWS::WAFv2::IPSet";
+ assertTrue(CfnCreateOnlyProperties.isCreateOnly(type, "Name"));
+ assertTrue(CfnCreateOnlyProperties.isCreateOnly(type, "Scope"));
+ assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "Addresses"));
+ assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "Description"));
+ assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "IPAddressVersion"));
+ assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "Tags"));
+ }
+
@Test
void isCreateOnly_treatsEmptySchemaListAsAuthoritative() {
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGateway::RestApi", "Name"));
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationWafV2IpSetIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationWafV2IpSetIntegrationTest.java
new file mode 100644
index 0000000000..6f15810325
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationWafV2IpSetIntegrationTest.java
@@ -0,0 +1,240 @@
+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.equalTo;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.not;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+
+/**
+ * AWS::WAFv2::IPSet through a stack: Ref is {@code name|id|scope}, {@code Fn::GetAtt} resolves the
+ * real {@code Arn} and {@code Id} rather than literal placeholders, an {@code Addresses} change
+ * updates in place keeping the id, a rename replaces the set, an omitted {@code Name} still gets a
+ * generated one, and deleting the stack deletes it. Every assertion reads WAFv2 back, not only the
+ * stack.
+ */
+@QuarkusTest
+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() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void ipSetFollowsTheTemplateAcrossCreateUpdateAndStackDelete() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-wafv2-ipset-" + suffix;
+ String nameA = "cfn-ipset-a-" + suffix;
+ String nameB = "cfn-ipset-b-" + suffix;
+
+ cfn("CreateStack", stackName, template(nameA, "\"192.0.2.1/32\""));
+ String created = describeStack(stackName)
+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
+ .extract().asString();
+ String id = output(created, "IpSetId");
+ String arn = output(created, "IpSetArn");
+
+ assertFalse(id.contains("IpSet."), "Fn::GetAtt Id resolved to a literal placeholder");
+ assertFalse(arn.contains("IpSet."), "Fn::GetAtt Arn resolved to a literal placeholder");
+ assertEquals(nameA + "|" + id + "|REGIONAL", output(created, "IpSetRef"));
+ ipSet(nameA, id)
+ .body("IPSet.ARN", equalTo(arn))
+ .body("IPSet.Addresses", contains("192.0.2.1/32"));
+
+ cfn("UpdateStack", stackName, template(nameA, "\"198.51.100.0/24\""));
+ String addressesUpdated = describeStack(stackName)
+ .body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
+ .extract().asString();
+
+ assertEquals(id, output(addressesUpdated, "IpSetId"));
+ assertEquals(arn, output(addressesUpdated, "IpSetArn"));
+ ipSet(nameA, id).body("IPSet.Addresses", contains("198.51.100.0/24"));
+
+ cfn("UpdateStack", stackName, template(nameB, "\"198.51.100.0/24\""));
+ String replaced = describeStack(stackName)
+ .body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
+ .body(not(containsString("ROLLBACK")))
+ .extract().asString();
+
+ String replacementId = output(replaced, "IpSetId");
+ String replacementArn = output(replaced, "IpSetArn");
+ assertFalse(replacementId.equals(id), "a renamed IP set must be replaced, not updated in place");
+ assertEquals(nameB + "|" + replacementId + "|REGIONAL", output(replaced, "IpSetRef"));
+ ipSet(nameB, replacementId).body("IPSet.ARN", equalTo(replacementArn));
+ listIpSets()
+ .body("IPSets.ARN", not(hasItem(arn)))
+ .body("IPSets.ARN", hasItem(replacementArn));
+
+ cfn("DeleteStack", stackName, null);
+
+ listIpSets().body("IPSets.ARN", not(hasItem(replacementArn)));
+ }
+
+ @Test
+ void createStackWithoutIpSetAddressesFailsWithRequiredPropertyReason() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-wafv2-ipset-required-" + suffix;
+ String template = """
+ {
+ "Resources": {
+ "IpSet": {
+ "Type": "AWS::WAFv2::IPSet",
+ "Properties": {
+ "Name": "cfn-ipset-required-%s",
+ "Scope": "REGIONAL",
+ "IPAddressVersion": "IPV4"
+ }
+ }
+ }
+ }
+ """.formatted(suffix);
+
+ cfn("CreateStack", stackName, template);
+
+ describeStackEvents(stackName)
+ .body(containsString("<ResourceStatus>CREATE_FAILED</ResourceStatus>"))
+ .body(containsString(
+ "<ResourceStatusReason>AWS::WAFv2::IPSet requires Addresses</ResourceStatusReason>"));
+ }
+
+ @Test
+ void createStackWithoutIpSetNameStillCreatesTheSet() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-wafv2-ipset-anon-" + suffix;
+ String template = """
+ {
+ "Resources": {
+ "IpSet": {
+ "Type": "AWS::WAFv2::IPSet",
+ "Properties": {
+ "Scope": "REGIONAL",
+ "IPAddressVersion": "IPV4",
+ "Addresses": ["203.0.113.10/32"]
+ }
+ }
+ },
+ "Outputs": {
+ "IpSetRef": {"Value": {"Ref": "IpSet"}},
+ "IpSetArn": {"Value": {"Fn::GetAtt": ["IpSet", "Arn"]}},
+ "IpSetId": {"Value": {"Fn::GetAtt": ["IpSet", "Id"]}}
+ }
+ }
+ """;
+
+ cfn("CreateStack", stackName, template);
+ String created = describeStack(stackName)
+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
+ .extract().asString();
+
+ String ref = output(created, "IpSetRef");
+ String generatedName = ref.substring(0, ref.indexOf('|'));
+ assertFalse(generatedName.isBlank(), "an IP set without Name must still get a generated one");
+ ipSet(generatedName, output(created, "IpSetId"))
+ .body("IPSet.ARN", equalTo(output(created, "IpSetArn")));
+
+ cfn("DeleteStack", stackName, null);
+
+ listIpSets().body("IPSets.ARN", not(hasItem(output(created, "IpSetArn"))));
+ }
+
+ private static String template(String name, String addresses) {
+ return """
+ {
+ "Resources": {
+ "IpSet": {
+ "Type": "AWS::WAFv2::IPSet",
+ "Properties": {
+ "Name": "%1$s",
+ "Scope": "REGIONAL",
+ "IPAddressVersion": "IPV4",
+ "Addresses": [%2$s],
+ "Description": "cfn ip set"
+ }
+ }
+ },
+ "Outputs": {
+ "IpSetRef": {"Value": {"Ref": "IpSet"}},
+ "IpSetArn": {"Value": {"Fn::GetAtt": ["IpSet", "Arn"]}},
+ "IpSetId": {"Value": {"Fn::GetAtt": ["IpSet", "Id"]}}
+ }
+ }
+ """.formatted(name, addresses);
+ }
+
+ 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 describeStackEvents(String stackName) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DescribeStackEvents")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ private ValidatableResponse ipSet(String name, String id) {
+ return waf("GetIPSet", "{\"Name\":\"" + name + "\",\"Scope\":\"REGIONAL\",\"Id\":\"" + id + "\"}")
+ .statusCode(200);
+ }
+
+ 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();
+ }
+}
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 e2596b0955..1552a1216a 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
@@ -7,6 +7,7 @@ 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.wafv2.WafV2Service;
+import io.github.hectorvent.floci.services.wafv2.model.IpSet;
import io.github.hectorvent.floci.services.wafv2.model.WebAcl;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
@@ -21,8 +22,10 @@ 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.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -33,6 +36,7 @@ import static org.mockito.Mockito.when;
class WafV2CfnProvisionerTest {
private static final String ASSOCIATION = "AWS::WAFv2::WebACLAssociation";
+ private static final String IP_SET_TYPE = "AWS::WAFv2::IPSet";
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";
@@ -114,7 +118,7 @@ class WafV2CfnProvisionerTest {
when(wafV2.listWebAcls("REGIONAL")).thenReturn(List.of(existing));
when(wafV2.createWebAcl(any(), eq("REGIONAL"), eq("portal-renamed"), eq("us-east-1")))
.thenReturn(created);
- org.mockito.Mockito.doThrow(new RuntimeException("WAFAssociatedItemException"))
+ doThrow(new RuntimeException("WAFAssociatedItemException"))
.when(wafV2).deleteWebAcl("REGIONAL", "acl-old", "portal", "lock-1");
StackResource resource = resource();
resource.setPhysicalId("portal|acl-old|REGIONAL");
@@ -334,6 +338,280 @@ class WafV2CfnProvisionerTest {
assertFalse(provisioner.rollbackUpdate(resource));
}
+ @Test
+ void ipSetCreatesBackingResourceAndSetsAwsReferences() {
+ ObjectNode props = ipSetProps("blocklist");
+ props.put("Description", "deny list");
+ props.set("Tags", mapper.createArrayNode()
+ .add(mapper.createObjectNode().put("Key", "Owner").put("Value", "Security")));
+ IpSet created = ipSet("blocklist", "ip-123", "REGIONAL", "lock-1");
+ created.setArn("arn:aws:wafv2:us-east-1:111122223333:regional/ipset/blocklist/ip-123");
+ when(wafV2.createIpSet(any(), eq("REGIONAL"), eq("blocklist"), eq("us-east-1")))
+ .thenReturn(created);
+ StackResource resource = ipSetResource();
+
+ provisioner.provision(resource, props, context());
+
+ ArgumentCaptor<IpSet> desired = ArgumentCaptor.forClass(IpSet.class);
+ verify(wafV2).createIpSet(desired.capture(), eq("REGIONAL"), eq("blocklist"), eq("us-east-1"));
+ assertEquals("deny list", desired.getValue().getDescription());
+ assertEquals("IPV4", desired.getValue().getIpAddressVersion());
+ assertEquals(List.of("192.0.2.1/32"), desired.getValue().getAddresses());
+ assertEquals("Security", desired.getValue().getTags().get("Owner"));
+ assertEquals("blocklist|ip-123|REGIONAL", resource.getPhysicalId());
+ assertEquals(created.getArn(), resource.getAttributes().get("Arn"));
+ assertEquals("ip-123", resource.getAttributes().get("Id"));
+ }
+
+ @Test
+ void sameNamedIpSetUpdatesInPlaceWithoutPassingTheIpAddressVersion() {
+ IpSet existing = ipSet("blocklist", "ip-123", "REGIONAL", "lock-1");
+ IpSet updated = ipSet("blocklist", "ip-123", "REGIONAL", "lock-2");
+ updated.setArn("arn:updated");
+ when(wafV2.listIpSets("REGIONAL")).thenReturn(List.of(existing));
+ when(wafV2.getIpSet("REGIONAL", "ip-123", "blocklist")).thenReturn(updated);
+ StackResource resource = ipSetResource();
+ resource.setPhysicalId("blocklist|ip-123|REGIONAL");
+ ObjectNode props = ipSetProps("blocklist");
+ props.put("Description", "rotated");
+ props.set("Addresses", mapper.createArrayNode().add("198.51.100.7/32"));
+
+ provisioner.provision(resource, props, context());
+
+ verify(wafV2).updateIpSet(eq("REGIONAL"), eq("ip-123"), eq("rotated"),
+ eq(List.of("198.51.100.7/32")), eq("blocklist"), eq("lock-1"));
+ verify(wafV2, never()).createIpSet(any(), any(), anyString(), anyString());
+ assertEquals("blocklist|ip-123|REGIONAL", resource.getPhysicalId());
+ assertEquals("arn:updated", resource.getAttributes().get("Arn"));
+ assertEquals("ip-123", resource.getAttributes().get("Id"));
+ }
+
+ @Test
+ void ipSetInPlaceUpdateReconcilesTags() {
+ IpSet existing = ipSet("blocklist", "ip-123", "REGIONAL", "lock-1");
+ IpSet fetched = ipSet("blocklist", "ip-123", "REGIONAL", "lock-2");
+ fetched.setArn("arn:blocklist");
+ when(wafV2.listIpSets("REGIONAL")).thenReturn(List.of(existing));
+ when(wafV2.getIpSet("REGIONAL", "ip-123", "blocklist")).thenReturn(fetched);
+ when(wafV2.listTagsForResource("arn:blocklist"))
+ .thenReturn(Map.of("Owner", "Security", "Stale", "yes"));
+ StackResource resource = ipSetResource();
+ resource.setPhysicalId("blocklist|ip-123|REGIONAL");
+ ObjectNode props = ipSetProps("blocklist");
+ props.set("Tags", mapper.createArrayNode()
+ .add(mapper.createObjectNode().put("Key", "Owner").put("Value", "Platform")));
+
+ provisioner.provision(resource, props, context());
+
+ verify(wafV2).untagResource("arn:blocklist", List.of("Stale"));
+ verify(wafV2).tagResource("arn:blocklist", Map.of("Owner", "Platform"));
+ }
+
+ @Test
+ void renamedIpSetRecordsThePriorSetAndCommittedCleanupDeletesIt() {
+ IpSet existing = ipSet("blocklist", "ip-old", "REGIONAL", "lock-1");
+ IpSet created = ipSet("blocklist-v2", "ip-new", "REGIONAL", "lock-2");
+ created.setArn("arn:new");
+ when(wafV2.listIpSets("REGIONAL")).thenReturn(List.of(existing));
+ when(wafV2.createIpSet(any(), eq("REGIONAL"), eq("blocklist-v2"), eq("us-east-1")))
+ .thenReturn(created);
+ StackResource resource = ipSetResource();
+ resource.setPhysicalId("blocklist|ip-old|REGIONAL");
+
+ provisioner.provision(resource, ipSetProps("blocklist-v2"),
+ updateContext("blocklist|ip-old|REGIONAL"));
+
+ assertEquals("blocklist-v2|ip-new|REGIONAL", resource.getPhysicalId());
+ assertEquals("arn:new", resource.getAttributes().get("Arn"));
+ assertTrue(provisioner.hasReplacementUpdate(resource));
+ assertEquals("blocklist|ip-old|REGIONAL", provisioner.updateCleanupPhysicalId(resource));
+ verify(wafV2, never()).deleteIpSet(any(), anyString(), anyString(), anyString());
+
+ UpdateCleanupResult result = provisioner.completeUpdate(resource);
+
+ assertTrue(result.complete());
+ verify(wafV2).deleteIpSet("REGIONAL", "ip-old", "blocklist", "lock-1");
+ assertFalse(provisioner.hasReplacementUpdate(resource));
+ }
+
+ @Test
+ void committedCleanupOfAnIpSetStillReportsThePriorSetWhenItsDeleteFails() {
+ IpSet existing = ipSet("blocklist", "ip-old", "REGIONAL", "lock-1");
+ IpSet created = ipSet("blocklist-v2", "ip-new", "REGIONAL", "lock-2");
+ created.setArn("arn:new");
+ when(wafV2.listIpSets("REGIONAL")).thenReturn(List.of(existing));
+ when(wafV2.createIpSet(any(), eq("REGIONAL"), eq("blocklist-v2"), eq("us-east-1")))
+ .thenReturn(created);
+ doThrow(new RuntimeException("WAFAssociatedItemException"))
+ .when(wafV2).deleteIpSet("REGIONAL", "ip-old", "blocklist", "lock-1");
+ StackResource resource = ipSetResource();
+ resource.setPhysicalId("blocklist|ip-old|REGIONAL");
+ provisioner.provision(resource, ipSetProps("blocklist-v2"),
+ updateContext("blocklist|ip-old|REGIONAL"));
+
+ UpdateCleanupResult result = provisioner.completeUpdate(resource);
+
+ assertTrue(result.applicable());
+ assertFalse(result.complete());
+ assertEquals("blocklist|ip-old|REGIONAL", result.previousPhysicalId());
+ assertEquals(1, result.attempts());
+ assertEquals("WAFAssociatedItemException", result.failureReason());
+ assertEquals("blocklist-v2|ip-new|REGIONAL", resource.getPhysicalId());
+ assertTrue(provisioner.hasReplacementUpdate(resource));
+ }
+
+ @Test
+ void rollbackOfAnIpSetReplacementRestoresThePriorSetAndDeletesTheReplacement() {
+ IpSet existing = ipSet("blocklist", "ip-old", "REGIONAL", "lock-1");
+ IpSet created = ipSet("blocklist-v2", "ip-new", "REGIONAL", "lock-2");
+ created.setArn("arn:new");
+ when(wafV2.listIpSets("REGIONAL")).thenReturn(List.of(existing, created));
+ when(wafV2.createIpSet(any(), eq("REGIONAL"), eq("blocklist-v2"), eq("us-east-1")))
+ .thenReturn(created);
+ StackResource resource = ipSetResource();
+ resource.setPhysicalId("blocklist|ip-old|REGIONAL");
+ provisioner.provision(resource, ipSetProps("blocklist-v2"),
+ updateContext("blocklist|ip-old|REGIONAL"));
+
+ assertTrue(provisioner.rollbackUpdate(resource));
+
+ assertEquals("blocklist|ip-old|REGIONAL", resource.getPhysicalId());
+ assertFalse(provisioner.hasReplacementUpdate(resource));
+ verify(wafV2).deleteIpSet("REGIONAL", "ip-new", "blocklist-v2", "lock-2");
+ }
+
+ @Test
+ void ipSetWithoutNameGeneratesOneOnCreate() {
+ ObjectNode props = ipSetProps("blocklist");
+ props.remove("Name");
+ when(wafV2.createIpSet(any(), eq("REGIONAL"), anyString(), eq("us-east-1")))
+ .thenAnswer(invocation -> {
+ IpSet created = ipSet(invocation.getArgument(2), "ip-123", "REGIONAL", "lock-1");
+ created.setArn("arn:generated");
+ return created;
+ });
+ StackResource resource = ipSetResource();
+
+ provisioner.provision(resource, props, context());
+
+ ArgumentCaptor<String> name = ArgumentCaptor.forClass(String.class);
+ verify(wafV2).createIpSet(any(), eq("REGIONAL"), name.capture(), eq("us-east-1"));
+ assertFalse(name.getValue().isBlank());
+ assertEquals(name.getValue() + "|ip-123|REGIONAL", resource.getPhysicalId());
+ assertEquals("arn:generated", resource.getAttributes().get("Arn"));
+ }
+
+ @Test
+ void ipSetWithoutNameReusesTheExistingNameOnUpdate() {
+ IpSet existing = ipSet("blocklist", "ip-123", "REGIONAL", "lock-1");
+ IpSet updated = ipSet("blocklist", "ip-123", "REGIONAL", "lock-2");
+ updated.setArn("arn:updated");
+ when(wafV2.listIpSets("REGIONAL")).thenReturn(List.of(existing));
+ when(wafV2.getIpSet("REGIONAL", "ip-123", "blocklist")).thenReturn(updated);
+ StackResource resource = ipSetResource();
+ resource.setPhysicalId("blocklist|ip-123|REGIONAL");
+ ObjectNode props = ipSetProps("blocklist");
+ props.remove("Name");
+
+ provisioner.provision(resource, props, context());
+
+ verify(wafV2).updateIpSet(eq("REGIONAL"), eq("ip-123"), any(), anyList(),
+ eq("blocklist"), eq("lock-1"));
+ verify(wafV2, never()).createIpSet(any(), any(), anyString(), anyString());
+ }
+
+ @Test
+ void ipSetWithUnknownIpAddressVersionFailsBeforeCallingWafV2() {
+ ObjectNode props = ipSetProps("blocklist");
+ props.put("IPAddressVersion", "IPV5");
+
+ AwsException failure = assertThrows(AwsException.class,
+ () -> provisioner.provision(ipSetResource(), props, context()));
+
+ assertEquals("WAFInvalidParameterException", failure.getErrorCode());
+ verifyNoInteractions(wafV2);
+ }
+
+ @Test
+ void ipSetWithoutScopeFailsBeforeCallingWafV2() {
+ assertMissingIpSetPropertyFails("Scope");
+ }
+
+ @Test
+ void ipSetWithoutIpAddressVersionFailsBeforeCallingWafV2() {
+ assertMissingIpSetPropertyFails("IPAddressVersion");
+ }
+
+ @Test
+ void ipSetWithoutAddressesFailsBeforeCallingWafV2() {
+ assertMissingIpSetPropertyFails("Addresses");
+ }
+
+ @Test
+ void ipSetDeleteRemovesTheBackingResource() {
+ IpSet existing = ipSet("blocklist", "ip-123", "REGIONAL", "lock-1");
+ when(wafV2.listIpSets("REGIONAL")).thenReturn(List.of(existing));
+
+ provisioner.delete(IP_SET_TYPE, "blocklist|ip-123|REGIONAL", "us-east-1");
+
+ verify(wafV2).deleteIpSet("REGIONAL", "ip-123", "blocklist", "lock-1");
+ }
+
+ @Test
+ void ipSetDeleteIsNoOpWhenAlreadyGone() {
+ when(wafV2.listIpSets("REGIONAL")).thenReturn(List.of());
+
+ provisioner.delete(IP_SET_TYPE, "blocklist|ip-123|REGIONAL", "us-east-1");
+
+ verify(wafV2, never()).deleteIpSet(any(), anyString(), anyString(), anyString());
+ }
+
+ @Test
+ void ipSetRollbackUpdateKeepsTheDefault() {
+ StackResource resource = ipSetResource();
+ resource.setPhysicalId("blocklist|ip-123|REGIONAL");
+
+ assertFalse(provisioner.rollbackUpdate(resource));
+ }
+
+ private void assertMissingIpSetPropertyFails(String property) {
+ ObjectNode props = ipSetProps("blocklist");
+ props.remove(property);
+
+ AwsException failure = assertThrows(AwsException.class,
+ () -> provisioner.provision(ipSetResource(), props, context()));
+
+ assertEquals("ValidationError", failure.getErrorCode());
+ assertEquals("AWS::WAFv2::IPSet requires " + property, failure.getMessage());
+ verifyNoInteractions(wafV2);
+ }
+
+ private ObjectNode ipSetProps(String name) {
+ ObjectNode props = mapper.createObjectNode()
+ .put("Name", name)
+ .put("Scope", "REGIONAL")
+ .put("IPAddressVersion", "IPV4");
+ props.set("Addresses", mapper.createArrayNode().add("192.0.2.1/32"));
+ return props;
+ }
+
+ private StackResource ipSetResource() {
+ StackResource resource = new StackResource();
+ resource.setLogicalId("Blocklist");
+ resource.setResourceType(IP_SET_TYPE);
+ resource.setAttributes(new HashMap<>());
+ return resource;
+ }
+
+ private IpSet ipSet(String name, String id, String scope, String lockToken) {
+ IpSet ipSet = new IpSet();
+ ipSet.setName(name);
+ ipSet.setId(id);
+ ipSet.setScope(scope);
+ ipSet.setLockToken(lockToken);
+ return ipSet;
+ }
+
private ObjectNode associationProps(String webAclArn) {
return associationProps(POOL, webAclArn);
}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index 3c8d90dcb4..7fbc5be80e 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -181,6 +181,7 @@ AWS::ServiceDiscovery::Service CloudMapCfnProvisioner
AWS::StepFunctions::StateMachine StepFunctionsCfnProvisioner
AWS::Transfer::Server TransferCfnProvisioner
AWS::Transfer::User TransferCfnProvisioner
+AWS::WAFv2::IPSet WafV2CfnProvisioner
AWS::WAFv2::WebACL WafV2CfnProvisioner
AWS::WAFv2::WebACLAssociation WafV2CfnProvisioner
Custom::DynamoDBReplica DynamoDbCfnProvisioner