Light, fluffy, and always free - The AWS Local Emulator alternative
feat(wafv2): add AWS WAF v2 management API (Phase 1) (#1327)
Hector Ventura33cb72e34113
diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xmlindex 8d0f5013da..746ea3aba3 100644--- a/compatibility-tests/sdk-test-java/pom.xml+++ b/compatibility-tests/sdk-test-java/pom.xml@@ -181,6 +181,11 @@<groupId>software.amazon.awssdk</groupId><artifactId>emr</artifactId></dependency>+ <!-- WAF v2 client -->+ <dependency>+ <groupId>software.amazon.awssdk</groupId>+ <artifactId>wafv2</artifactId>+ </dependency><!-- Kinesis client --><dependency><groupId>software.amazon.awssdk</groupId>diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.javaindex 76738650a3..cb24e70748 100644--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java@@ -13,6 +13,7 @@ import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;import software.amazon.awssdk.services.eventbridge.EventBridgeClient;import software.amazon.awssdk.services.servicediscovery.ServiceDiscoveryClient;import software.amazon.awssdk.services.emr.EmrClient;+import software.amazon.awssdk.services.wafv2.Wafv2Client;import software.amazon.awssdk.services.iam.IamClient;import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;import software.amazon.awssdk.services.kinesis.KinesisClient;@@ -495,6 +496,14 @@ public final class TestFixtures {.build();}+ public static Wafv2Client wafv2Client() {+ return Wafv2Client.builder()+ .endpointOverride(ENDPOINT)+ .region(REGION)+ .credentialsProvider(CREDENTIALS)+ .build();+ }+public static SfnClient sfnClient() {return SfnClient.builder().endpointOverride(ENDPOINT)diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/WafV2Test.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/WafV2Test.javanew file mode 100644index 0000000000..f0223b1d1c--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/WafV2Test.java@@ -0,0 +1,193 @@+package com.floci.test;++import org.junit.jupiter.api.*;+import software.amazon.awssdk.services.wafv2.Wafv2Client;+import software.amazon.awssdk.services.wafv2.model.*;++import java.util.List;++import static org.assertj.core.api.Assertions.*;++/**+ * WAF v2 validated through the real AWS SDK v2 client: IP set + Web ACL lifecycle,+ * LockToken optimistic concurrency, resource association, and scope isolation.+ */+@DisplayName("WAF v2")+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class WafV2Test {++ private static Wafv2Client waf;+ private static String ipSetName;+ private static String aclName;+ private static String ipSetId;+ private static String ipSetArn;+ private static String aclId;+ private static String aclArn;+ private static String aclLockToken;++ private static final String API_RESOURCE_ARN =+ "arn:aws:apigateway:us-east-1::/restapis/floci-wafv2-sdk/stages/prod";++ @BeforeAll+ static void setup() {+ waf = TestFixtures.wafv2Client();+ ipSetName = TestFixtures.uniqueName("waf-ips");+ aclName = TestFixtures.uniqueName("waf-acl");+ }++ @AfterAll+ static void cleanup() {+ try {+ waf.disassociateWebACL(r -> r.resourceArn(API_RESOURCE_ARN));+ } catch (Exception ignored) {}+ try {+ String lock = waf.getWebACL(r -> r.name(aclName).scope(Scope.REGIONAL).id(aclId)).lockToken();+ waf.deleteWebACL(r -> r.name(aclName).scope(Scope.REGIONAL).id(aclId).lockToken(lock));+ } catch (Exception ignored) {}+ try {+ String lock = waf.getIPSet(r -> r.name(ipSetName).scope(Scope.REGIONAL).id(ipSetId)).lockToken();+ waf.deleteIPSet(r -> r.name(ipSetName).scope(Scope.REGIONAL).id(ipSetId).lockToken(lock));+ } catch (Exception ignored) {}+ waf.close();+ }++ @Test+ @Order(1)+ void createIpSet() {+ CreateIpSetResponse resp = waf.createIPSet(r -> r+ .name(ipSetName).scope(Scope.REGIONAL)+ .ipAddressVersion(IPAddressVersion.IPV4)+ .addresses("10.0.0.0/24", "192.168.0.0/16"));+ ipSetId = resp.summary().id();+ ipSetArn = resp.summary().arn();+ assertThat(ipSetId).isNotBlank();+ assertThat(resp.summary().lockToken()).isNotBlank();+ }++ @Test+ @Order(2)+ void duplicateIpSetFails() {+ assertThatThrownBy(() -> waf.createIPSet(r -> r+ .name(ipSetName).scope(Scope.REGIONAL)+ .ipAddressVersion(IPAddressVersion.IPV4)+ .addresses("10.0.0.0/24")))+ .isInstanceOf(WafDuplicateItemException.class);+ }++ @Test+ @Order(3)+ void createWebAcl() {+ Rule rule = Rule.builder()+ .name("iprule").priority(1)+ .statement(Statement.builder()+ .ipSetReferenceStatement(IPSetReferenceStatement.builder().arn(ipSetArn).build())+ .build())+ .action(RuleAction.builder().block(BlockAction.builder().build()).build())+ .visibilityConfig(VisibilityConfig.builder()+ .sampledRequestsEnabled(true).cloudWatchMetricsEnabled(true).metricName("iprule").build())+ .build();++ CreateWebAclResponse resp = waf.createWebACL(r -> r+ .name(aclName).scope(Scope.REGIONAL)+ .defaultAction(DefaultAction.builder().allow(AllowAction.builder().build()).build())+ .visibilityConfig(VisibilityConfig.builder()+ .sampledRequestsEnabled(true).cloudWatchMetricsEnabled(true).metricName("acl").build())+ .rules(rule));+ aclId = resp.summary().id();+ aclArn = resp.summary().arn();+ assertThat(aclId).isNotBlank();+ assertThat(aclArn).contains("regional/webacl");+ }++ @Test+ @Order(4)+ void getWebAcl() {+ GetWebAclResponse resp = waf.getWebACL(r -> r.name(aclName).scope(Scope.REGIONAL).id(aclId));+ assertThat(resp.webACL().name()).isEqualTo(aclName);+ assertThat(resp.webACL().rules()).hasSize(1);+ assertThat(resp.webACL().rules().get(0).statement().ipSetReferenceStatement().arn()).isEqualTo(ipSetArn);+ aclLockToken = resp.lockToken();+ assertThat(aclLockToken).isNotBlank();+ }++ @Test+ @Order(5)+ void updateWebAclRotatesLockToken() {+ UpdateWebAclResponse resp = waf.updateWebACL(r -> r+ .name(aclName).scope(Scope.REGIONAL).id(aclId).lockToken(aclLockToken)+ .description("updated")+ .defaultAction(DefaultAction.builder().block(BlockAction.builder().build()).build())+ .visibilityConfig(VisibilityConfig.builder()+ .sampledRequestsEnabled(true).cloudWatchMetricsEnabled(true).metricName("acl").build()));+ assertThat(resp.nextLockToken()).isNotBlank().isNotEqualTo(aclLockToken);+ }++ @Test+ @Order(6)+ void staleLockTokenFails() {+ assertThatThrownBy(() -> waf.updateWebACL(r -> r+ .name(aclName).scope(Scope.REGIONAL).id(aclId).lockToken(aclLockToken)+ .defaultAction(DefaultAction.builder().allow(AllowAction.builder().build()).build())+ .visibilityConfig(VisibilityConfig.builder()+ .sampledRequestsEnabled(true).cloudWatchMetricsEnabled(true).metricName("acl").build())))+ .isInstanceOf(WafOptimisticLockException.class);+ }++ @Test+ @Order(7)+ void associateAndQuery() {+ waf.associateWebACL(r -> r.webACLArn(aclArn).resourceArn(API_RESOURCE_ARN));++ GetWebAclForResourceResponse forResource =+ waf.getWebACLForResource(r -> r.resourceArn(API_RESOURCE_ARN));+ assertThat(forResource.webACL().id()).isEqualTo(aclId);++ ListResourcesForWebAclResponse resources =+ waf.listResourcesForWebACL(r -> r.webACLArn(aclArn));+ assertThat(resources.resourceArns()).containsExactly(API_RESOURCE_ARN);+ }++ @Test+ @Order(8)+ void deleteWhileAssociatedFails() {+ String lock = waf.getWebACL(r -> r.name(aclName).scope(Scope.REGIONAL).id(aclId)).lockToken();+ assertThatThrownBy(() -> waf.deleteWebACL(r -> r+ .name(aclName).scope(Scope.REGIONAL).id(aclId).lockToken(lock)))+ .isInstanceOf(WafAssociatedItemException.class);+ }++ @Test+ @Order(9)+ void cloudfrontScopeIsolated() {+ waf.createIPSet(r -> r+ .name(ipSetName).scope(Scope.CLOUDFRONT)+ .ipAddressVersion(IPAddressVersion.IPV4)+ .addresses("172.16.0.0/12"));+ List<IPSetSummary> cf = waf.listIPSets(r -> r.scope(Scope.CLOUDFRONT)).ipSets();+ IPSetSummary found = cf.stream().filter(s -> s.name().equals(ipSetName)).findFirst().orElseThrow();+ assertThat(found.arn()).isNotEqualTo(ipSetArn).contains("global/ipset");++ // cleanup the cloudfront ip set+ String lock = waf.getIPSet(r -> r.name(ipSetName).scope(Scope.CLOUDFRONT).id(found.id())).lockToken();+ waf.deleteIPSet(r -> r.name(ipSetName).scope(Scope.CLOUDFRONT).id(found.id()).lockToken(lock));+ }++ @Test+ @Order(10)+ void teardown() {+ waf.disassociateWebACL(r -> r.resourceArn(API_RESOURCE_ARN));+ String lock = waf.getWebACL(r -> r.name(aclName).scope(Scope.REGIONAL).id(aclId)).lockToken();+ waf.deleteWebACL(r -> r.name(aclName).scope(Scope.REGIONAL).id(aclId).lockToken(lock));++ String ipLock = waf.getIPSet(r -> r.name(ipSetName).scope(Scope.REGIONAL).id(ipSetId)).lockToken();+ waf.deleteIPSet(r -> r.name(ipSetName).scope(Scope.REGIONAL).id(ipSetId).lockToken(ipLock));+ }++ @Test+ @Order(11)+ void getMissingWebAclThrows() {+ assertThatThrownBy(() -> waf.getWebACL(r -> r+ .name("nope").scope(Scope.REGIONAL).id("00000000-0000-0000-0000-000000000000")))+ .isInstanceOf(WafNonexistentItemException.class);+ }+}\ No newline at end of filediff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex e3b27ceb14..b27bdf2d05 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -325,6 +325,7 @@ public interface EmulatorConfig {EventBridgeServiceConfig eventbridge();CloudMapServiceConfig cloudmap();EmrServiceConfig emr();+ WafV2ServiceConfig wafv2();SchedulerServiceConfig scheduler();CloudWatchLogsServiceConfig cloudwatchlogs();CloudWatchMetricsServiceConfig cloudwatchmetrics();@@ -588,6 +589,11 @@ public interface EmulatorConfig {int clusterStartupDelaySeconds();}+ interface WafV2ServiceConfig {+ @WithDefault("true")+ boolean enabled();+ }+interface SchedulerServiceConfig {@WithDefault("true")boolean enabled();diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.javaindex ef69246682..b2e001e26b 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java@@ -26,6 +26,7 @@ import io.github.hectorvent.floci.services.cognito.CognitoJsonHandler;import io.github.hectorvent.floci.services.cloudmap.CloudMapHandler;import io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler;import io.github.hectorvent.floci.services.emr.EmrHandler;+import io.github.hectorvent.floci.services.wafv2.WafV2Handler;import io.github.hectorvent.floci.services.kinesis.KinesisJsonHandler;import io.github.hectorvent.floci.services.kms.KmsJsonHandler;import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerJsonHandler;@@ -59,6 +60,7 @@ public class AwsJson11Controller {private final EventBridgeHandler eventBridgeHandler;private final CloudMapHandler cloudMapHandler;private final EmrHandler emrHandler;+ private final WafV2Handler wafV2Handler;private final CloudWatchLogsHandler cloudWatchLogsHandler;private final SecretsManagerJsonHandler secretsManagerJsonHandler;private final KinesisJsonHandler kinesisJsonHandler;@@ -91,6 +93,7 @@ public class AwsJson11Controller {SsmJsonHandler ssmJsonHandler, EventBridgeHandler eventBridgeHandler,CloudMapHandler cloudMapHandler,EmrHandler emrHandler,+ WafV2Handler wafV2Handler,CloudWatchLogsHandler cloudWatchLogsHandler,SecretsManagerJsonHandler secretsManagerJsonHandler,KinesisJsonHandler kinesisJsonHandler,@@ -120,6 +123,7 @@ public class AwsJson11Controller {this.eventBridgeHandler = eventBridgeHandler;this.cloudMapHandler = cloudMapHandler;this.emrHandler = emrHandler;+ this.wafV2Handler = wafV2Handler;this.cloudWatchLogsHandler = cloudWatchLogsHandler;this.secretsManagerJsonHandler = secretsManagerJsonHandler;this.kinesisJsonHandler = kinesisJsonHandler;@@ -177,6 +181,7 @@ public class AwsJson11Controller {case "events" -> eventBridgeHandler.handle(action, request, region);case "servicediscovery" -> cloudMapHandler.handle(action, request, region);case "elasticmapreduce" -> emrHandler.handle(action, request, region);+ case "wafv2" -> wafV2Handler.handle(action, request, region);case "logs" -> cloudWatchLogsHandler.handle(action, request, region);case "secretsmanager" -> secretsManagerJsonHandler.handle(action, request, region);case "kinesis" -> kinesisJsonHandler.handle(action, request, region);diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.javaindex 97839e6dc9..8957c47039 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java@@ -112,6 +112,10 @@ public class ResolvedServiceCatalog {"emr", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,protocols(ServiceProtocol.JSON),Set.of("ElasticMapReduce."), Set.of("elasticmapreduce"), Set.of(), Set.of()),+ descriptor("wafv2", "wafv2", config.services().wafv2().enabled(), true,+ "wafv2", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,+ protocols(ServiceProtocol.JSON),+ Set.of("AWSWAF_20190729."), Set.of("wafv2"), Set.of(), Set.of()),descriptor("scheduler", "scheduler", config.services().scheduler().enabled(), true,"scheduler", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,protocols(ServiceProtocol.JSON),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.javanew file mode 100644index 0000000000..0f72f502b3--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Handler.java@@ -0,0 +1,565 @@+package io.github.hectorvent.floci.services.wafv2;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ArrayNode;+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.services.wafv2.model.IpSet;+import io.github.hectorvent.floci.services.wafv2.model.RegexPatternSet;+import io.github.hectorvent.floci.services.wafv2.model.RuleGroup;+import io.github.hectorvent.floci.services.wafv2.model.WebAcl;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import jakarta.ws.rs.core.Response;+import org.jboss.logging.Logger;++import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++/**+ * WAF v2 JSON 1.1 handler. Dispatched from {@link AwsJson11Controller} under the+ * {@code AWSWAF_20190729.} target prefix.+ */+@ApplicationScoped+public class WafV2Handler {++ private static final Logger LOG = Logger.getLogger(WafV2Handler.class);++ private final WafV2Service service;+ private final ObjectMapper objectMapper;++ @Inject+ public WafV2Handler(WafV2Service service, ObjectMapper objectMapper) {+ this.service = service;+ this.objectMapper = objectMapper;+ }++ public Response handle(String action, JsonNode request, String region) {+ LOG.debugv("WAFv2 action: {0}", action);+ try {+ return switch (action) {+ case "CreateWebACL" -> handleCreateWebAcl(request, region);+ case "GetWebACL" -> handleGetWebAcl(request);+ case "UpdateWebACL" -> handleUpdateWebAcl(request);+ case "DeleteWebACL" -> handleDeleteWebAcl(request);+ case "ListWebACLs" -> handleListWebAcls(request);+ case "CreateIPSet" -> handleCreateIpSet(request, region);+ case "GetIPSet" -> handleGetIpSet(request);+ case "UpdateIPSet" -> handleUpdateIpSet(request);+ case "DeleteIPSet" -> handleDeleteIpSet(request);+ case "ListIPSets" -> handleListIpSets(request);+ case "CreateRegexPatternSet" -> handleCreateRegexPatternSet(request, region);+ case "GetRegexPatternSet" -> handleGetRegexPatternSet(request);+ case "UpdateRegexPatternSet" -> handleUpdateRegexPatternSet(request);+ case "DeleteRegexPatternSet" -> handleDeleteRegexPatternSet(request);+ case "ListRegexPatternSets" -> handleListRegexPatternSets(request);+ case "CreateRuleGroup" -> handleCreateRuleGroup(request, region);+ case "GetRuleGroup" -> handleGetRuleGroup(request);+ case "UpdateRuleGroup" -> handleUpdateRuleGroup(request);+ case "DeleteRuleGroup" -> handleDeleteRuleGroup(request);+ case "ListRuleGroups" -> handleListRuleGroups(request);+ case "CheckCapacity" -> handleCheckCapacity(request);+ case "AssociateWebACL" -> handleAssociateWebAcl(request);+ case "DisassociateWebACL" -> handleDisassociateWebAcl(request);+ case "GetWebACLForResource" -> handleGetWebAclForResource(request);+ case "ListResourcesForWebACL" -> handleListResourcesForWebAcl(request);+ case "PutLoggingConfiguration" -> handlePutLoggingConfiguration(request);+ case "GetLoggingConfiguration" -> handleGetLoggingConfiguration(request);+ case "DeleteLoggingConfiguration" -> handleDeleteLoggingConfiguration(request);+ case "ListLoggingConfigurations" -> handleListLoggingConfigurations();+ case "PutPermissionPolicy" -> handlePutPermissionPolicy(request);+ case "GetPermissionPolicy" -> handleGetPermissionPolicy(request);+ case "DeletePermissionPolicy" -> handleDeletePermissionPolicy(request);+ case "TagResource" -> handleTagResource(request);+ case "UntagResource" -> handleUntagResource(request);+ case "ListTagsForResource" -> handleListTagsForResource(request);+ default -> Response.status(400)+ .entity(new AwsErrorResponse("WAFInvalidOperationException",+ "Operation " + action + " is not supported."))+ .build();+ };+ } catch (AwsException e) {+ return Response.status(e.getHttpStatus())+ .entity(new AwsErrorResponse(e.jsonType(), e.getMessage()))+ .build();+ } catch (Exception e) {+ LOG.errorv("WAFv2 error processing action {0}: {1}", action, e.getMessage());+ return Response.status(500)+ .entity(new AwsErrorResponse("WAFInternalErrorException", e.getMessage()))+ .build();+ }+ }++ // ──────────────────────────── Web ACL ────────────────────────────++ private Response handleCreateWebAcl(JsonNode request, String region) {+ WebAcl acl = new WebAcl();+ acl.setDescription(text(request, "Description"));+ acl.setDefaultAction(rawObject(request.path("DefaultAction")));+ acl.setRules(rawArray(request.path("Rules")));+ acl.setVisibilityConfig(rawObject(request.path("VisibilityConfig")));+ acl.setCustomResponseBodies(rawObject(request.path("CustomResponseBodies")));+ acl.setCaptchaConfig(rawObject(request.path("CaptchaConfig")));+ acl.setChallengeConfig(rawObject(request.path("ChallengeConfig")));+ acl.setTokenDomains(stringList(request.path("TokenDomains")));+ acl.setAssociationConfig(rawObject(request.path("AssociationConfig")));+ acl.setDataProtectionConfig(rawObject(request.path("DataProtectionConfig")));+ acl.setTags(parseTags(request));+ WebAcl created = service.createWebAcl(acl, text(request, "Scope"), text(request, "Name"), region);+ ObjectNode response = objectMapper.createObjectNode();+ response.set("Summary", summaryNode(created.getName(), created.getId(),+ created.getDescription(), created.getLockToken(), created.getArn()));+ return Response.ok(response).build();+ }++ private Response handleGetWebAcl(JsonNode request) {+ WebAcl acl = service.getWebAcl(text(request, "Scope"), text(request, "Id"));+ ObjectNode response = objectMapper.createObjectNode();+ response.set("WebACL", webAclNode(acl));+ response.put("LockToken", acl.getLockToken());+ return Response.ok(response).build();+ }++ private Response handleUpdateWebAcl(JsonNode request) {+ WebAcl changes = new WebAcl();+ changes.setDescription(text(request, "Description"));+ changes.setDefaultAction(rawObject(request.path("DefaultAction")));+ changes.setRules(rawArray(request.path("Rules")));+ changes.setVisibilityConfig(rawObject(request.path("VisibilityConfig")));+ changes.setCustomResponseBodies(rawObject(request.path("CustomResponseBodies")));+ changes.setCaptchaConfig(rawObject(request.path("CaptchaConfig")));+ changes.setChallengeConfig(rawObject(request.path("ChallengeConfig")));+ changes.setTokenDomains(stringList(request.path("TokenDomains")));+ changes.setAssociationConfig(rawObject(request.path("AssociationConfig")));+ changes.setDataProtectionConfig(rawObject(request.path("DataProtectionConfig")));+ String next = service.updateWebAcl(changes, text(request, "Scope"),+ text(request, "Id"), text(request, "LockToken"));+ return Response.ok(objectMapper.createObjectNode().put("NextLockToken", next)).build();+ }++ private Response handleDeleteWebAcl(JsonNode request) {+ service.deleteWebAcl(text(request, "Scope"), text(request, "Id"), text(request, "LockToken"));+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleListWebAcls(JsonNode request) {+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode arr = response.putArray("WebACLs");+ for (WebAcl acl : service.listWebAcls(text(request, "Scope"))) {+ arr.add(summaryNode(acl.getName(), acl.getId(), acl.getDescription(),+ acl.getLockToken(), acl.getArn()));+ }+ return Response.ok(response).build();+ }++ // ──────────────────────────── IP set ────────────────────────────++ private Response handleCreateIpSet(JsonNode request, String region) {+ IpSet ipSet = new IpSet();+ ipSet.setDescription(text(request, "Description"));+ ipSet.setIpAddressVersion(text(request, "IPAddressVersion"));+ ipSet.setAddresses(stringList(request.path("Addresses")));+ ipSet.setTags(parseTags(request));+ IpSet created = service.createIpSet(ipSet, text(request, "Scope"), text(request, "Name"), region);+ ObjectNode response = objectMapper.createObjectNode();+ response.set("Summary", summaryNode(created.getName(), created.getId(),+ created.getDescription(), created.getLockToken(), created.getArn()));+ return Response.ok(response).build();+ }++ private Response handleGetIpSet(JsonNode request) {+ IpSet ipSet = service.getIpSet(text(request, "Scope"), text(request, "Id"));+ ObjectNode response = objectMapper.createObjectNode();+ response.set("IPSet", ipSetNode(ipSet));+ response.put("LockToken", ipSet.getLockToken());+ return Response.ok(response).build();+ }++ private Response handleUpdateIpSet(JsonNode request) {+ String next = service.updateIpSet(text(request, "Scope"), text(request, "Id"),+ text(request, "Description"), stringList(request.path("Addresses")),+ text(request, "LockToken"));+ return Response.ok(objectMapper.createObjectNode().put("NextLockToken", next)).build();+ }++ private Response handleDeleteIpSet(JsonNode request) {+ service.deleteIpSet(text(request, "Scope"), text(request, "Id"), text(request, "LockToken"));+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleListIpSets(JsonNode request) {+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode arr = response.putArray("IPSets");+ for (IpSet ipSet : service.listIpSets(text(request, "Scope"))) {+ arr.add(summaryNode(ipSet.getName(), ipSet.getId(), ipSet.getDescription(),+ ipSet.getLockToken(), ipSet.getArn()));+ }+ return Response.ok(response).build();+ }++ // ──────────────────────────── Regex pattern set ────────────────────────────++ private Response handleCreateRegexPatternSet(JsonNode request, String region) {+ RegexPatternSet set = new RegexPatternSet();+ set.setDescription(text(request, "Description"));+ set.setRegularExpressionList(regexList(request.path("RegularExpressionList")));+ set.setTags(parseTags(request));+ RegexPatternSet created = service.createRegexPatternSet(set, text(request, "Scope"),+ text(request, "Name"), region);+ ObjectNode response = objectMapper.createObjectNode();+ response.set("Summary", summaryNode(created.getName(), created.getId(),+ created.getDescription(), created.getLockToken(), created.getArn()));+ return Response.ok(response).build();+ }++ private Response handleGetRegexPatternSet(JsonNode request) {+ RegexPatternSet set = service.getRegexPatternSet(text(request, "Scope"), text(request, "Id"));+ ObjectNode response = objectMapper.createObjectNode();+ response.set("RegexPatternSet", regexSetNode(set));+ response.put("LockToken", set.getLockToken());+ return Response.ok(response).build();+ }++ private Response handleUpdateRegexPatternSet(JsonNode request) {+ String next = service.updateRegexPatternSet(text(request, "Scope"), text(request, "Id"),+ text(request, "Description"), regexList(request.path("RegularExpressionList")),+ text(request, "LockToken"));+ return Response.ok(objectMapper.createObjectNode().put("NextLockToken", next)).build();+ }++ private Response handleDeleteRegexPatternSet(JsonNode request) {+ service.deleteRegexPatternSet(text(request, "Scope"), text(request, "Id"), text(request, "LockToken"));+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleListRegexPatternSets(JsonNode request) {+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode arr = response.putArray("RegexPatternSets");+ for (RegexPatternSet set : service.listRegexPatternSets(text(request, "Scope"))) {+ arr.add(summaryNode(set.getName(), set.getId(), set.getDescription(),+ set.getLockToken(), set.getArn()));+ }+ return Response.ok(response).build();+ }++ // ──────────────────────────── Rule group ────────────────────────────++ private Response handleCreateRuleGroup(JsonNode request, String region) {+ RuleGroup group = new RuleGroup();+ group.setDescription(text(request, "Description"));+ group.setCapacity(request.path("Capacity").asLong(0));+ group.setRules(rawArray(request.path("Rules")));+ group.setVisibilityConfig(rawObject(request.path("VisibilityConfig")));+ group.setCustomResponseBodies(rawObject(request.path("CustomResponseBodies")));+ group.setTags(parseTags(request));+ RuleGroup created = service.createRuleGroup(group, text(request, "Scope"), text(request, "Name"), region);+ ObjectNode response = objectMapper.createObjectNode();+ response.set("Summary", summaryNode(created.getName(), created.getId(),+ created.getDescription(), created.getLockToken(), created.getArn()));+ return Response.ok(response).build();+ }++ private Response handleGetRuleGroup(JsonNode request) {+ RuleGroup group = service.getRuleGroup(text(request, "Scope"), text(request, "Id"));+ ObjectNode response = objectMapper.createObjectNode();+ response.set("RuleGroup", ruleGroupNode(group));+ response.put("LockToken", group.getLockToken());+ return Response.ok(response).build();+ }++ private Response handleUpdateRuleGroup(JsonNode request) {+ RuleGroup changes = new RuleGroup();+ changes.setDescription(text(request, "Description"));+ changes.setRules(rawArray(request.path("Rules")));+ changes.setVisibilityConfig(rawObject(request.path("VisibilityConfig")));+ changes.setCustomResponseBodies(rawObject(request.path("CustomResponseBodies")));+ String next = service.updateRuleGroup(changes, text(request, "Scope"),+ text(request, "Id"), text(request, "LockToken"));+ return Response.ok(objectMapper.createObjectNode().put("NextLockToken", next)).build();+ }++ private Response handleDeleteRuleGroup(JsonNode request) {+ service.deleteRuleGroup(text(request, "Scope"), text(request, "Id"), text(request, "LockToken"));+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleListRuleGroups(JsonNode request) {+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode arr = response.putArray("RuleGroups");+ for (RuleGroup group : service.listRuleGroups(text(request, "Scope"))) {+ arr.add(summaryNode(group.getName(), group.getId(), group.getDescription(),+ group.getLockToken(), group.getArn()));+ }+ return Response.ok(response).build();+ }++ private Response handleCheckCapacity(JsonNode request) {+ long capacity = service.checkCapacity(rawArray(request.path("Rules")));+ return Response.ok(objectMapper.createObjectNode().put("Capacity", capacity)).build();+ }++ // ──────────────────────────── Association ────────────────────────────++ private Response handleAssociateWebAcl(JsonNode request) {+ service.associateWebAcl(text(request, "WebACLArn"), text(request, "ResourceArn"));+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleDisassociateWebAcl(JsonNode request) {+ service.disassociateWebAcl(text(request, "ResourceArn"));+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleGetWebAclForResource(JsonNode request) {+ WebAcl acl = service.getWebAclForResource(text(request, "ResourceArn"));+ ObjectNode response = objectMapper.createObjectNode();+ if (acl != null) {+ response.set("WebACL", webAclNode(acl));+ }+ return Response.ok(response).build();+ }++ private Response handleListResourcesForWebAcl(JsonNode request) {+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode arr = response.putArray("ResourceArns");+ service.listResourcesForWebAcl(text(request, "WebACLArn")).forEach(arr::add);+ return Response.ok(response).build();+ }++ // ──────────────────────────── Logging ────────────────────────────++ private Response handlePutLoggingConfiguration(JsonNode request) {+ JsonNode config = request.path("LoggingConfiguration");+ String resourceArn = config.path("ResourceArn").asText(null);+ if (resourceArn == null) {+ throw new AwsException("WAFInvalidParameterException", "ResourceArn is required.", 400);+ }+ String stored = service.putLoggingConfiguration(resourceArn, config.toString());+ ObjectNode response = objectMapper.createObjectNode();+ setRawJson(response, "LoggingConfiguration", stored);+ return Response.ok(response).build();+ }++ private Response handleGetLoggingConfiguration(JsonNode request) {+ String stored = service.getLoggingConfiguration(text(request, "ResourceArn"));+ ObjectNode response = objectMapper.createObjectNode();+ setRawJson(response, "LoggingConfiguration", stored);+ return Response.ok(response).build();+ }++ private Response handleDeleteLoggingConfiguration(JsonNode request) {+ service.deleteLoggingConfiguration(text(request, "ResourceArn"));+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleListLoggingConfigurations() {+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode arr = response.putArray("LoggingConfigurations");+ for (String stored : service.listLoggingConfigurations()) {+ try {+ arr.add(objectMapper.readTree(stored));+ } catch (Exception ignored) {+ // skip unparseable stored config+ }+ }+ return Response.ok(response).build();+ }++ // ──────────────────────────── Permission policy ────────────────────────────++ private Response handlePutPermissionPolicy(JsonNode request) {+ service.putPermissionPolicy(text(request, "ResourceArn"), text(request, "Policy"));+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleGetPermissionPolicy(JsonNode request) {+ String policy = service.getPermissionPolicy(text(request, "ResourceArn"));+ return Response.ok(objectMapper.createObjectNode().put("Policy", policy)).build();+ }++ private Response handleDeletePermissionPolicy(JsonNode request) {+ service.deletePermissionPolicy(text(request, "ResourceArn"));+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ // ──────────────────────────── Tags ────────────────────────────++ private Response handleTagResource(JsonNode request) {+ service.tagResource(text(request, "ResourceARN"), parseTagList(request.path("Tags")));+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleUntagResource(JsonNode request) {+ List<String> keys = new ArrayList<>();+ request.path("TagKeys").forEach(k -> keys.add(k.asText()));+ service.untagResource(text(request, "ResourceARN"), keys);+ return Response.ok(objectMapper.createObjectNode()).build();+ }++ private Response handleListTagsForResource(JsonNode request) {+ String resourceArn = text(request, "ResourceARN");+ Map<String, String> tags = service.listTagsForResource(resourceArn);+ ObjectNode response = objectMapper.createObjectNode();+ ObjectNode info = response.putObject("TagInfoForResource");+ info.put("ResourceARN", resourceArn);+ ArrayNode arr = info.putArray("TagList");+ tags.forEach((k, v) -> {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("Key", k);+ node.put("Value", v);+ arr.add(node);+ });+ return Response.ok(response).build();+ }++ // ──────────────────────────── Builders ────────────────────────────++ private ObjectNode summaryNode(String name, String id, String description,+ String lockToken, String arn) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("Name", name);+ node.put("Id", id);+ if (description != null) {+ node.put("Description", description);+ }+ node.put("LockToken", lockToken);+ node.put("ARN", arn);+ return node;+ }++ private ObjectNode webAclNode(WebAcl acl) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("Name", acl.getName());+ node.put("Id", acl.getId());+ node.put("ARN", acl.getArn());+ setRawJson(node, "DefaultAction", acl.getDefaultAction());+ if (acl.getDescription() != null) {+ node.put("Description", acl.getDescription());+ }+ setRawJson(node, "Rules", acl.getRules());+ setRawJson(node, "VisibilityConfig", acl.getVisibilityConfig());+ node.put("Capacity", acl.getCapacity());+ setRawJson(node, "CustomResponseBodies", acl.getCustomResponseBodies());+ setRawJson(node, "CaptchaConfig", acl.getCaptchaConfig());+ setRawJson(node, "ChallengeConfig", acl.getChallengeConfig());+ setRawJson(node, "AssociationConfig", acl.getAssociationConfig());+ if (acl.getLabelNamespace() != null) {+ node.put("LabelNamespace", acl.getLabelNamespace());+ }+ if (!acl.getTokenDomains().isEmpty()) {+ ArrayNode domains = node.putArray("TokenDomains");+ acl.getTokenDomains().forEach(domains::add);+ }+ node.put("ManagedByFirewallManager", false);+ return node;+ }++ private ObjectNode ipSetNode(IpSet ipSet) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("Name", ipSet.getName());+ node.put("Id", ipSet.getId());+ node.put("ARN", ipSet.getArn());+ if (ipSet.getDescription() != null) {+ node.put("Description", ipSet.getDescription());+ }+ node.put("IPAddressVersion", ipSet.getIpAddressVersion());+ ArrayNode addresses = node.putArray("Addresses");+ ipSet.getAddresses().forEach(addresses::add);+ return node;+ }++ private ObjectNode regexSetNode(RegexPatternSet set) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("Name", set.getName());+ node.put("Id", set.getId());+ node.put("ARN", set.getArn());+ if (set.getDescription() != null) {+ node.put("Description", set.getDescription());+ }+ ArrayNode list = node.putArray("RegularExpressionList");+ set.getRegularExpressionList().forEach(r -> list.addObject().put("RegexString", r));+ return node;+ }++ private ObjectNode ruleGroupNode(RuleGroup group) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("Name", group.getName());+ node.put("Id", group.getId());+ node.put("ARN", group.getArn());+ node.put("Capacity", group.getCapacity());+ if (group.getDescription() != null) {+ node.put("Description", group.getDescription());+ }+ setRawJson(node, "Rules", group.getRules());+ setRawJson(node, "VisibilityConfig", group.getVisibilityConfig());+ setRawJson(node, "CustomResponseBodies", group.getCustomResponseBodies());+ if (group.getLabelNamespace() != null) {+ node.put("LabelNamespace", group.getLabelNamespace());+ }+ return node;+ }++ // ──────────────────────────── Parsing ────────────────────────────++ private Map<String, String> parseTags(JsonNode request) {+ return parseTagList(request.path("Tags"));+ }++ private Map<String, String> parseTagList(JsonNode tagsNode) {+ Map<String, String> tags = new LinkedHashMap<>();+ if (tagsNode.isArray()) {+ for (JsonNode tag : tagsNode) {+ String key = tag.path("Key").asText(null);+ if (key != null) {+ tags.put(key, tag.path("Value").asText(null));+ }+ }+ }+ return tags;+ }++ private List<String> stringList(JsonNode node) {+ List<String> values = new ArrayList<>();+ if (node != null && node.isArray()) {+ node.forEach(v -> values.add(v.asText()));+ }+ return values;+ }++ private List<String> regexList(JsonNode node) {+ List<String> values = new ArrayList<>();+ if (node != null && node.isArray()) {+ node.forEach(v -> values.add(v.path("RegexString").asText()));+ }+ return values;+ }++ private String text(JsonNode request, String field) {+ JsonNode node = request.path(field);+ return node.isMissingNode() || node.isNull() ? null : node.asText(null);+ }++ private String rawObject(JsonNode node) {+ return (node != null && node.isObject() && !node.isEmpty()) ? node.toString() : null;+ }++ private String rawArray(JsonNode node) {+ return (node != null && node.isArray() && !node.isEmpty()) ? node.toString() : null;+ }++ private void setRawJson(ObjectNode target, String field, String rawJson) {+ if (rawJson == null) {+ return;+ }+ try {+ target.set(field, objectMapper.readTree(rawJson));+ } catch (Exception e) {+ LOG.warnv("Failed to parse stored {0} JSON; field omitted. Value: {1}", field, rawJson);+ }+ }+}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.javanew file mode 100644index 0000000000..c2bb6a906b--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/wafv2/WafV2Service.java@@ -0,0 +1,529 @@+package io.github.hectorvent.floci.services.wafv2;++import com.fasterxml.jackson.core.type.TypeReference;+import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.StorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+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;+import io.github.hectorvent.floci.services.wafv2.model.WebAcl;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;++import java.time.Instant;+import java.util.ArrayList;+import java.util.List;+import java.util.Map;+import java.util.UUID;++/**+ * WAF v2 management-plane business logic. Resources are identified by the+ * (Scope, Id) pair (storage key {@code scope:id}); Name + Scope find the Id on the+ * duplicate-name check. Updates/deletes enforce the LockToken optimistic-concurrency+ * contract. Recursive rule structures are stored opaquely as raw JSON.+ */+@ApplicationScoped+public class WafV2Service {++ private final StorageBackend<String, WebAcl> webAclStore;+ private final StorageBackend<String, IpSet> ipSetStore;+ private final StorageBackend<String, RegexPatternSet> regexStore;+ private final StorageBackend<String, RuleGroup> ruleGroupStore;+ private final StorageBackend<String, String> loggingStore;+ private final StorageBackend<String, String> associationStore;+ private final StorageBackend<String, String> policyStore;+ private final RegionResolver regionResolver;+ private final ObjectMapper objectMapper;++ @Inject+ public WafV2Service(StorageFactory storageFactory, RegionResolver regionResolver,+ ObjectMapper objectMapper) {+ this.webAclStore = storageFactory.create("wafv2", "wafv2-webacls.json",+ new TypeReference<Map<String, WebAcl>>() {});+ this.ipSetStore = storageFactory.create("wafv2", "wafv2-ipsets.json",+ new TypeReference<Map<String, IpSet>>() {});+ this.regexStore = storageFactory.create("wafv2", "wafv2-regex-sets.json",+ new TypeReference<Map<String, RegexPatternSet>>() {});+ this.ruleGroupStore = storageFactory.create("wafv2", "wafv2-rule-groups.json",+ new TypeReference<Map<String, RuleGroup>>() {});+ this.loggingStore = storageFactory.create("wafv2", "wafv2-logging.json",+ new TypeReference<Map<String, String>>() {});+ this.associationStore = storageFactory.create("wafv2", "wafv2-associations.json",+ new TypeReference<Map<String, String>>() {});+ this.policyStore = storageFactory.create("wafv2", "wafv2-policies.json",+ new TypeReference<Map<String, String>>() {});+ this.regionResolver = regionResolver;+ this.objectMapper = objectMapper;+ }++ // ──────────────────────────── Web ACL ────────────────────────────++ public WebAcl createWebAcl(WebAcl acl, String scope, String name, String region) {+ validateScope(scope);+ requireName(name);+ if (findByName(webAclStore, scope, name) != null) {+ throw new AwsException("WAFDuplicateItemException",+ "AWS WAF couldn't perform the operation because some resource "+ + "in your request is a duplicate of an existing one.", 400);+ }+ acl.setId(UUID.randomUUID().toString());+ acl.setName(name);+ acl.setScope(scope);+ acl.setRegion(region);+ acl.setLockToken(UUID.randomUUID().toString());+ acl.setCreationTime(Instant.now());+ acl.setCapacity(computeCapacity(acl.getRules()));+ acl.setLabelNamespace("awswaf:" + regionResolver.getAccountId() + ":webacl:" + name + ":");+ acl.setArn(buildArn(scope, "webacl", name, acl.getId(), region));+ webAclStore.put(key(scope, acl.getId()), acl);+ return acl;+ }++ public WebAcl getWebAcl(String scope, String id) {+ return require(webAclStore, scope, id);+ }++ public String updateWebAcl(WebAcl changes, String scope, String id, String lockToken) {+ WebAcl existing = require(webAclStore, scope, id);+ checkLock(existing.getLockToken(), lockToken);+ existing.setDescription(changes.getDescription());+ existing.setDefaultAction(changes.getDefaultAction());+ existing.setRules(changes.getRules());+ existing.setVisibilityConfig(changes.getVisibilityConfig());+ existing.setCustomResponseBodies(changes.getCustomResponseBodies());+ existing.setCaptchaConfig(changes.getCaptchaConfig());+ existing.setChallengeConfig(changes.getChallengeConfig());+ existing.setTokenDomains(changes.getTokenDomains());+ existing.setAssociationConfig(changes.getAssociationConfig());+ existing.setDataProtectionConfig(changes.getDataProtectionConfig());+ existing.setCapacity(computeCapacity(changes.getRules()));+ return rotate(existing, webAclStore, scope);+ }++ public void deleteWebAcl(String scope, String id, String lockToken) {+ WebAcl existing = require(webAclStore, scope, id);+ checkLock(existing.getLockToken(), lockToken);+ boolean associated = associationStore.scan(k -> true).stream()+ .anyMatch(arn -> arn.equals(existing.getArn()));+ if (associated) {+ throw new AwsException("WAFAssociatedItemException",+ "AWS WAF couldn't perform the operation because your resource is "+ + "associated with one or more web requests sources.", 400);+ }+ webAclStore.delete(key(scope, id));+ }++ public List<WebAcl> listWebAcls(String scope) {+ validateScope(scope);+ return listByScope(webAclStore, scope);+ }++ // ──────────────────────────── IP set ────────────────────────────++ public IpSet createIpSet(IpSet ipSet, String scope, String name, String region) {+ validateScope(scope);+ requireName(name);+ if (findByName(ipSetStore, scope, name) != null) {+ throw new AwsException("WAFDuplicateItemException", "Duplicate IPSet name: " + name, 400);+ }+ ipSet.setId(UUID.randomUUID().toString());+ ipSet.setName(name);+ ipSet.setScope(scope);+ ipSet.setRegion(region);+ ipSet.setLockToken(UUID.randomUUID().toString());+ ipSet.setArn(buildArn(scope, "ipset", name, ipSet.getId(), region));+ ipSetStore.put(key(scope, ipSet.getId()), ipSet);+ return ipSet;+ }++ public IpSet getIpSet(String scope, String id) {+ return require(ipSetStore, scope, id);+ }++ public String updateIpSet(String scope, String id, String description,+ List<String> addresses, String lockToken) {+ IpSet existing = require(ipSetStore, scope, id);+ checkLock(existing.getLockToken(), lockToken);+ existing.setDescription(description);+ existing.setAddresses(addresses);+ return rotate(existing, ipSetStore, scope);+ }++ public void deleteIpSet(String scope, String id, String lockToken) {+ IpSet existing = require(ipSetStore, scope, id);+ checkLock(existing.getLockToken(), lockToken);+ ipSetStore.delete(key(scope, id));+ }++ public List<IpSet> listIpSets(String scope) {+ validateScope(scope);+ return listByScope(ipSetStore, scope);+ }++ // ──────────────────────────── Regex pattern set ────────────────────────────++ public RegexPatternSet createRegexPatternSet(RegexPatternSet set, String scope, String name, String region) {+ validateScope(scope);+ requireName(name);+ if (findByName(regexStore, scope, name) != null) {+ throw new AwsException("WAFDuplicateItemException", "Duplicate RegexPatternSet name: " + name, 400);+ }+ set.setId(UUID.randomUUID().toString());+ set.setName(name);+ set.setScope(scope);+ set.setRegion(region);+ set.setLockToken(UUID.randomUUID().toString());+ set.setArn(buildArn(scope, "regexpatternset", name, set.getId(), region));+ regexStore.put(key(scope, set.getId()), set);+ return set;+ }++ public RegexPatternSet getRegexPatternSet(String scope, String id) {+ return require(regexStore, scope, id);+ }++ public String updateRegexPatternSet(String scope, String id, String description,+ List<String> regexList, String lockToken) {+ RegexPatternSet existing = require(regexStore, scope, id);+ checkLock(existing.getLockToken(), lockToken);+ existing.setDescription(description);+ existing.setRegularExpressionList(regexList);+ return rotate(existing, regexStore, scope);+ }++ public void deleteRegexPatternSet(String scope, String id, String lockToken) {+ RegexPatternSet existing = require(regexStore, scope, id);+ checkLock(existing.getLockToken(), lockToken);+ regexStore.delete(key(scope, id));+ }++ public List<RegexPatternSet> listRegexPatternSets(String scope) {+ validateScope(scope);+ return listByScope(regexStore, scope);+ }++ // ──────────────────────────── Rule group ────────────────────────────++ public RuleGroup createRuleGroup(RuleGroup group, String scope, String name, String region) {+ validateScope(scope);+ requireName(name);+ if (findByName(ruleGroupStore, scope, name) != null) {+ throw new AwsException("WAFDuplicateItemException", "Duplicate RuleGroup name: " + name, 400);+ }+ group.setId(UUID.randomUUID().toString());+ group.setName(name);+ group.setScope(scope);+ group.setRegion(region);+ group.setLockToken(UUID.randomUUID().toString());+ group.setLabelNamespace("awswaf:" + regionResolver.getAccountId() + ":rulegroup:" + name + ":");+ group.setArn(buildArn(scope, "rulegroup", name, group.getId(), region));+ ruleGroupStore.put(key(scope, group.getId()), group);+ return group;+ }++ public RuleGroup getRuleGroup(String scope, String id) {+ return require(ruleGroupStore, scope, id);+ }++ public String updateRuleGroup(RuleGroup changes, String scope, String id, String lockToken) {+ RuleGroup existing = require(ruleGroupStore, scope, id);+ checkLock(existing.getLockToken(), lockToken);+ existing.setDescription(changes.getDescription());+ existing.setRules(changes.getRules());+ existing.setVisibilityConfig(changes.getVisibilityConfig());+ existing.setCustomResponseBodies(changes.getCustomResponseBodies());+ return rotate(existing, ruleGroupStore, scope);+ }++ public void deleteRuleGroup(String scope, String id, String lockToken) {+ RuleGroup existing = require(ruleGroupStore, scope, id);+ checkLock(existing.getLockToken(), lockToken);+ ruleGroupStore.delete(key(scope, id));+ }++ public List<RuleGroup> listRuleGroups(String scope) {+ validateScope(scope);+ return listByScope(ruleGroupStore, scope);+ }++ public long checkCapacity(String rulesJson) {+ return computeCapacity(rulesJson);+ }++ // ──────────────────────────── Association ────────────────────────────++ public void associateWebAcl(String webAclArn, String resourceArn) {+ boolean known = webAclStore.scan(k -> true).stream()+ .anyMatch(a -> a.getArn().equals(webAclArn));+ if (!known) {+ throw new AwsException("WAFNonexistentItemException",+ "AWS WAF couldn't perform the operation because your resource doesn't exist.", 404);+ }+ associationStore.put(resourceArn, webAclArn);+ }++ public void disassociateWebAcl(String resourceArn) {+ associationStore.delete(resourceArn);+ }++ public WebAcl getWebAclForResource(String resourceArn) {+ String webAclArn = associationStore.get(resourceArn).orElse(null);+ if (webAclArn == null) {+ return null;+ }+ return webAclStore.scan(k -> true).stream()+ .filter(a -> a.getArn().equals(webAclArn))+ .findFirst().orElse(null);+ }++ public List<String> listResourcesForWebAcl(String webAclArn) {+ List<String> resources = new ArrayList<>();+ for (String resourceArn : associationStore.keys()) {+ associationStore.get(resourceArn)+ .filter(webAclArn::equals)+ .ifPresent(a -> resources.add(resourceArn));+ }+ return resources;+ }++ // ──────────────────────────── Logging ────────────────────────────++ public String putLoggingConfiguration(String resourceArn, String loggingConfigJson) {+ loggingStore.put(resourceArn, loggingConfigJson);+ return loggingConfigJson;+ }++ public String getLoggingConfiguration(String resourceArn) {+ return loggingStore.get(resourceArn).orElseThrow(() -> new AwsException(+ "WAFNonexistentItemException", "No logging configuration for: " + resourceArn, 404));+ }++ public void deleteLoggingConfiguration(String resourceArn) {+ loggingStore.delete(resourceArn);+ }++ public List<String> listLoggingConfigurations() {+ return new ArrayList<>(loggingStore.scan(k -> true));+ }++ // ──────────────────────────── Permission policy ────────────────────────────++ public void putPermissionPolicy(String resourceArn, String policy) {+ policyStore.put(resourceArn, policy);+ }++ public String getPermissionPolicy(String resourceArn) {+ return policyStore.get(resourceArn).orElseThrow(() -> new AwsException(+ "WAFNonexistentItemException", "No policy for: " + resourceArn, 404));+ }++ public void deletePermissionPolicy(String resourceArn) {+ policyStore.delete(resourceArn);+ }++ // ──────────────────────────── Tags ────────────────────────────++ public Map<String, String> listTagsForResource(String resourceArn) {+ return taggable(resourceArn).getTags();+ }++ public void tagResource(String resourceArn, Map<String, String> tags) {+ Object resource = taggable(resourceArn);+ applyTagged(resource, r -> r.getTags().putAll(tags));+ }++ public void untagResource(String resourceArn, List<String> keys) {+ Object resource = taggable(resourceArn);+ applyTagged(resource, r -> keys.forEach(r.getTags()::remove));+ }++ // ──────────────────────────── Helpers ────────────────────────────++ private interface Tagged { Map<String, String> getTags(); }++ private Tagged taggable(String resourceArn) {+ if (resourceArn == null) {+ throw new AwsException("WAFInvalidParameterException", "ResourceARN is required.", 400);+ }+ WebAcl acl = scanArn(webAclStore, resourceArn);+ if (acl != null) {+ return acl::getTags;+ }+ IpSet ip = scanArn(ipSetStore, resourceArn);+ if (ip != null) {+ return ip::getTags;+ }+ RegexPatternSet rx = scanArn(regexStore, resourceArn);+ if (rx != null) {+ return rx::getTags;+ }+ RuleGroup rg = scanArn(ruleGroupStore, resourceArn);+ if (rg != null) {+ return rg::getTags;+ }+ throw new AwsException("WAFNonexistentItemException", "Resource not found: " + resourceArn, 404);+ }++ private void applyTagged(Object resource, java.util.function.Consumer<Tagged> mutation) {+ if (resource instanceof WebAcl a) {+ mutation.accept(a::getTags);+ webAclStore.put(key(a.getScope(), a.getId()), a);+ } else if (resource instanceof IpSet i) {+ mutation.accept(i::getTags);+ ipSetStore.put(key(i.getScope(), i.getId()), i);+ } else if (resource instanceof RegexPatternSet r) {+ mutation.accept(r::getTags);+ regexStore.put(key(r.getScope(), r.getId()), r);+ } else if (resource instanceof RuleGroup g) {+ mutation.accept(g::getTags);+ ruleGroupStore.put(key(g.getScope(), g.getId()), g);+ }+ }++ private <V> V scanArn(StorageBackend<String, V> store, String arn) {+ return store.scan(k -> true).stream()+ .filter(v -> arn.equals(arnOf(v)))+ .findFirst().orElse(null);+ }++ private String arnOf(Object v) {+ if (v instanceof WebAcl a) return a.getArn();+ if (v instanceof IpSet i) return i.getArn();+ if (v instanceof RegexPatternSet r) return r.getArn();+ if (v instanceof RuleGroup g) return g.getArn();+ return null;+ }++ private <V> V require(StorageBackend<String, V> store, String scope, String id) {+ validateScope(scope);+ if (id == null) {+ throw new AwsException("WAFInvalidParameterException", "Id is required.", 400);+ }+ return store.get(key(scope, id)).orElseThrow(() -> new AwsException(+ "WAFNonexistentItemException",+ "AWS WAF couldn't perform the operation because your resource doesn't exist.", 404));+ }++ private <V> V findByName(StorageBackend<String, V> store, String scope, String name) {+ return store.scan(k -> true).stream()+ .filter(v -> scope.equals(scopeOf(v)) && name.equals(nameOf(v)))+ .findFirst().orElse(null);+ }++ private <V> List<V> listByScope(StorageBackend<String, V> store, String scope) {+ List<V> result = new ArrayList<>();+ for (V v : store.scan(k -> true)) {+ if (scope.equals(scopeOf(v))) {+ result.add(v);+ }+ }+ return result;+ }++ private String scopeOf(Object v) {+ if (v instanceof WebAcl a) return a.getScope();+ if (v instanceof IpSet i) return i.getScope();+ if (v instanceof RegexPatternSet r) return r.getScope();+ if (v instanceof RuleGroup g) return g.getScope();+ return null;+ }++ private String nameOf(Object v) {+ if (v instanceof WebAcl a) return a.getName();+ if (v instanceof IpSet i) return i.getName();+ if (v instanceof RegexPatternSet r) return r.getName();+ if (v instanceof RuleGroup g) return g.getName();+ return null;+ }++ @SuppressWarnings("unchecked")+ private <V> String rotate(V resource, StorageBackend<String, V> store, String scope) {+ String next = UUID.randomUUID().toString();+ String id;+ if (resource instanceof WebAcl a) { a.setLockToken(next); id = a.getId(); }+ else if (resource instanceof IpSet i) { i.setLockToken(next); id = i.getId(); }+ else if (resource instanceof RegexPatternSet r) { r.setLockToken(next); id = r.getId(); }+ else { RuleGroup g = (RuleGroup) resource; g.setLockToken(next); id = g.getId(); }+ store.put(key(scope, id), resource);+ return next;+ }++ private void checkLock(String current, String supplied) {+ if (supplied == null || !supplied.equals(current)) {+ throw new AwsException("WAFOptimisticLockException",+ "AWS WAF couldn't save your changes because someone changed the resource "+ + "after you started to edit it. Reapply your changes.", 400);+ }+ }++ private void validateScope(String scope) {+ if (!"CLOUDFRONT".equals(scope) && !"REGIONAL".equals(scope)) {+ throw new AwsException("WAFInvalidParameterException",+ "Scope must be CLOUDFRONT or REGIONAL.", 400);+ }+ }++ private void requireName(String name) {+ if (name == null || name.isBlank()) {+ throw new AwsException("WAFInvalidParameterException", "Name is required.", 400);+ }+ }++ private String key(String scope, String id) {+ return scope + ":" + id;+ }++ private String buildArn(String scope, String type, String name, String id, String region) {+ String prefix = "CLOUDFRONT".equals(scope) ? "global" : "regional";+ String arnRegion = "CLOUDFRONT".equals(scope) ? "us-east-1" : region;+ return regionResolver.buildArn("wafv2", arnRegion, prefix + "/" + type + "/" + name + "/" + id);+ }++ /**+ * Deterministic WCU approximation: 1 base unit per rule plus a small premium for+ * recursive logical statements. Real AWS computes exact WCUs per statement type;+ * Phase 1 only needs a stable, positive number.+ */+ private long computeCapacity(String rulesJson) {+ if (rulesJson == null || rulesJson.isBlank()) {+ return 0L;+ }+ try {+ JsonNode rules = objectMapper.readTree(rulesJson);+ if (!rules.isArray()) {+ return 1L;+ }+ long total = 0L;+ for (JsonNode rule : rules) {+ total += 1 + countStatements(rule.path("Statement"));+ }+ return Math.max(1L, total);+ } catch (Exception e) {+ return 1L;+ }+ }++ private long countStatements(JsonNode statement) {+ if (statement == null || !statement.isObject()) {+ return 0L;+ }+ long count = 0L;+ for (String logical : List.of("AndStatement", "OrStatement", "NotStatement")) {+ JsonNode nested = statement.path(logical).path("Statements");+ if (nested.isArray()) {+ for (JsonNode s : nested) {+ count += 1 + countStatements(s);+ }+ }+ JsonNode single = statement.path(logical).path("Statement");+ if (single.isObject()) {+ count += 1 + countStatements(single);+ }+ }+ return count;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/wafv2/model/IpSet.java b/src/main/java/io/github/hectorvent/floci/services/wafv2/model/IpSet.javanew file mode 100644index 0000000000..c73da0277c--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/wafv2/model/IpSet.java@@ -0,0 +1,56 @@+package io.github.hectorvent.floci.services.wafv2.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;++/** WAF v2 IP set. {@code ipAddressVersion} is IPV4 or IPV6; {@code addresses} are CIDRs. */+@RegisterForReflection+public class IpSet {++ private String id;+ private String name;+ private String arn;+ private String scope;+ private String description;+ private String ipAddressVersion;+ private List<String> addresses = new ArrayList<>();+ private String lockToken;+ private String region;+ private Map<String, String> tags = new HashMap<>();++ public IpSet() {}++ public String getId() { return id; }+ public void setId(String id) { this.id = id; }++ public String getName() { return name; }+ public void setName(String name) { this.name = name; }++ public String getArn() { return arn; }+ public void setArn(String arn) { this.arn = arn; }++ public String getScope() { return scope; }+ public void setScope(String scope) { this.scope = scope; }++ public String getDescription() { return description; }+ public void setDescription(String description) { this.description = description; }++ public String getIpAddressVersion() { return ipAddressVersion; }+ public void setIpAddressVersion(String ipAddressVersion) { this.ipAddressVersion = ipAddressVersion; }++ public List<String> getAddresses() { return addresses; }+ public void setAddresses(List<String> addresses) { this.addresses = addresses; }++ public String getLockToken() { return lockToken; }+ public void setLockToken(String lockToken) { this.lockToken = lockToken; }++ public String getRegion() { return region; }+ public void setRegion(String region) { this.region = region; }++ public Map<String, String> getTags() { return tags; }+ public void setTags(Map<String, String> tags) { this.tags = tags; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/wafv2/model/RegexPatternSet.java b/src/main/java/io/github/hectorvent/floci/services/wafv2/model/RegexPatternSet.javanew file mode 100644index 0000000000..de67fe2e9e--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/wafv2/model/RegexPatternSet.java@@ -0,0 +1,54 @@+package io.github.hectorvent.floci.services.wafv2.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;++/** WAF v2 regex pattern set. {@code regularExpressionList} holds the regex strings. */+@RegisterForReflection+public class RegexPatternSet {++ private String id;+ private String name;+ private String arn;+ private String scope;+ private String description;+ private List<String> regularExpressionList = new ArrayList<>();+ private String lockToken;+ private String region;+ private Map<String, String> tags = new HashMap<>();++ public RegexPatternSet() {}++ public String getId() { return id; }+ public void setId(String id) { this.id = id; }++ public String getName() { return name; }+ public void setName(String name) { this.name = name; }++ public String getArn() { return arn; }+ public void setArn(String arn) { this.arn = arn; }++ public String getScope() { return scope; }+ public void setScope(String scope) { this.scope = scope; }++ public String getDescription() { return description; }+ public void setDescription(String description) { this.description = description; }++ public List<String> getRegularExpressionList() { return regularExpressionList; }+ public void setRegularExpressionList(List<String> regularExpressionList) {+ this.regularExpressionList = regularExpressionList;+ }++ public String getLockToken() { return lockToken; }+ public void setLockToken(String lockToken) { this.lockToken = lockToken; }++ public String getRegion() { return region; }+ public void setRegion(String region) { this.region = region; }++ public Map<String, String> getTags() { return tags; }+ public void setTags(Map<String, String> tags) { this.tags = tags; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/wafv2/model/RuleGroup.java b/src/main/java/io/github/hectorvent/floci/services/wafv2/model/RuleGroup.javanew file mode 100644index 0000000000..6a60a770e5--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/wafv2/model/RuleGroup.java@@ -0,0 +1,70 @@+package io.github.hectorvent.floci.services.wafv2.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.util.HashMap;+import java.util.Map;++/**+ * WAF v2 rule group. {@code rules}, {@code visibilityConfig} and+ * {@code customResponseBodies} are stored as raw JSON strings. {@code capacity} is the+ * caller-declared WCU budget for the group.+ */+@RegisterForReflection+public class RuleGroup {++ private String id;+ private String name;+ private String arn;+ private String scope;+ private String description;+ private long capacity;+ private String rules;+ private String visibilityConfig;+ private String customResponseBodies;+ private String labelNamespace;+ private String lockToken;+ private String region;+ private Map<String, String> tags = new HashMap<>();++ public RuleGroup() {}++ public String getId() { return id; }+ public void setId(String id) { this.id = id; }++ public String getName() { return name; }+ public void setName(String name) { this.name = name; }++ public String getArn() { return arn; }+ public void setArn(String arn) { this.arn = arn; }++ public String getScope() { return scope; }+ public void setScope(String scope) { this.scope = scope; }++ public String getDescription() { return description; }+ public void setDescription(String description) { this.description = description; }++ public long getCapacity() { return capacity; }+ public void setCapacity(long capacity) { this.capacity = capacity; }++ public String getRules() { return rules; }+ public void setRules(String rules) { this.rules = rules; }++ public String getVisibilityConfig() { return visibilityConfig; }+ public void setVisibilityConfig(String visibilityConfig) { this.visibilityConfig = visibilityConfig; }++ public String getCustomResponseBodies() { return customResponseBodies; }+ public void setCustomResponseBodies(String customResponseBodies) { this.customResponseBodies = customResponseBodies; }++ public String getLabelNamespace() { return labelNamespace; }+ public void setLabelNamespace(String labelNamespace) { this.labelNamespace = labelNamespace; }++ public String getLockToken() { return lockToken; }+ public void setLockToken(String lockToken) { this.lockToken = lockToken; }++ public String getRegion() { return region; }+ public void setRegion(String region) { this.region = region; }++ public Map<String, String> getTags() { return tags; }+ public void setTags(Map<String, String> tags) { this.tags = tags; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/wafv2/model/WebAcl.java b/src/main/java/io/github/hectorvent/floci/services/wafv2/model/WebAcl.javanew file mode 100644index 0000000000..3367a96412--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/wafv2/model/WebAcl.java@@ -0,0 +1,103 @@+package io.github.hectorvent.floci.services.wafv2.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;++/**+ * WAF v2 Web ACL. Recursive sub-structures (DefaultAction, Rules, VisibilityConfig,+ * CaptchaConfig, ChallengeConfig, AssociationConfig, CustomResponseBodies) are stored+ * as raw JSON strings and re-emitted verbatim — Phase 1 does not parse rule logic.+ * {@code lockToken} backs the optimistic-concurrency contract; it is returned beside+ * the resource on Get and rotated on Update, never embedded in the wire WebACL shape.+ */+@RegisterForReflection+public class WebAcl {++ private String id;+ private String name;+ private String arn;+ private String scope;+ private String description;+ private String defaultAction;+ private String rules;+ private String visibilityConfig;+ private long capacity;+ private String customResponseBodies;+ private String captchaConfig;+ private String challengeConfig;+ private List<String> tokenDomains = new ArrayList<>();+ private String associationConfig;+ private String dataProtectionConfig;+ private String labelNamespace;+ private String lockToken;+ private String region;+ private Instant creationTime;+ private Map<String, String> tags = new HashMap<>();++ public WebAcl() {}++ public String getId() { return id; }+ public void setId(String id) { this.id = id; }++ public String getName() { return name; }+ public void setName(String name) { this.name = name; }++ public String getArn() { return arn; }+ public void setArn(String arn) { this.arn = arn; }++ public String getScope() { return scope; }+ public void setScope(String scope) { this.scope = scope; }++ public String getDescription() { return description; }+ public void setDescription(String description) { this.description = description; }++ public String getDefaultAction() { return defaultAction; }+ public void setDefaultAction(String defaultAction) { this.defaultAction = defaultAction; }++ public String getRules() { return rules; }+ public void setRules(String rules) { this.rules = rules; }++ public String getVisibilityConfig() { return visibilityConfig; }+ public void setVisibilityConfig(String visibilityConfig) { this.visibilityConfig = visibilityConfig; }++ public long getCapacity() { return capacity; }+ public void setCapacity(long capacity) { this.capacity = capacity; }++ public String getCustomResponseBodies() { return customResponseBodies; }+ public void setCustomResponseBodies(String customResponseBodies) { this.customResponseBodies = customResponseBodies; }++ public String getCaptchaConfig() { return captchaConfig; }+ public void setCaptchaConfig(String captchaConfig) { this.captchaConfig = captchaConfig; }++ public String getChallengeConfig() { return challengeConfig; }+ public void setChallengeConfig(String challengeConfig) { this.challengeConfig = challengeConfig; }++ public List<String> getTokenDomains() { return tokenDomains; }+ public void setTokenDomains(List<String> tokenDomains) { this.tokenDomains = tokenDomains; }++ public String getAssociationConfig() { return associationConfig; }+ public void setAssociationConfig(String associationConfig) { this.associationConfig = associationConfig; }++ public String getDataProtectionConfig() { return dataProtectionConfig; }+ public void setDataProtectionConfig(String dataProtectionConfig) { this.dataProtectionConfig = dataProtectionConfig; }++ public String getLabelNamespace() { return labelNamespace; }+ public void setLabelNamespace(String labelNamespace) { this.labelNamespace = labelNamespace; }++ public String getLockToken() { return lockToken; }+ public void setLockToken(String lockToken) { this.lockToken = lockToken; }++ public String getRegion() { return region; }+ public void setRegion(String region) { this.region = region; }++ public Instant getCreationTime() { return creationTime; }+ public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; }++ public Map<String, String> getTags() { return tags; }+ public void setTags(Map<String, String> tags) { this.tags = tags; }+}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex 9b38571b0d..a82a73e61d 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -198,6 +198,8 @@ floci:enabled: trueemr:enabled: true+ wafv2:+ enabled: truescheduler:enabled: truecloudwatchlogs:diff --git a/src/test/java/io/github/hectorvent/floci/services/wafv2/WafV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/wafv2/WafV2IntegrationTest.javanew file mode 100644index 0000000000..88937fb154--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/wafv2/WafV2IntegrationTest.java@@ -0,0 +1,208 @@+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.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasSize;+import static org.hamcrest.Matchers.not;+import static org.hamcrest.Matchers.notNullValue;++/**+ * WAF v2 management-plane flow over the AWS JSON 1.1 wire protocol: IP set + Web ACL+ * lifecycle, LockToken optimistic concurrency, association guards, and CLOUDFRONT vs+ * REGIONAL scope isolation.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class WafV2IntegrationTest {++ private static final String CT = "application/x-amz-json-1.1";+ private static final String PREFIX = "AWSWAF_20190729.";+ private static final String API_RESOURCE_ARN =+ "arn:aws:apigateway:us-east-1::/restapis/floci-waf-test/stages/prod";++ private static String ipSetId;+ private static String ipSetArn;+ private static String webAclId;+ private static String webAclArn;+ private static String webAclLockToken;++ @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+ @Order(1)+ void createIpSet() {+ Response resp = call("CreateIPSet",+ "{\"Name\":\"floci-waf-ips\",\"Scope\":\"REGIONAL\",\"IPAddressVersion\":\"IPV4\","+ + "\"Addresses\":[\"10.0.0.0/24\",\"192.168.0.0/16\"]}");+ resp.then().statusCode(200)+ .body("Summary.Id", notNullValue())+ .body("Summary.LockToken", notNullValue());+ ipSetId = resp.jsonPath().getString("Summary.Id");+ ipSetArn = resp.jsonPath().getString("Summary.ARN");+ }++ @Test+ @Order(2)+ void duplicateIpSetNameFails() {+ call("CreateIPSet",+ "{\"Name\":\"floci-waf-ips\",\"Scope\":\"REGIONAL\",\"IPAddressVersion\":\"IPV4\","+ + "\"Addresses\":[\"10.0.0.0/24\"]}")+ .then().statusCode(400)+ .body("__type", equalTo("WAFDuplicateItemException"));+ }++ @Test+ @Order(3)+ void createWebAcl() {+ Response resp = call("CreateWebACL",+ "{\"Name\":\"floci-waf-acl\",\"Scope\":\"REGIONAL\","+ + "\"DefaultAction\":{\"Allow\":{}},"+ + "\"VisibilityConfig\":{\"SampledRequestsEnabled\":true,"+ + "\"CloudWatchMetricsEnabled\":true,\"MetricName\":\"acl\"},"+ + "\"Rules\":[{\"Name\":\"iprule\",\"Priority\":1,"+ + "\"Statement\":{\"IPSetReferenceStatement\":{\"ARN\":\"" + ipSetArn + "\"}},"+ + "\"Action\":{\"Block\":{}},"+ + "\"VisibilityConfig\":{\"SampledRequestsEnabled\":true,"+ + "\"CloudWatchMetricsEnabled\":true,\"MetricName\":\"iprule\"}}]}");+ resp.then().statusCode(200)+ .body("Summary.Id", notNullValue())+ .body("Summary.ARN", notNullValue())+ .body("Summary.LockToken", notNullValue());+ webAclId = resp.jsonPath().getString("Summary.Id");+ webAclArn = resp.jsonPath().getString("Summary.ARN");+ }++ @Test+ @Order(4)+ void getWebAcl() {+ Response resp = call("GetWebACL",+ "{\"Name\":\"floci-waf-acl\",\"Scope\":\"REGIONAL\",\"Id\":\"" + webAclId + "\"}");+ resp.then().statusCode(200)+ .body("WebACL.Name", equalTo("floci-waf-acl"))+ .body("WebACL.Rules[0].Statement.IPSetReferenceStatement.ARN", equalTo(ipSetArn))+ .body("WebACL.DefaultAction.Allow", notNullValue())+ .body("LockToken", notNullValue());+ webAclLockToken = resp.jsonPath().getString("LockToken");+ }++ @Test+ @Order(5)+ void updateWebAclRotatesLockToken() {+ Response resp = call("UpdateWebACL",+ "{\"Name\":\"floci-waf-acl\",\"Scope\":\"REGIONAL\",\"Id\":\"" + webAclId + "\","+ + "\"LockToken\":\"" + webAclLockToken + "\","+ + "\"Description\":\"updated\","+ + "\"DefaultAction\":{\"Block\":{}},"+ + "\"VisibilityConfig\":{\"SampledRequestsEnabled\":true,"+ + "\"CloudWatchMetricsEnabled\":true,\"MetricName\":\"acl\"}}");+ resp.then().statusCode(200).body("NextLockToken", notNullValue());+ String next = resp.jsonPath().getString("NextLockToken");+ org.junit.jupiter.api.Assertions.assertNotEquals(webAclLockToken, next);+ }++ @Test+ @Order(6)+ void staleLockTokenUpdateFails() {+ // webAclLockToken is now stale after the previous update.+ call("UpdateWebACL",+ "{\"Name\":\"floci-waf-acl\",\"Scope\":\"REGIONAL\",\"Id\":\"" + webAclId + "\","+ + "\"LockToken\":\"" + webAclLockToken + "\","+ + "\"DefaultAction\":{\"Allow\":{}},"+ + "\"VisibilityConfig\":{\"SampledRequestsEnabled\":true,"+ + "\"CloudWatchMetricsEnabled\":true,\"MetricName\":\"acl\"}}")+ .then().statusCode(400)+ .body("__type", equalTo("WAFOptimisticLockException"));+ }++ @Test+ @Order(7)+ void associateAndQuery() {+ call("AssociateWebACL",+ "{\"WebACLArn\":\"" + webAclArn + "\",\"ResourceArn\":\"" + API_RESOURCE_ARN + "\"}")+ .then().statusCode(200);++ call("GetWebACLForResource", "{\"ResourceArn\":\"" + API_RESOURCE_ARN + "\"}")+ .then().statusCode(200)+ .body("WebACL.Id", equalTo(webAclId));++ call("ListResourcesForWebACL", "{\"WebACLArn\":\"" + webAclArn + "\"}")+ .then().statusCode(200)+ .body("ResourceArns", hasSize(1))+ .body("ResourceArns[0]", equalTo(API_RESOURCE_ARN));+ }++ @Test+ @Order(8)+ void deleteWebAclWhileAssociatedFails() {+ String lockToken = call("GetWebACL",+ "{\"Name\":\"floci-waf-acl\",\"Scope\":\"REGIONAL\",\"Id\":\"" + webAclId + "\"}")+ .jsonPath().getString("LockToken");+ call("DeleteWebACL",+ "{\"Name\":\"floci-waf-acl\",\"Scope\":\"REGIONAL\",\"Id\":\"" + webAclId + "\","+ + "\"LockToken\":\"" + lockToken + "\"}")+ .then().statusCode(400)+ .body("__type", equalTo("WAFAssociatedItemException"));+ }++ @Test+ @Order(9)+ void cloudfrontScopeIsolatedFromRegional() {+ // Same Name in CLOUDFRONT scope must not collide with the REGIONAL IP set.+ call("CreateIPSet",+ "{\"Name\":\"floci-waf-ips\",\"Scope\":\"CLOUDFRONT\",\"IPAddressVersion\":\"IPV4\","+ + "\"Addresses\":[\"172.16.0.0/12\"]}")+ .then().statusCode(200);++ call("ListIPSets", "{\"Scope\":\"CLOUDFRONT\"}")+ .then().statusCode(200)+ .body("IPSets.find { it.Name == 'floci-waf-ips' }.ARN", not(equalTo(ipSetArn)));+ }++ @Test+ @Order(10)+ void teardown() {+ call("DisassociateWebACL", "{\"ResourceArn\":\"" + API_RESOURCE_ARN + "\"}")+ .then().statusCode(200);+ String lockToken = call("GetWebACL",+ "{\"Name\":\"floci-waf-acl\",\"Scope\":\"REGIONAL\",\"Id\":\"" + webAclId + "\"}")+ .jsonPath().getString("LockToken");+ call("DeleteWebACL",+ "{\"Name\":\"floci-waf-acl\",\"Scope\":\"REGIONAL\",\"Id\":\"" + webAclId + "\","+ + "\"LockToken\":\"" + lockToken + "\"}")+ .then().statusCode(200);++ String ipLock = call("GetIPSet",+ "{\"Name\":\"floci-waf-ips\",\"Scope\":\"REGIONAL\",\"Id\":\"" + ipSetId + "\"}")+ .jsonPath().getString("LockToken");+ call("DeleteIPSet",+ "{\"Name\":\"floci-waf-ips\",\"Scope\":\"REGIONAL\",\"Id\":\"" + ipSetId + "\","+ + "\"LockToken\":\"" + ipLock + "\"}")+ .then().statusCode(200);+ }++ @Test+ @Order(11)+ void getMissingWebAclReturnsNotFound() {+ call("GetWebACL",+ "{\"Name\":\"nope\",\"Scope\":\"REGIONAL\",\"Id\":\"00000000-0000-0000-0000-000000000000\"}")+ .then().statusCode(404)+ .body("__type", equalTo("WAFNonexistentItemException"));+ }+}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex 20e0ca2860..c5ed3600b7 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -114,6 +114,8 @@ floci:enabled: trueemr:enabled: true+ wafv2:+ enabled: truescheduler:enabled: truecloudwatchlogs: