Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(wafv2): reject non-CIDR IPSet addresses (#3511)

Matheus Oliveiraa40409f59121
diff --git a/docs/services/wafv2.md b/docs/services/wafv2.md
index 44d6edf4ce..0c844964b6 100644
--- a/docs/services/wafv2.md
+++ b/docs/services/wafv2.md
@@ -52,6 +52,10 @@ Floci emulates the AWS WAF v2 management API. Web ACLs, IP sets, regex pattern s
WAF v2 resources are partitioned by `Scope`: `REGIONAL` (ALB, API Gateway, AppSync) or `CLOUDFRONT`. Pass `--scope` on every call; `CLOUDFRONT`-scoped requests must target `us-east-1` as on real AWS.
+## IP set addresses
+
+`CreateIPSet` and `UpdateIPSet` require every entry in `Addresses` to be in CIDR notation matching the set's `IPAddressVersion`: an IPv4 address with a `/1`-`/32` prefix, or an IPv6 address with a `/1`-`/128` prefix (a `/0` prefix is rejected, matching AWS). A bare address with no prefix, a prefix outside that range, or an address that does not match the declared `IPAddressVersion` is rejected with `WAFInvalidParameterException`.
+
## Example
```bash
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/JsonErrorResponseUtils.java b/src/main/java/io/github/hectorvent/floci/core/common/JsonErrorResponseUtils.java
index c9b084a585..83ac997162 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/JsonErrorResponseUtils.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/JsonErrorResponseUtils.java
@@ -1,11 +1,17 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.services.dynamodb.model.ConditionalCheckFailedException;
import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.ws.rs.core.Response;
+import java.util.Map;
+
public class JsonErrorResponseUtils {
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
private JsonErrorResponseUtils() {
// Do not instantiate
}
@@ -15,6 +21,9 @@ public class JsonErrorResponseUtils {
}
public static Response createErrorResponse(AwsException e) {
+ if (e.getExtendedData() != null) {
+ return createExtendedErrorResponse(e);
+ }
JsonNode item = null;
if (e instanceof ConditionalCheckFailedException){
item = ((ConditionalCheckFailedException) e).getItem();
@@ -22,6 +31,25 @@ public class JsonErrorResponseUtils {
return createErrorResponse(e.getHttpStatus(), e.getErrorCode(), e.jsonType(), e.getMessage(), item);
}
+ /**
+ * AwsJson11Controller dispatches services like WAFv2 through this class rather than the
+ * generic {@code AwsExceptionMapper} JAX-RS provider, so extendedData (Field/Parameter/Reason
+ * style structured errors) needs its own serialization path here to reach the client at all.
+ */
+ private static Response createExtendedErrorResponse(AwsException e) {
+ String queryErrorFault = (e.getHttpStatus() < 500) ? "Sender" : "Receiver";
+ ObjectNode node = OBJECT_MAPPER.createObjectNode();
+ node.put("__type", e.jsonType());
+ node.put("message", e.getMessage());
+ for (Map.Entry<String, Object> entry : e.getExtendedData().entrySet()) {
+ node.set(entry.getKey(), OBJECT_MAPPER.valueToTree(entry.getValue()));
+ }
+ return Response.status(e.getHttpStatus())
+ .header("x-amzn-query-error", e.getErrorCode() + ";" + queryErrorFault)
+ .entity(node)
+ .build();
+ }
+
public static Response createUnknownOperationErrorResponse(String target) {
return createErrorResponse(404,
"UnknownOperationException",
diff --git a/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Handler.java b/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Handler.java
index ca9dc590ee..9eddf2ddfc 100644
--- a/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Handler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Handler.java
@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsJson11Controller;
+import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils;
import io.github.hectorvent.floci.services.wafv2.model.IpSet;
import io.github.hectorvent.floci.services.wafv2.model.RegexPatternSet;
import io.github.hectorvent.floci.services.wafv2.model.RuleGroup;
@@ -84,9 +85,7 @@ public class WafV2Handler {
.build();
};
} catch (AwsException e) {
- return Response.status(e.getHttpStatus())
- .entity(new AwsErrorResponse(e.jsonType(), e.getMessage()))
- .build();
+ return JsonErrorResponseUtils.createErrorResponse(e);
} catch (Exception e) {
LOG.errorv("WAFv2 error processing action {0}: {1}", action, e.getMessage());
return Response.status(500)
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 3929cc78ce..3f2eece250 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
@@ -14,8 +14,11 @@ import io.github.hectorvent.floci.services.wafv2.model.WebAcl;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
+import java.net.Inet4Address;
+import java.net.InetAddress;
import java.time.Instant;
import java.util.ArrayList;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@@ -130,6 +133,7 @@ public class WafV2Service {
if (findByName(ipSetStore, scope, name) != null) {
throw new AwsException("WAFDuplicateItemException", "Duplicate IPSet name: " + name, 400);
}
+ validateAddresses(ipSet.getAddresses(), ipSet.getIpAddressVersion());
ipSet.setId(UUID.randomUUID().toString());
ipSet.setName(name);
ipSet.setScope(scope);
@@ -148,6 +152,7 @@ public class WafV2Service {
List<String> addresses, String name, String lockToken) {
IpSet existing = require(ipSetStore, scope, id, name);
checkLock(existing.getLockToken(), lockToken);
+ validateAddresses(addresses, existing.getIpAddressVersion());
existing.setDescription(description);
existing.setAddresses(addresses);
return rotate(existing, ipSetStore, scope);
@@ -481,6 +486,74 @@ public class WafV2Service {
}
}
+ /**
+ * 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}
+ * contract: a bare IP address with no prefix is rejected, as is a prefix outside
+ * 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) {
+ 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;
+ }
+ for (String address : addresses) {
+ validateCidrAddress(address, ipv6);
+ }
+ }
+
+ private void validateCidrAddress(String address, boolean ipv6) {
+ int maxPrefix = ipv6 ? 128 : 32;
+ int slash = address == null ? -1 : address.lastIndexOf('/');
+ if (slash < 1 || slash == address.length() - 1) {
+ throw invalidAddress(address,
+ "must be specified in CIDR notation, e.g. \"203.0.113.10/32\" (a bare IP address is not valid).");
+ }
+ String addressPart = address.substring(0, slash);
+ int prefixLength;
+ try {
+ prefixLength = Integer.parseInt(address.substring(slash + 1));
+ } catch (NumberFormatException e) {
+ throw invalidAddress(address, "the CIDR prefix length must be an integer.");
+ }
+ InetAddress parsed;
+ try {
+ parsed = InetAddress.ofLiteral(addressPart);
+ } catch (IllegalArgumentException e) {
+ throw invalidAddress(address, "the address portion is not a valid IP literal.");
+ }
+ boolean isIpv4Address = parsed instanceof Inet4Address;
+ if (ipv6 == isIpv4Address) {
+ throw invalidAddress(address,
+ "the address does not match the IPSet's IPAddressVersion (" + (ipv6 ? "IPV6" : "IPV4") + ").");
+ }
+ if (prefixLength < 1 || prefixLength > maxPrefix) {
+ throw invalidAddress(address,
+ "the CIDR prefix length must be between 1 and " + maxPrefix + ".");
+ }
+ }
+
+ private AwsException invalidAddress(String address, String reason) {
+ return invalidParameter("IP_ADDRESS", address, reason);
+ }
+
+ /**
+ * Builds a {@code WAFInvalidParameterException} with the Field/Parameter/Reason triple
+ * 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) {
+ Map<String, Object> extendedData = new LinkedHashMap<>();
+ extendedData.put("Field", field);
+ extendedData.put("Parameter", parameter);
+ extendedData.put("Reason", reason);
+ return new AwsException("WAFInvalidParameterException",
+ "Field: " + field + ", Parameter: " + parameter + ", Reason: " + reason, 400, extendedData);
+ }
+
private String key(String scope, String id) {
return scope + ":" + id;
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/wafv2/WafV2IpSetCidrValidationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/wafv2/WafV2IpSetCidrValidationIntegrationTest.java
new file mode 100644
index 0000000000..91f355e230
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/wafv2/WafV2IpSetCidrValidationIntegrationTest.java
@@ -0,0 +1,141 @@
+package io.github.hectorvent.floci.services.wafv2;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.Response;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.notNullValue;
+
+/**
+ * Validates that {@code CreateIPSet} and {@code UpdateIPSet} reject {@code Addresses}
+ * entries that are not valid CIDR blocks for the declared {@code IPAddressVersion},
+ * matching the AWS WAFv2 API contract (issue #3328).
+ */
+@QuarkusTest
+class WafV2IpSetCidrValidationIntegrationTest {
+
+ private static final String CT = "application/x-amz-json-1.1";
+ private static final String PREFIX = "AWSWAF_20190729.";
+
+ @BeforeAll
+ static void configure() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ private static Response call(String action, String body) {
+ return given().contentType(CT).header("X-Amz-Target", PREFIX + action)
+ .body(body).when().post("/");
+ }
+
+ @Test
+ void bareIpv4AddressIsRejected() {
+ call("CreateIPSet",
+ "{\"Name\":\"cidr-validation-bare-ipv4\",\"Scope\":\"REGIONAL\",\"IPAddressVersion\":\"IPV4\","
+ + "\"Addresses\":[\"203.0.113.10\"]}")
+ .then().statusCode(400)
+ .body("__type", equalTo("WAFInvalidParameterException"))
+ .body("Field", equalTo("IP_ADDRESS"))
+ .body("Parameter", equalTo("203.0.113.10"));
+ }
+
+ @Test
+ void emptyAddressesStillRequiresAValidIpAddressVersion() {
+ call("CreateIPSet",
+ "{\"Name\":\"cidr-validation-empty-addresses-no-version\",\"Scope\":\"REGIONAL\","
+ + "\"Addresses\":[]}")
+ .then().statusCode(400)
+ .body("__type", equalTo("WAFInvalidParameterException"))
+ .body("Field", equalTo("IP_ADDRESS_VERSION"));
+ }
+
+ @Test
+ void emptyAddressesRejectsAnInvalidIpAddressVersion() {
+ call("CreateIPSet",
+ "{\"Name\":\"cidr-validation-empty-addresses-bad-version\",\"Scope\":\"REGIONAL\","
+ + "\"IPAddressVersion\":\"IPV5\",\"Addresses\":[]}")
+ .then().statusCode(400)
+ .body("__type", equalTo("WAFInvalidParameterException"))
+ .body("Field", equalTo("IP_ADDRESS_VERSION"))
+ .body("Parameter", equalTo("IPV5"));
+ }
+
+ @Test
+ void emptyAddressesWithAValidIpAddressVersionSucceeds() {
+ call("CreateIPSet",
+ "{\"Name\":\"cidr-validation-empty-addresses-valid\",\"Scope\":\"REGIONAL\","
+ + "\"IPAddressVersion\":\"IPV4\",\"Addresses\":[]}")
+ .then().statusCode(200)
+ .body("Summary.Id", notNullValue());
+ }
+
+ @Test
+ void validIpv4CidrSucceeds() {
+ call("CreateIPSet",
+ "{\"Name\":\"cidr-validation-valid-ipv4\",\"Scope\":\"REGIONAL\",\"IPAddressVersion\":\"IPV4\","
+ + "\"Addresses\":[\"203.0.113.10/32\"]}")
+ .then().statusCode(200)
+ .body("Summary.Id", notNullValue());
+ }
+
+ @Test
+ void bareIpv6AddressIsRejected() {
+ call("CreateIPSet",
+ "{\"Name\":\"cidr-validation-bare-ipv6\",\"Scope\":\"REGIONAL\",\"IPAddressVersion\":\"IPV6\","
+ + "\"Addresses\":[\"1111:0000:0000:0000:0000:0000:0000:0111\"]}")
+ .then().statusCode(400)
+ .body("__type", equalTo("WAFInvalidParameterException"));
+ }
+
+ @Test
+ void validIpv6CidrSucceeds() {
+ call("CreateIPSet",
+ "{\"Name\":\"cidr-validation-valid-ipv6\",\"Scope\":\"REGIONAL\",\"IPAddressVersion\":\"IPV6\","
+ + "\"Addresses\":[\"1111:0000:0000:0000:0000:0000:0000:0111/128\"]}")
+ .then().statusCode(200)
+ .body("Summary.Id", notNullValue());
+ }
+
+ @Test
+ void outOfRangeIpv4PrefixIsRejected() {
+ call("CreateIPSet",
+ "{\"Name\":\"cidr-validation-out-of-range\",\"Scope\":\"REGIONAL\",\"IPAddressVersion\":\"IPV4\","
+ + "\"Addresses\":[\"203.0.113.10/33\"]}")
+ .then().statusCode(400)
+ .body("__type", equalTo("WAFInvalidParameterException"));
+ }
+
+ @Test
+ void mismatchedAddressFamilyIsRejected() {
+ call("CreateIPSet",
+ "{\"Name\":\"cidr-validation-mismatched-family\",\"Scope\":\"REGIONAL\",\"IPAddressVersion\":\"IPV4\","
+ + "\"Addresses\":[\"1111:0000:0000:0000:0000:0000:0000:0111/128\"]}")
+ .then().statusCode(400)
+ .body("__type", equalTo("WAFInvalidParameterException"));
+ }
+
+ @Test
+ void updateIpSetValidatesAddresses() {
+ Response created = call("CreateIPSet",
+ "{\"Name\":\"cidr-validation-update\",\"Scope\":\"REGIONAL\",\"IPAddressVersion\":\"IPV4\","
+ + "\"Addresses\":[\"203.0.113.10/32\"]}");
+ created.then().statusCode(200);
+ String id = created.jsonPath().getString("Summary.Id");
+ String lockToken = created.jsonPath().getString("Summary.LockToken");
+
+ call("UpdateIPSet",
+ "{\"Name\":\"cidr-validation-update\",\"Scope\":\"REGIONAL\",\"Id\":\"" + id + "\","
+ + "\"LockToken\":\"" + lockToken + "\",\"Addresses\":[\"198.51.100.5\"]}")
+ .then().statusCode(400)
+ .body("__type", equalTo("WAFInvalidParameterException"));
+
+ call("UpdateIPSet",
+ "{\"Name\":\"cidr-validation-update\",\"Scope\":\"REGIONAL\",\"Id\":\"" + id + "\","
+ + "\"LockToken\":\"" + lockToken + "\",\"Addresses\":[\"198.51.100.5/32\"]}")
+ .then().statusCode(200)
+ .body("NextLockToken", notNullValue());
+ }
+}