feat(cloudformation): provision WAFv2 web ACLs and AWS Config rules (#2701)

* feat: provision WAFv2 web ACLs

* feat: provision AWS Config rules

* fix: adapt provisioners to current 3-arg CfnResourceProvisioner.delete()

* fix: preserve new-resource tracking when replacement cleanup fails, and stop dropping inline-object InputParameters

Local code review (review-local.ts) flagged two ordering bugs on the replacement
path in both provisioners: the new resource's physicalId/attributes were only
recorded after the old resource's delete call succeeded, so a delete failure
(e.g. WAFAssociatedItemException, or a Config rule still referenced elsewhere)
left the stack tracking the old resource while the newly created one leaked
untracked. Both now record the new resource first and treat old-resource
cleanup failure as non-fatal, matching the existing precedent in
Ec2LaunchTemplateCfnProvisioner.

Also fixed AWS::Config::ConfigRule.InputParameters being silently dropped
when a template supplies it as an inline JSON object (the common case) rather
than a pre-stringified JSON string: JsonNode.asText() returns empty string
for object nodes.

* fix(cloudformation): preserve intrinsic-resolved JSON fields on WAFv2 WebACL, log tolerated replacement-cleanup failures, add GetAtt coverage

raw() in WafV2CfnProvisioner used JsonNode#isEmpty(), which is true for every
scalar node, so any field CloudFormationTemplateEngine#resolveNode collapsed
into a TextNode (e.g. an Fn::Join-built DefaultAction) silently became null
instead of the literal JSON text. Mirror ConfigCfnProvisioner's existing
isTextual()-aware handling.

Also log (previously fully swallowed) exceptions when replacement cleanup of
the superseded WAFv2 WebACL or Config rule fails, so a leaked old resource is
diagnosable, and add an integration test asserting the exact Fn::GetAtt keys
for both provisioners resolve through CloudFormation to the real resource.

Config's PutConfigRule call being unconditional on every provision is correct
AWS upsert semantics ("Adds or updates" per the Config API), not a missing
create/update branch.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-08-29 15:28:23 -04:00
1 parent a1383fdd3d
commit 8a705d0aae
6 files changed
+724

No files matched your search

+2
View File
@@ -85,6 +85,8 @@ cross-resource references.
| Kinesis Data Firehose | `DeliveryStream` |
| CloudWatch | `Alarm` |
| CloudWatch Logs | `LogGroup` |
| WAFv2 | `WebACL` |
| Config | `ConfigRule` |
| CloudFormation | `Stack` (nested stacks), `CustomResource` and `Custom::*` (Lambda-backed) |
| CDK | `CDK::Metadata` (accepted; no-op) |
@@ -0,0 +1,137 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.configservice.AwsConfigService;
import io.github.hectorvent.floci.services.configservice.model.ConfigRule;
import io.github.hectorvent.floci.services.configservice.model.ConfigRuleSource;
import io.github.hectorvent.floci.services.configservice.model.CustomPolicyDetails;
import io.github.hectorvent.floci.services.configservice.model.EvaluationModeConfiguration;
import io.github.hectorvent.floci.services.configservice.model.Scope;
import io.github.hectorvent.floci.services.configservice.model.SourceDetail;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@ApplicationScoped
public class ConfigCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(ConfigCfnProvisioner.class);
private static final String CONFIG_RULE = "AWS::Config::ConfigRule";
private final AwsConfigService configService;
@Inject
public ConfigCfnProvisioner(AwsConfigService configService) {
this.configService = configService;
}
@Override
public Set<String> resourceTypes() {
return Set.of(CONFIG_RULE);
}
@Override
public void provision(StackResource resource, JsonNode props, ProvisionContext ctx) {
JsonNode resolved = ctx.engine().resolveNode(props);
String previousName = resource.getPhysicalId();
String name = text(resolved, "ConfigRuleName");
if (name == null || name.isBlank()) {
name = previousName == null
? ctx.generatePhysicalName(resource.getLogicalId(), 128, false)
: previousName;
}
ConfigRule rule = configService.putConfigRule(ctx.region(), new ConfigRule(
name, null, null, text(resolved, "Description"), scope(resolved.path("Scope")),
source(resolved.path("Source")), inputParameters(resolved.path("InputParameters")),
text(resolved, "MaximumExecutionFrequency"), null, null,
evaluationModes(resolved.path("EvaluationModes"))));
resource.setPhysicalId(rule.configRuleName());
resource.getAttributes().put("Arn", rule.configRuleArn());
resource.getAttributes().put("ConfigRuleId", rule.configRuleId());
if (previousName != null && !previousName.equals(name)) {
try {
deleteIfPresent(ctx.region(), previousName);
} catch (RuntimeException e) {
// old rule may still be referenced elsewhere; new rule is already tracked
LOG.warnv("Config CFN replacement cleanup of rule {0} tolerated: {1}",
previousName, e.getMessage());
}
}
}
@Override
public void delete(String resourceType, String physicalId, String region) {
deleteIfPresent(region, physicalId);
}
private void deleteIfPresent(String region, String name) {
if (name == null) {
return;
}
if (configService.describeConfigRules(region, List.of()).stream()
.anyMatch(rule -> name.equals(rule.configRuleName()))) {
configService.deleteConfigRule(region, name);
}
}
private Scope scope(JsonNode node) {
if (!node.isObject()) {
return null;
}
return new Scope(strings(node.path("ComplianceResourceTypes")), text(node, "TagKey"),
text(node, "TagValue"), text(node, "ComplianceResourceId"));
}
private ConfigRuleSource source(JsonNode node) {
List<SourceDetail> details = new ArrayList<>();
JsonNode detailNodes = node.path("SourceDetails");
if (detailNodes.isArray()) {
for (JsonNode detail : detailNodes) {
details.add(new SourceDetail(text(detail, "EventSource"), text(detail, "MessageType"),
text(detail, "MaximumExecutionFrequency")));
}
}
JsonNode policy = node.path("CustomPolicyDetails");
CustomPolicyDetails customPolicy = policy.isObject()
? new CustomPolicyDetails(text(policy, "PolicyRuntime"), text(policy, "PolicyText"),
policy.has("EnableDebugLogDelivery")
? policy.get("EnableDebugLogDelivery").asBoolean() : null)
: null;
return new ConfigRuleSource(text(node, "Owner"), text(node, "SourceIdentifier"),
details.isEmpty() ? null : details, customPolicy);
}
private List<EvaluationModeConfiguration> evaluationModes(JsonNode nodes) {
if (!nodes.isArray()) {
return null;
}
List<EvaluationModeConfiguration> modes = new ArrayList<>();
nodes.forEach(node -> modes.add(new EvaluationModeConfiguration(text(node, "Mode"))));
return modes;
}
private List<String> strings(JsonNode nodes) {
List<String> values = new ArrayList<>();
if (nodes.isArray()) {
nodes.forEach(node -> values.add(node.asText()));
}
return values;
}
private String text(JsonNode node, String field) {
JsonNode value = node == null ? null : node.get(field);
return value == null || value.isNull() ? null : value.asText();
}
private String inputParameters(JsonNode node) {
if (node == null || node.isMissingNode() || node.isNull()) {
return null;
}
return node.isTextual() ? node.asText() : node.toString();
}
}
@@ -0,0 +1,153 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
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.WebAcl;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@ApplicationScoped
public class WafV2CfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(WafV2CfnProvisioner.class);
private static final String WEB_ACL = "AWS::WAFv2::WebACL";
private final WafV2Service wafV2Service;
@Inject
public WafV2CfnProvisioner(WafV2Service wafV2Service) {
this.wafV2Service = wafV2Service;
}
@Override
public Set<String> resourceTypes() {
return Set.of(WEB_ACL);
}
@Override
public void provision(StackResource resource, JsonNode props, ProvisionContext ctx) {
JsonNode resolved = ctx.engine().resolveNode(props);
String name = text(resolved, "Name");
WebAcl existing = findExisting(resource.getPhysicalId());
if (name == null || name.isBlank()) {
name = existing == null
? ctx.generatePhysicalName(resource.getLogicalId(), 128, false)
: existing.getName();
}
String scope = text(resolved, "Scope");
WebAcl desired = fromProperties(resolved);
WebAcl acl;
if (existing != null && existing.getName().equals(name) && existing.getScope().equals(scope)) {
wafV2Service.updateWebAcl(desired, scope, existing.getId(), existing.getLockToken());
acl = wafV2Service.getWebAcl(scope, existing.getId());
reconcileTags(acl, desired.getTags());
} else {
acl = wafV2Service.createWebAcl(desired, scope, name, ctx.region());
setReferences(resource, acl);
if (existing != null) {
try {
wafV2Service.deleteWebAcl(existing.getScope(), existing.getId(), existing.getLockToken());
} catch (RuntimeException e) {
// old ACL may still be associated with a resource; new ACL is already tracked
LOG.warnv("WAFv2 CFN replacement cleanup of {0}|{1}|{2} tolerated: {3}",
existing.getName(), existing.getId(), existing.getScope(), e.getMessage());
}
}
return;
}
setReferences(resource, acl);
}
@Override
public void delete(String resourceType, String physicalId, String region) {
WebAcl existing = findExisting(physicalId);
if (existing != null) {
wafV2Service.deleteWebAcl(existing.getScope(), existing.getId(), existing.getLockToken());
}
}
private WebAcl fromProperties(JsonNode props) {
WebAcl acl = new WebAcl();
acl.setDescription(text(props, "Description"));
acl.setDefaultAction(raw(props, "DefaultAction"));
acl.setRules(raw(props, "Rules"));
acl.setVisibilityConfig(raw(props, "VisibilityConfig"));
acl.setCustomResponseBodies(raw(props, "CustomResponseBodies"));
acl.setCaptchaConfig(raw(props, "CaptchaConfig"));
acl.setChallengeConfig(raw(props, "ChallengeConfig"));
acl.setAssociationConfig(raw(props, "AssociationConfig"));
acl.setDataProtectionConfig(raw(props, "DataProtectionConfig"));
List<String> tokenDomains = new ArrayList<>();
JsonNode tokens = props.path("TokenDomains");
if (tokens.isArray()) {
tokens.forEach(token -> tokenDomains.add(token.asText()));
}
acl.setTokenDomains(tokenDomains);
Map<String, String> tags = new LinkedHashMap<>();
JsonNode tagNodes = props.path("Tags");
if (tagNodes.isArray()) {
for (JsonNode tag : tagNodes) {
String key = text(tag, "Key");
if (key != null) {
tags.put(key, text(tag, "Value"));
}
}
}
acl.setTags(tags);
return acl;
}
private void reconcileTags(WebAcl existing, Map<String, String> desired) {
List<String> removed = existing.getTags().keySet().stream()
.filter(key -> !desired.containsKey(key)).toList();
if (!removed.isEmpty()) {
wafV2Service.untagResource(existing.getArn(), removed);
}
if (!desired.isEmpty()) {
wafV2Service.tagResource(existing.getArn(), desired);
}
}
private WebAcl findExisting(String physicalId) {
String[] parts = physicalId == null ? new String[0] : physicalId.split("\\|", -1);
if (parts.length != 3) {
return null;
}
return wafV2Service.listWebAcls(parts[2]).stream()
.filter(acl -> parts[1].equals(acl.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());
resource.getAttributes().put("Capacity", Long.toString(acl.getCapacity()));
resource.getAttributes().put("Id", acl.getId());
resource.getAttributes().put("LabelNamespace", acl.getLabelNamespace());
}
private String text(JsonNode node, String field) {
JsonNode value = node == null ? null : node.get(field);
return value == null || value.isNull() ? null : value.asText();
}
private String raw(JsonNode node, String field) {
JsonNode value = node == null ? null : node.get(field);
if (value == null || value.isNull()) {
return null;
}
if (value.isTextual()) {
return value.asText();
}
return value.isEmpty() ? null : value.toString();
}
}
@@ -0,0 +1,163 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
/**
* End-to-end check that CloudFormation registers real {@code Fn::GetAtt} attributes for
* AWS::WAFv2::WebACL and AWS::Config::ConfigRule rather than leaving them to resolve to
* literal placeholders. Both resources are metadata (no container), so this is Docker-free.
*/
@QuarkusTest
class CloudFormationWafV2ConfigGetAttIntegrationTest {
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.";
private static final String CONFIG_JSON = "application/x-amz-json-1.1";
private static final String CONFIG_TARGET_PREFIX = "StarlingDoveService.";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void createStackProvisionsWebAclAndResolvesGetAtt() {
String suffix = Long.toString(System.nanoTime(), 36);
String aclName = "cfn-acl-" + suffix;
String stackName = "cfn-wafv2-getatt-stack-" + suffix;
String template = """
{
"Resources": {
"Acl": {
"Type": "AWS::WAFv2::WebACL",
"Properties": {
"Name": "%s",
"Scope": "REGIONAL",
"DefaultAction": {"Allow": {}},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "%s"
}
}
}
},
"Outputs": {
"AclArn": {"Value": {"Fn::GetAtt": ["Acl", "Arn"]}},
"AclId": {"Value": {"Fn::GetAtt": ["Acl", "Id"]}}
}
}
""".formatted(aclName, aclName);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
String describeBody = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
.extract().asString();
// The GetAtt Id output must be the real WAFv2 WebACL id, not a synthetic placeholder —
// recover it from the Outputs and confirm the ACL is really registered under it.
String idMarker = "<OutputKey>AclId</OutputKey><OutputValue>";
int idStart = describeBody.indexOf(idMarker) + idMarker.length();
String aclId = describeBody.substring(idStart, describeBody.indexOf("</OutputValue>", idStart));
given()
.contentType(WAF_JSON)
.header("X-Amz-Target", WAF_TARGET_PREFIX + "GetWebACL")
.body("{\"Name\":\"" + aclName + "\",\"Scope\":\"REGIONAL\",\"Id\":\"" + aclId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("WebACL.Name", org.hamcrest.Matchers.equalTo(aclName));
}
@Test
void createStackProvisionsConfigRuleAndResolvesGetAtt() {
String suffix = Long.toString(System.nanoTime(), 36);
String ruleName = "cfn-rule-" + suffix;
String stackName = "cfn-config-getatt-stack-" + suffix;
String template = """
{
"Resources": {
"Rule": {
"Type": "AWS::Config::ConfigRule",
"Properties": {
"ConfigRuleName": "%s",
"Source": {
"Owner": "AWS",
"SourceIdentifier": "S3_BUCKET_PUBLIC_READ_PROHIBITED"
}
}
}
},
"Outputs": {
"RuleArn": {"Value": {"Fn::GetAtt": ["Rule", "Arn"]}},
"RuleId": {"Value": {"Fn::GetAtt": ["Rule", "ConfigRuleId"]}}
}
}
""".formatted(ruleName);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
.body(containsString("<OutputKey>RuleArn</OutputKey>"))
.body(containsString("<OutputKey>RuleId</OutputKey>"));
// The rule really exists in AWS Config, addressable by the name CloudFormation used.
given()
.contentType(CONFIG_JSON)
.header("X-Amz-Target", CONFIG_TARGET_PREFIX + "DescribeConfigRules")
.body("{\"ConfigRuleNames\":[\"" + ruleName + "\"]}")
.when()
.post("/")
.then()
.statusCode(200)
.body("ConfigRules[0].ConfigRuleName", org.hamcrest.Matchers.equalTo(ruleName));
}
}
@@ -0,0 +1,128 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.configservice.AwsConfigService;
import io.github.hectorvent.floci.services.configservice.model.ConfigRule;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ConfigCfnProvisionerTest {
private final AwsConfigService config = mock(AwsConfigService.class);
private final ConfigCfnProvisioner provisioner = new ConfigCfnProvisioner(config);
private final ObjectMapper mapper = new ObjectMapper();
@Test
void configRuleMapsCustomPolicyAndSetsAwsReferences() {
ObjectNode props = mapper.createObjectNode()
.put("ConfigRuleName", "tenant-isolation")
.put("Description", "requires tenant tags");
props.set("Scope", mapper.createObjectNode().set("ComplianceResourceTypes",
mapper.createArrayNode().add("AWS::S3::Bucket").add("AWS::SQS::Queue")));
ObjectNode source = mapper.createObjectNode().put("Owner", "CUSTOM_POLICY");
source.set("SourceDetails", mapper.createArrayNode().add(mapper.createObjectNode()
.put("EventSource", "aws.config")
.put("MessageType", "ConfigurationItemChangeNotification")));
source.set("CustomPolicyDetails", mapper.createObjectNode()
.put("PolicyRuntime", "guard-2.x.x")
.put("PolicyText", "rule tenant_isolation { true }")
.put("EnableDebugLogDelivery", false));
props.set("Source", source);
ConfigRule stored = new ConfigRule("tenant-isolation", "arn:rule", "config-rule-123",
null, null, null, null, null, "ACTIVE", null, List.of());
when(config.putConfigRule(eq("us-east-1"), any())).thenReturn(stored);
when(config.describeConfigRules("us-east-1", List.of())).thenReturn(List.of());
StackResource resource = resource();
provisioner.provision(resource, props, context());
ArgumentCaptor<ConfigRule> desired = ArgumentCaptor.forClass(ConfigRule.class);
verify(config).putConfigRule(eq("us-east-1"), desired.capture());
assertEquals(List.of("AWS::S3::Bucket", "AWS::SQS::Queue"),
desired.getValue().scope().complianceResourceTypes());
assertEquals("CUSTOM_POLICY", desired.getValue().source().owner());
assertEquals("guard-2.x.x", desired.getValue().source().customPolicyDetails().policyRuntime());
assertEquals("tenant-isolation", resource.getPhysicalId());
assertEquals("arn:rule", resource.getAttributes().get("Arn"));
assertEquals("config-rule-123", resource.getAttributes().get("ConfigRuleId"));
}
@Test
void inputParametersGivenAsInlineJsonObjectIsSerializedNotDropped() {
ObjectNode props = mapper.createObjectNode()
.put("ConfigRuleName", "tenant-isolation");
props.set("Source", mapper.createObjectNode().put("Owner", "AWS")
.put("SourceIdentifier", "S3_BUCKET_VERSIONING_ENABLED"));
props.set("InputParameters", mapper.createObjectNode().put("minimumRetentionDays", "30"));
ConfigRule stored = new ConfigRule("tenant-isolation", "arn:rule", "config-rule-123",
null, null, null, null, null, "ACTIVE", null, List.of());
when(config.putConfigRule(eq("us-east-1"), any())).thenReturn(stored);
when(config.describeConfigRules("us-east-1", List.of())).thenReturn(List.of());
StackResource resource = resource();
provisioner.provision(resource, props, context());
ArgumentCaptor<ConfigRule> desired = ArgumentCaptor.forClass(ConfigRule.class);
verify(config).putConfigRule(eq("us-east-1"), desired.capture());
assertEquals("{\"minimumRetentionDays\":\"30\"}", desired.getValue().inputParameters());
}
@Test
void renameTracksNewRuleEvenWhenOldRuleDeleteFails() {
ObjectNode props = mapper.createObjectNode().put("ConfigRuleName", "renamed-rule");
props.set("Source", mapper.createObjectNode().put("Owner", "AWS")
.put("SourceIdentifier", "S3_BUCKET_VERSIONING_ENABLED"));
ConfigRule stored = new ConfigRule("renamed-rule", "arn:renamed", "config-rule-456",
null, null, null, null, null, "ACTIVE", null, List.of());
when(config.putConfigRule(eq("us-east-1"), any())).thenReturn(stored);
when(config.describeConfigRules("us-east-1", List.of()))
.thenReturn(List.of(new ConfigRule("old-rule", "arn:old", "config-rule-123",
null, null, null, null, null, "ACTIVE", null, List.of())));
org.mockito.Mockito.doThrow(new RuntimeException("rule in use"))
.when(config).deleteConfigRule("us-east-1", "old-rule");
StackResource resource = resource();
resource.setPhysicalId("old-rule");
provisioner.provision(resource, props, context());
assertEquals("renamed-rule", resource.getPhysicalId());
assertEquals("arn:renamed", resource.getAttributes().get("Arn"));
}
@Test
void deleteIsIdempotent() {
when(config.describeConfigRules("us-east-1", List.of())).thenReturn(List.of());
provisioner.delete("AWS::Config::ConfigRule", "missing", "us-east-1");
verify(config).describeConfigRules("us-east-1", List.of());
}
private ProvisionContext context() {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolveNode(any(JsonNode.class))).thenAnswer(inv -> inv.getArgument(0));
return new ProvisionContext(engine, "us-east-1", "111122223333", "stack");
}
private StackResource resource() {
StackResource resource = new StackResource();
resource.setLogicalId("TenantIsolation");
resource.setResourceType("AWS::Config::ConfigRule");
resource.setAttributes(new HashMap<>());
return resource;
}
}
@@ -0,0 +1,141 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
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.WebAcl;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class WafV2CfnProvisionerTest {
private final WafV2Service wafV2 = mock(WafV2Service.class);
private final WafV2CfnProvisioner provisioner = new WafV2CfnProvisioner(wafV2);
private final ObjectMapper mapper = new ObjectMapper();
@Test
void webAclCreatesBackingResourceAndSetsAwsReferences() {
ObjectNode props = mapper.createObjectNode()
.put("Name", "portal")
.put("Scope", "REGIONAL")
.put("Description", "edge policy");
props.set("DefaultAction", mapper.createObjectNode().set("Allow", mapper.createObjectNode()));
props.set("VisibilityConfig", mapper.createObjectNode().put("MetricName", "portal"));
props.set("Rules", mapper.createArrayNode().add(mapper.createObjectNode().put("Name", "managed")));
props.set("Tags", mapper.createArrayNode()
.add(mapper.createObjectNode().put("Key", "Owner").put("Value", "Platform")));
WebAcl created = acl("portal", "acl-123", "REGIONAL", "lock-1");
created.setArn("arn:aws:wafv2:us-east-1:111122223333:regional/webacl/portal/acl-123");
created.setCapacity(2);
created.setLabelNamespace("awswaf:111122223333:webacl:portal:");
when(wafV2.createWebAcl(any(), eq("REGIONAL"), eq("portal"), eq("us-east-1")))
.thenReturn(created);
StackResource resource = resource();
provisioner.provision(resource, props, context());
ArgumentCaptor<WebAcl> desired = ArgumentCaptor.forClass(WebAcl.class);
verify(wafV2).createWebAcl(desired.capture(), eq("REGIONAL"), eq("portal"), eq("us-east-1"));
assertEquals("{\"Allow\":{}}", desired.getValue().getDefaultAction());
assertEquals("Platform", desired.getValue().getTags().get("Owner"));
assertEquals("portal|acl-123|REGIONAL", resource.getPhysicalId());
assertEquals(created.getArn(), resource.getAttributes().get("Arn"));
assertEquals("acl-123", resource.getAttributes().get("Id"));
assertEquals("2", resource.getAttributes().get("Capacity"));
assertEquals(created.getLabelNamespace(), resource.getAttributes().get("LabelNamespace"));
}
@Test
void sameNamedWebAclUpdatesInPlace() {
WebAcl existing = acl("portal", "acl-123", "REGIONAL", "lock-1");
WebAcl updated = acl("portal", "acl-123", "REGIONAL", "lock-2");
updated.setArn("arn:updated");
when(wafV2.listWebAcls("REGIONAL")).thenReturn(List.of(existing));
when(wafV2.getWebAcl("REGIONAL", "acl-123")).thenReturn(updated);
StackResource resource = resource();
resource.setPhysicalId("portal|acl-123|REGIONAL");
ObjectNode props = mapper.createObjectNode().put("Name", "portal").put("Scope", "REGIONAL");
provisioner.provision(resource, props, context());
verify(wafV2).updateWebAcl(any(), eq("REGIONAL"), eq("acl-123"), eq("lock-1"));
assertEquals("portal|acl-123|REGIONAL", resource.getPhysicalId());
}
@Test
void replacementTracksNewAclEvenWhenOldAclDeleteFails() {
WebAcl existing = acl("portal", "acl-old", "REGIONAL", "lock-1");
WebAcl created = acl("portal-renamed", "acl-new", "REGIONAL", "lock-2");
created.setArn("arn:new");
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"))
.when(wafV2).deleteWebAcl("REGIONAL", "acl-old", "lock-1");
StackResource resource = resource();
resource.setPhysicalId("portal|acl-old|REGIONAL");
ObjectNode props = mapper.createObjectNode().put("Name", "portal-renamed").put("Scope", "REGIONAL");
provisioner.provision(resource, props, context());
assertEquals("portal-renamed|acl-new|REGIONAL", resource.getPhysicalId());
assertEquals("arn:new", resource.getAttributes().get("Arn"));
}
@Test
void intrinsicResolvedRuleFieldIsNotDoubleEncoded() {
ObjectNode props = mapper.createObjectNode().put("Name", "portal").put("Scope", "REGIONAL");
props.set("DefaultAction", mapper.createObjectNode());
ObjectNode resolved = mapper.createObjectNode().put("Name", "portal").put("Scope", "REGIONAL");
resolved.set("DefaultAction",
com.fasterxml.jackson.databind.node.TextNode.valueOf("{\"Allow\":{}}"));
WebAcl created = acl("portal", "acl-1", "REGIONAL", "lock-1");
when(wafV2.createWebAcl(any(), eq("REGIONAL"), eq("portal"), eq("us-east-1"))).thenReturn(created);
StackResource resource = resource();
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolveNode(props)).thenReturn(resolved);
ProvisionContext ctx = new ProvisionContext(engine, "us-east-1", "111122223333", "stack");
provisioner.provision(resource, props, ctx);
ArgumentCaptor<WebAcl> desired = ArgumentCaptor.forClass(WebAcl.class);
verify(wafV2).createWebAcl(desired.capture(), eq("REGIONAL"), eq("portal"), eq("us-east-1"));
assertEquals("{\"Allow\":{}}", desired.getValue().getDefaultAction());
}
private ProvisionContext context() {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolveNode(any(JsonNode.class))).thenAnswer(inv -> inv.getArgument(0));
return new ProvisionContext(engine, "us-east-1", "111122223333", "stack");
}
private StackResource resource() {
StackResource resource = new StackResource();
resource.setLogicalId("PortalWebAcl");
resource.setResourceType("AWS::WAFv2::WebACL");
resource.setAttributes(new HashMap<>());
return resource;
}
private WebAcl acl(String name, String id, String scope, String lockToken) {
WebAcl acl = new WebAcl();
acl.setName(name);
acl.setId(id);
acl.setScope(scope);
acl.setLockToken(lockToken);
return acl;
}
}