feat(networkfirewall): emulate AWS Network Firewall (#2580)

* feat: emulate AWS Network Firewall

* docs: register Network Firewall service

* feat(networkfirewall): add AssociateFirewallPolicy

Sets FirewallPolicyArn on the stored firewall, validating that both the
firewall and the policy exist. Round-trip covered by an integration test
(create -> associate -> describe shows the new policy ARN).

FirewallPolicyChangeProtection is not enforced; documented as a limitation.

* docs(networkfirewall): register the generated action table

* docs(networkfirewall): correct the service matrix protocol and action count

The Network Firewall row claimed JSON 1.1 with 25 actions; the service speaks
x-amz-json-1.0 and the generated action table lists 27.

* test(networkfirewall): assert list membership instead of positional indexes

hasSize(1) and [0] assertions coupled these tests to JUnit's method order and
to being the only resource in the store.

* fix(networkfirewall): declare the storage key and mode in the service catalog

The service persists four backends through StorageFactory, but its descriptor
left storageKey and storageMode null, so it was skipped by PersistentPathValidator
and by per-service storage configuration.

* fix(networkfirewall): reject DeleteFirewall when delete protection is enabled

AWS raises InvalidOperationException rather than deleting a protected firewall;
the emulator deleted it regardless of the flag it had already stored.

* fix(networkfirewall): give the subnet and AZ association ops real semantics

All four routed through updateFirewall, which copies request fields onto the
stored firewall wholesale. That ignored SubnetChangeProtection and
AvailabilityZoneChangeProtection, and a Disassociate call left the mappings it
was meant to remove in place. Associate now adds deduplicated mappings,
Disassociate removes the named ones, and either is rejected with
InvalidOperationException while the matching change protection is set.

DescribeFirewall only synthesises endpoints for a firewall created without
SubnetMappings, so draining every subnet now reports no sync states.

* fix(networkfirewall): name the resource kind in ResourceAlreadyExistsException

createNamed passed the response wrapper field, so a duplicate create reported
"RuleGroupResponse already exists" instead of "RuleGroup already exists".

* fix(networkfirewall): validate association requests before touching the firewall

mappingsOf() creates the mappings array on the live stored node, so it ran
before the request array was validated: a rejected DisassociateSubnets on a
firewall created without SubnetMappings left an empty array behind and
permanently suppressed the synthetic sync states in DescribeFirewall.

* fix(networkfirewall): name the resource kind in ResourceNotFoundException

describeNamed passed the response wrapper field as the kind, so a miss reported
"RuleGroupResponse not found". Same defect as the create path; the now-unused
responseField parameter goes with it.

* fix(networkfirewall): return the deleted firewall and its status from DeleteFirewall

AWS responds with {Firewall, FirewallStatus}; the emulator returned only the ARN
and name, so an SDK client parsed an empty response. The handler already had the
region in scope, so no controller change was needed.

* fix(networkfirewall): enforce modeled enums on rule group Type and logging config

Three modeled enums were read and stored without being checked.

CreateRuleGroup/UpdateRuleGroup Type: the model enumerates STATELESS, STATEFUL
and STATEFUL_DOMAIN. The prefix choice was a two-way branch, so every unmodelled
value (including a lowercase "stateful") silently fell through to the
stateful-rulegroup ARN and was persisted as a rule group AWS would have
rejected. The branch keeps its meaning deliberately: only STATELESS gets the
stateless prefix, and both stateful variants share stateful-rulegroup, matching
AWS. A test pins STATEFUL_DOMAIN to that prefix so the mapping is no longer
implicit.

UpdateLoggingConfiguration LogType (ALERT/FLOW/TLS) and LogDestinationType
(S3/CloudWatchLogs/KinesisDataFirehose): the LoggingConfiguration is stored
verbatim, so an unmodelled or wrongly-cased value was persisted and echoed back
by DescribeLoggingConfiguration. Enforced case-sensitively, as the model spells
them and as LZA's network-firewall construct sends them.

Rejections use InvalidRequestException, which both operations list.

* fix(networkfirewall): validate association requests before mutating stored mappings

mappingsOf handed back the live stored array (or installed one), so a
request with a valid mapping followed by an invalid one mutated the
firewall before the rejection. The mappings are now a detached copy,
validated in full, and attached only when storeAndRespond commits.

* fix(networkfirewall): whitelist mutable fields on the shared UpdateFirewall* path

The generic update loop copied every raw request field onto the stored
firewall, so an UpdateFirewallDescription request carrying SubnetMappings
or AvailabilityZoneMappings persisted them without the change-protection
checks the Associate/Disassociate ops enforce. The loop now copies only
the union of fields the six UpdateFirewall* operations actually model
(Description, the four protection flags, EnabledAnalysisTypes), matching
AWS dropping unmodeled request members.

* fix(networkfirewall): scope UpdateFirewall* to the invoked op's own field

The shared updateFirewall path copied any field present in the raw
request that appeared in the union of all UpdateFirewall* mutable
fields, regardless of which specific action was invoked. A plain
UpdateFirewallDescription request could therefore smuggle
DeleteProtection (or any other operation's field) past its own
dedicated operation and change-protection checks.

Each UpdateFirewall* operation models exactly one mutable field
(botocore 2020-11-12); replace the shared whitelist with a per-action
field map so a request only ever mutates the field its own action
models.

* fix(networkfirewall): default DeleteProtection/SubnetChangeProtection/FirewallPolicyChangeProtection to true

botocore's network-firewall 2020-11-12 model documents CreateFirewall as
initializing these three flags to TRUE when the caller omits them;
AvailabilityZoneChangeProtection is the lone exception, documented as
defaulting to FALSE (already correct). Floci defaulted all four to false,
so the enforcement code in firewallForChange/deleteFirewall was correct
but unreachable in the common case of an SDK/Terraform caller that omits
the flags entirely.

RED-first: createFirewall_withoutProtectionFlags_defaultsToProtected
failed against the old defaults (DeleteProtection false, expected true).
Existing tests that relied on the old false default to exercise
mutation paths now pass explicit false for the flags they don't intend
to test, matching how a real caller opts out of protection.
NetworkFirewallIntegrationTest: 27/27 green.

* fix(networkfirewall): flatten UpdateFirewall* response to the modelled shape

All six UpdateFirewall* operations shared updateFirewall(), which returned
firewallResponse()'s nested {Firewall, FirewallStatus} envelope -- the
CreateFirewall/DescribeFirewall shape. botocore 2020-11-12 models each
UpdateFirewall*Response as a flat {FirewallArn, FirewallName, <field>,
UpdateToken}, confirmed for all six ops (UpdateFirewallDescription,
UpdateFirewallDeleteProtection, UpdateSubnetChangeProtection,
UpdateFirewallPolicyChangeProtection, UpdateAvailabilityZoneChangeProtection,
UpdateFirewallAnalysisSettings). A typed SDK client got null back from every
modelled accessor.

RED-first: updateFirewallDeleteProtection_returnsTheFlatModelledShape failed
(FirewallArn/DeleteProtection/UpdateToken were all null at the top level;
present one level down inside Firewall). CreateFirewall/DescribeFirewall
still use firewallResponse() and are unaffected -- only the six Update*
callers changed. NetworkFirewallIntegrationTest: 28/28 green.

* fix(networkfirewall): omit optional update fields instead of echoing null

UpdateFirewallDescription and UpdateFirewallAnalysisSettings read the response
member back with path(), so a firewall created without Description or
EnabledAnalysisTypes serialised the resulting MissingNode as an explicit null.
Both members are optional on these ops (botocore 2020-11-12 marks no required
members on either), so the response now omits what was never set.

* docs: correct service count to 79 after the #2579 merge

The upstream/main merge (6bd7c9d3a) added two new services
(servicequotas, ram) on top of this branch's own network-firewall
addition. The merge-base count was 76; three disjoint new services
(1 ours + 2 upstream) makes 79, not 78 as the merge commit left it.

* docs: correct service count to 80 after the sso-admin merge

upstream/main reports 79 with sso-admin included; this branch adds one further
descriptor (network-firewall, 94 vs upstream's 93), so the hand-maintained count
is 80.

* fix(networkfirewall): honour change protection and clear-on-omit per the model

Two review findings, both verified against the botocore clone at
/Volumes/Extra/repos/botocore rather than the pip install.

AssociateFirewallPolicy (Greptile P1) persisted a replacement policy ARN even
with FirewallPolicyChangeProtection set. The flag is documented as protecting
'against a change to the firewall policy association' and InvalidOperationException
is in the op's modeled errors, so it now routes through firewallForChange like the
subnet and AZ association ops. An existing test created its firewall inline and so
inherited the now-default-true protection; it states the flag explicitly.

UpdateFirewallDescription (pgermosen) preserved and re-echoed a stale description
when the request omitted Description. The model is explicit: 'If you omit this
setting, Network Firewall removes the description for the firewall.' Omission now
clears the stored value.

Deliberately NOT symmetric: EnabledAnalysisTypes carries no equivalent statement
in the model, so UpdateFirewallAnalysisSettings still preserves an omitted value.
A test pins that difference so it reads as a decision rather than an oversight.

* fix(networkfirewall): serialise the association read-modify-write

mappingsOf hands out a deepCopy of the stored mapping array and storeAndRespond
replaces the whole field with it, so two overlapping association calls each start
from the same snapshot and the later write-back discards the earlier caller's
mapping. A 16-caller test loses 4 of 16 associations before this change, and
leaves survivors behind when every subnet is concurrently disassociated.

The four association operations are now synchronized. updateFirewall and
associateFirewallPolicy are deliberately untouched: they mutate a field on the
live shared node rather than replacing a detached copy, so a concurrent write to
a different field is not lost.

Reported by Greptile on #2580; the finding was initially disputed on the grounds
that the storage backends return live references, which is true but irrelevant —
the detachment is in mappingsOf, not in storage.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-08-27 09:23:52 -04:00
1 parent 9563b7ef08
commit 715bab68e7
17 files changed
+1632 -7

No files matched your search

@@ -0,0 +1,121 @@
package io.github.hectorvent.floci.services.networkfirewall;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The association operations read the stored mapping array, work on a detached
* copy, then replace the whole field on write-back. Without serialising that
* read-modify-write, two overlapping calls each start from the same snapshot and
* the later write silently drops the earlier caller's mapping.
*/
class NetworkFirewallConcurrencyTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final String NAME = "ConcurrentAssociationFirewall";
private static final int CALLERS = 16;
@Test
void concurrentAssociateSubnets_keepsEveryMapping() throws Exception {
ObjectMapper mapper = new ObjectMapper();
NetworkFirewallService service = new NetworkFirewallService(mapper,
new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>());
ObjectNode create = mapper.createObjectNode();
create.put("FirewallName", NAME);
create.put("VpcId", "vpc-0123456789abcdef0");
create.put("SubnetChangeProtection", false);
create.putArray("SubnetMappings");
service.createFirewall(create, REGION, ACCOUNT);
String firewallArn = "arn:aws:network-firewall:" + REGION + ":" + ACCOUNT + ":firewall/" + NAME;
ExecutorService pool = Executors.newFixedThreadPool(CALLERS);
CountDownLatch start = new CountDownLatch(1);
List<Future<?>> submitted = new ArrayList<>();
try {
for (int caller = 0; caller < CALLERS; caller++) {
String subnetId = String.format("subnet-%017d", caller);
submitted.add(pool.submit(() -> {
ObjectNode request = mapper.createObjectNode();
request.put("FirewallArn", firewallArn);
request.putArray("SubnetMappings")
.addObject().put("SubnetId", subnetId);
start.await();
return service.associateSubnets(request);
}));
}
start.countDown();
for (Future<?> future : submitted) {
future.get(30, TimeUnit.SECONDS);
}
} finally {
pool.shutdownNow();
}
ObjectNode described = service.describeFirewall(firewallArn, null, REGION, ACCOUNT);
assertEquals(CALLERS, described.path("Firewall").path("SubnetMappings").size(),
"every successful AssociateSubnets call must survive; a lost update means one "
+ "caller's mapping was overwritten by a concurrent write-back");
}
@Test
void concurrentDisassociateSubnets_removesEveryNamedMapping() throws Exception {
ObjectMapper mapper = new ObjectMapper();
NetworkFirewallService service = new NetworkFirewallService(mapper,
new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>());
ObjectNode create = mapper.createObjectNode();
create.put("FirewallName", NAME);
create.put("VpcId", "vpc-0123456789abcdef0");
create.put("SubnetChangeProtection", false);
var mappings = create.putArray("SubnetMappings");
for (int caller = 0; caller < CALLERS; caller++) {
mappings.addObject().put("SubnetId", String.format("subnet-%017d", caller));
}
service.createFirewall(create, REGION, ACCOUNT);
String firewallArn = "arn:aws:network-firewall:" + REGION + ":" + ACCOUNT + ":firewall/" + NAME;
ExecutorService pool = Executors.newFixedThreadPool(CALLERS);
CountDownLatch start = new CountDownLatch(1);
List<Future<?>> submitted = new ArrayList<>();
try {
for (int caller = 0; caller < CALLERS; caller++) {
String subnetId = String.format("subnet-%017d", caller);
submitted.add(pool.submit(() -> {
ObjectNode request = mapper.createObjectNode();
request.put("FirewallArn", firewallArn);
request.putArray("SubnetIds").add(subnetId);
start.await();
return service.disassociateSubnets(request);
}));
}
start.countDown();
for (Future<?> future : submitted) {
future.get(30, TimeUnit.SECONDS);
}
} finally {
pool.shutdownNow();
}
ObjectNode described = service.describeFirewall(firewallArn, null, REGION, ACCOUNT);
assertTrue(described.path("Firewall").path("SubnetMappings").isEmpty(),
"every subnet was disassociated by some caller, so none may survive a "
+ "concurrent write-back that resurrects a stale snapshot");
}
}
@@ -0,0 +1,711 @@
package io.github.hectorvent.floci.services.networkfirewall;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.aMapWithSize;
import static org.hamcrest.Matchers.anEmptyMap;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.emptyOrNullString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@QuarkusTest
class NetworkFirewallIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String TARGET_PREFIX = "NetworkFirewall_20201112.";
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=723679240095/20260101/us-east-1/network-firewall/aws4_request";
private static final String FIREWALL_ARN =
"arn:aws:network-firewall:us-east-1:723679240095:firewall/AWSAccelerator-us-east-1-nfw";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void createListAndDescribeFirewall_returnsPersistentReadyResource() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "CreateFirewall")
.header("Authorization", AUTH_HEADER)
.body("{\"FirewallName\":\"AWSAccelerator-us-east-1-nfw\","
+ "\"FirewallPolicyArn\":\"arn:aws:network-firewall:us-east-1:723679240095:"
+ "firewall-policy/AWSAccelerator-us-east-1-nfw-policy\","
+ "\"VpcId\":\"vpc-1234567890abcdef0\","
+ "\"SubnetMappings\":[{\"SubnetId\":\"subnet-11111111111111111\"}]}" )
.when()
.post("/")
.then()
.statusCode(200)
.body("Firewall.FirewallArn", equalTo(FIREWALL_ARN));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "ListFirewalls")
.header("Authorization", AUTH_HEADER)
.body("{}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Firewalls.FirewallArn", hasItem(FIREWALL_ARN));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "DescribeFirewall")
.header("Authorization", AUTH_HEADER)
.body("{\"FirewallArn\":\"" + FIREWALL_ARN + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Firewall.FirewallArn", equalTo(FIREWALL_ARN))
.body("FirewallStatus.Status", equalTo("READY"))
.body("FirewallStatus.SyncStates.us-east-1a.Attachment.Status", equalTo("READY"))
.body("FirewallStatus.SyncStates.us-east-1a.Attachment.SubnetId",
equalTo("subnet-11111111111111111"))
.body("FirewallStatus.SyncStates.us-east-1a.Attachment.EndpointId",
matchesPattern("vpce-[0-9a-f]{17}"));
}
@Test
void createFirewall_withoutProtectionFlags_defaultsToProtected() {
// botocore 2020-11-12: CreateFirewall initializes DeleteProtection,
// SubnetChangeProtection and FirewallPolicyChangeProtection to TRUE when the
// caller omits them. AvailabilityZoneChangeProtection is the lone exception,
// documented as defaulting to FALSE.
String name = "DefaultProtectionFirewall";
call("CreateFirewall", "{\"FirewallName\":\"" + name + "\","
+ "\"FirewallPolicyArn\":\"arn:aws:network-firewall:us-east-1:723679240095:"
+ "firewall-policy/" + name + "-policy\","
+ "\"VpcId\":\"vpc-0123456789abcdef0\","
+ "\"SubnetMappings\":[{\"SubnetId\":\"subnet-def00000000000001\"}]}")
.statusCode(200);
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.DeleteProtection", equalTo(true))
.body("Firewall.SubnetChangeProtection", equalTo(true))
.body("Firewall.FirewallPolicyChangeProtection", equalTo(true))
.body("Firewall.AvailabilityZoneChangeProtection", equalTo(false));
}
@Test
void describeFirewall_withoutIdentifier_returnsAwsError() {
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "DescribeFirewall")
.header("Authorization", AUTH_HEADER)
.body("{}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
}
@Test
void createAndListRuleGroup_returnsAwsMetadataShape() {
String arn = "arn:aws:network-firewall:us-east-1:723679240095:"
+ "stateful-rulegroup/vellum-domain-allow-list";
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "CreateRuleGroup")
.header("Authorization", AUTH_HEADER)
.body("{\"RuleGroupName\":\"vellum-domain-allow-list\",\"Type\":\"STATEFUL\","
+ "\"Capacity\":100,\"RuleGroup\":{\"RulesSource\":{\"RulesString\":\"pass ip any any\"}}}")
.when()
.post("/")
.then()
.statusCode(200)
.body("RuleGroupResponse.RuleGroupArn", equalTo(arn));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "ListRuleGroups")
.header("Authorization", AUTH_HEADER)
.body("{\"Type\":\"STATEFUL\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("RuleGroups.Arn", hasItem(arn))
.body("RuleGroups.find { it.Arn == '" + arn + "' }.Name",
equalTo("vellum-domain-allow-list"));
}
@Test
void associateFirewallPolicy_thenDescribeFirewall_showsNewPolicyArn() {
String firewallArn = "arn:aws:network-firewall:us-east-1:723679240095:firewall/AssocTestFirewall";
String initialPolicyArn = "arn:aws:network-firewall:us-east-1:723679240095:"
+ "firewall-policy/AssocTestFirewall-initial-policy";
String newPolicyArn = "arn:aws:network-firewall:us-east-1:723679240095:"
+ "firewall-policy/AssocTestFirewall-new-policy";
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "CreateFirewall")
.header("Authorization", AUTH_HEADER)
.body("{\"FirewallName\":\"AssocTestFirewall\","
+ "\"FirewallPolicyArn\":\"" + initialPolicyArn + "\","
+ "\"VpcId\":\"vpc-assoctest0000000000\","
+ "\"FirewallPolicyChangeProtection\":false,"
+ "\"SubnetMappings\":[{\"SubnetId\":\"subnet-22222222222222222\"}]}")
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "CreateFirewallPolicy")
.header("Authorization", AUTH_HEADER)
.body("{\"FirewallPolicyName\":\"AssocTestFirewall-new-policy\","
+ "\"FirewallPolicy\":{\"StatelessDefaultActions\":[\"aws:pass\"],"
+ "\"StatelessFragmentDefaultActions\":[\"aws:pass\"]}}")
.when()
.post("/")
.then()
.statusCode(200)
.body("FirewallPolicyResponse.FirewallPolicyArn", equalTo(newPolicyArn));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "AssociateFirewallPolicy")
.header("Authorization", AUTH_HEADER)
.body("{\"FirewallArn\":\"" + firewallArn + "\","
+ "\"FirewallPolicyArn\":\"" + newPolicyArn + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("FirewallPolicyArn", equalTo(newPolicyArn));
given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + "DescribeFirewall")
.header("Authorization", AUTH_HEADER)
.body("{\"FirewallArn\":\"" + firewallArn + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("Firewall.FirewallPolicyArn", equalTo(newPolicyArn));
}
@Test
void deleteFirewall_withDeleteProtection_isRejectedAndLeavesTheFirewall() {
String name = "DeleteProtectedFirewall";
createFirewall(name, "\"DeleteProtection\":true,", "subnet-33333333333333333");
call("DeleteFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(400)
.body("__type", equalTo("InvalidOperationException"));
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.FirewallArn", equalTo(firewallArn(name)));
}
@Test
void associateSubnets_addsToTheExistingMappingsWithoutDuplicating() {
String name = "AssociateSubnetsFirewall";
createFirewall(name, "", "subnet-44444444444444444");
call("AssociateSubnets", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"SubnetMappings\":[{\"SubnetId\":\"subnet-55555555555555555\"},"
+ "{\"SubnetId\":\"subnet-44444444444444444\"}]}")
.statusCode(200)
.body("SubnetMappings.SubnetId", hasItems(
"subnet-44444444444444444", "subnet-55555555555555555"))
.body("SubnetMappings", hasSize(2));
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.SubnetMappings.SubnetId", hasItems(
"subnet-44444444444444444", "subnet-55555555555555555"))
.body("Firewall.SubnetMappings", hasSize(2));
}
@Test
void associateSubnets_partiallyInvalidRequest_leavesStoredMappingsUntouched() {
// A valid mapping followed by one missing its required SubnetId must reject
// the WHOLE request without mutating stored state: validate-then-commit,
// never commit-then-validate.
String name = "PartialInvalidAssociateFirewall";
createFirewall(name, "", "subnet-11111111111111111");
call("AssociateSubnets", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"SubnetMappings\":[{\"SubnetId\":\"subnet-22222222222222222\"},"
+ "{\"IPAddressType\":\"IPV4\"}]}")
.statusCode(400);
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.SubnetMappings.SubnetId", not(hasItem("subnet-22222222222222222")))
.body("Firewall.SubnetMappings", hasSize(1));
}
@Test
void associateSubnets_withSubnetChangeProtection_isRejected() {
String name = "SubnetProtectedAssociateFirewall";
createFirewall(name, "\"SubnetChangeProtection\":true,", "subnet-66666666666666666");
call("AssociateSubnets", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"SubnetMappings\":[{\"SubnetId\":\"subnet-77777777777777777\"}]}")
.statusCode(400)
.body("__type", equalTo("InvalidOperationException"));
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.SubnetMappings.SubnetId", not(hasItem("subnet-77777777777777777")));
}
@Test
void updateFirewallDescription_cannotSmuggleProtectedMappingsPastChangeProtection() {
// The UpdateFirewall* ops each model a specific mutable field. Extra fields in the
// raw request (SubnetMappings here) must not be persisted — otherwise a plain
// UpdateFirewallDescription bypasses SubnetChangeProtection entirely.
String name = "SmuggledMappingsFirewall";
createFirewall(name, "\"SubnetChangeProtection\":true,", "subnet-88888888888888888");
call("UpdateFirewallDescription", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"Description\":\"updated\","
+ "\"SubnetMappings\":[{\"SubnetId\":\"subnet-99999999999999999\"}]}")
.statusCode(200);
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.Description", equalTo("updated"))
.body("Firewall.SubnetMappings.SubnetId", not(hasItem("subnet-99999999999999999")))
.body("Firewall.SubnetMappings", hasSize(1));
}
@Test
void updateFirewallDescription_cannotSmuggleAnotherOperationsProtectionField() {
// Each UpdateFirewall* operation models exactly one mutable field (botocore
// 2020-11-12). A raw UpdateFirewallDescription request that also carries
// DeleteProtection (only modeled on UpdateFirewallDeleteProtection) must not
// persist it — otherwise DeleteProtection can be flipped without ever calling
// UpdateFirewallDeleteProtection, and DescribeFirewall reports a change that op
// never made.
String name = "SmuggledDeleteProtectionFirewall";
createFirewall(name, "", "subnet-11122233344455566");
call("UpdateFirewallDescription", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"Description\":\"updated\","
+ "\"DeleteProtection\":true}")
.statusCode(200);
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.Description", equalTo("updated"))
.body("Firewall.DeleteProtection", equalTo(false));
}
@Test
void updateFirewallDeleteProtection_returnsTheFlatModelledShape() {
// botocore 2020-11-12: UpdateFirewallDeleteProtectionResponse is
// {FirewallArn, FirewallName, DeleteProtection, UpdateToken} at the top
// level -- NOT nested under Firewall/FirewallStatus. Every UpdateFirewall*
// op shares this flat shape with its own field substituted for
// DeleteProtection, so a typed SDK client can read it back.
String name = "UpdateShapeFirewall";
createFirewall(name, "", "subnet-ee000000000000001");
call("UpdateFirewallDeleteProtection", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"DeleteProtection\":true}")
.statusCode(200)
.body("FirewallArn", equalTo(firewallArn(name)))
.body("FirewallName", equalTo(name))
.body("DeleteProtection", equalTo(true))
.body("UpdateToken", not(nullValue()))
.body("Firewall", nullValue())
.body("FirewallStatus", nullValue());
}
@Test
void disassociateSubnets_removesOnlyTheNamedSubnets() {
String name = "DisassociateSubnetsFirewall";
createFirewall(name, "", "subnet-88888888888888888", "subnet-99999999999999999");
call("DisassociateSubnets", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"SubnetIds\":[\"subnet-88888888888888888\"]}")
.statusCode(200)
.body("SubnetMappings.SubnetId", contains("subnet-99999999999999999"));
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.SubnetMappings.SubnetId", contains("subnet-99999999999999999"));
}
@Test
void disassociateSubnets_removingTheLastSubnet_leavesNoSyncStates() {
String name = "DrainedSubnetsFirewall";
createFirewall(name, "", "subnet-aaaaaaaaaaaaaaaaa");
call("DisassociateSubnets", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"SubnetIds\":[\"subnet-aaaaaaaaaaaaaaaaa\"]}")
.statusCode(200)
.body("SubnetMappings", empty());
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.SubnetMappings", empty())
.body("FirewallStatus.SyncStates", anEmptyMap());
}
@Test
void disassociateSubnets_withSubnetChangeProtection_isRejected() {
String name = "SubnetProtectedDisassociateFirewall";
createFirewall(name, "\"SubnetChangeProtection\":true,", "subnet-bbbbbbbbbbbbbbbbb");
call("DisassociateSubnets", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"SubnetIds\":[\"subnet-bbbbbbbbbbbbbbbbb\"]}")
.statusCode(400)
.body("__type", equalTo("InvalidOperationException"));
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.SubnetMappings.SubnetId", hasItem("subnet-bbbbbbbbbbbbbbbbb"));
}
@Test
void associateAvailabilityZones_addsToTheExistingMappingsWithoutDuplicating() {
String name = "AssociateZonesFirewall";
createFirewall(name, "", "subnet-ccccccccccccccccc");
call("AssociateAvailabilityZones", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"AvailabilityZoneMappings\":[{\"AvailabilityZone\":\"us-east-1a\"}]}")
.statusCode(200)
.body("AvailabilityZoneMappings.AvailabilityZone", contains("us-east-1a"));
call("AssociateAvailabilityZones", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"AvailabilityZoneMappings\":[{\"AvailabilityZone\":\"us-east-1a\"},"
+ "{\"AvailabilityZone\":\"us-east-1b\"}]}")
.statusCode(200)
.body("AvailabilityZoneMappings.AvailabilityZone", contains("us-east-1a", "us-east-1b"));
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.AvailabilityZoneMappings.AvailabilityZone",
contains("us-east-1a", "us-east-1b"));
}
@Test
void associateAvailabilityZones_withAvailabilityZoneChangeProtection_isRejected() {
String name = "ZoneProtectedAssociateFirewall";
createFirewall(name, "\"AvailabilityZoneChangeProtection\":true,", "subnet-ddddddddddddddddd");
call("AssociateAvailabilityZones", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"AvailabilityZoneMappings\":[{\"AvailabilityZone\":\"us-east-1c\"}]}")
.statusCode(400)
.body("__type", equalTo("InvalidOperationException"));
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.AvailabilityZoneMappings", nullValue());
}
@Test
void disassociateAvailabilityZones_removesOnlyTheNamedZones() {
String name = "DisassociateZonesFirewall";
createFirewall(name, "", "subnet-eeeeeeeeeeeeeeeee");
call("AssociateAvailabilityZones", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"AvailabilityZoneMappings\":[{\"AvailabilityZone\":\"us-east-1a\"},"
+ "{\"AvailabilityZone\":\"us-east-1b\"}]}")
.statusCode(200);
call("DisassociateAvailabilityZones", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"AvailabilityZoneMappings\":[{\"AvailabilityZone\":\"us-east-1a\"}]}")
.statusCode(200)
.body("AvailabilityZoneMappings.AvailabilityZone", contains("us-east-1b"));
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.AvailabilityZoneMappings.AvailabilityZone", contains("us-east-1b"));
}
@Test
void disassociateAvailabilityZones_withAvailabilityZoneChangeProtection_isRejected() {
String name = "ZoneProtectedDisassociateFirewall";
createFirewall(name, "\"AvailabilityZoneChangeProtection\":true,", "subnet-fffffffffffffffff");
call("DisassociateAvailabilityZones", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"AvailabilityZoneMappings\":[{\"AvailabilityZone\":\"us-east-1a\"}]}")
.statusCode(400)
.body("__type", equalTo("InvalidOperationException"));
}
@Test
void disassociateSubnets_withoutSubnetIds_leavesTheFirewallUntouched() {
String name = "FallbackSubnetsFirewall";
call("CreateFirewall", "{\"FirewallName\":\"" + name + "\","
+ "\"FirewallPolicyArn\":\"arn:aws:network-firewall:us-east-1:723679240095:"
+ "firewall-policy/" + name + "-policy\","
+ "\"VpcId\":\"vpc-0123456789abcdef0\","
+ "\"SubnetChangeProtection\":false}")
.statusCode(200);
call("DisassociateSubnets", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.SubnetMappings", nullValue())
.body("FirewallStatus.SyncStates", aMapWithSize(6));
}
@Test
void createRuleGroup_whenAlreadyPresent_namesTheResourceKindInTheError() {
String body = "{\"RuleGroupName\":\"duplicate-rule-group\",\"Type\":\"STATEFUL\","
+ "\"Capacity\":100,\"RuleGroup\":{\"RulesSource\":{\"RulesString\":\"pass ip any any\"}}}";
call("CreateRuleGroup", body).statusCode(200);
call("CreateRuleGroup", body)
.statusCode(400)
.body("__type", equalTo("ResourceAlreadyExistsException"))
.body("message", equalTo("RuleGroup already exists: duplicate-rule-group"));
}
@Test
void deleteFirewall_returnsTheDeletedFirewallAndItsStatus() {
String name = "DeletableFirewall";
createFirewall(name, "", "subnet-11111111111111112");
call("DeleteFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.FirewallArn", equalTo(firewallArn(name)))
.body("Firewall.FirewallName", equalTo(name))
.body("FirewallStatus.Status", equalTo("READY"));
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
void describeRuleGroup_whenMissing_namesTheResourceKindInTheError() {
call("DescribeRuleGroup", "{\"RuleGroupName\":\"no-such-rule-group\"}")
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"))
.body("message", equalTo("RuleGroup not found: no-such-rule-group"));
}
@Test
void createRuleGroup_withUnmodelledType_isRejectedAndStoresNothing() {
call("CreateRuleGroup", "{\"RuleGroupName\":\"bogus-type-rule-group\",\"Type\":\"FOO\","
+ "\"Capacity\":100,\"RuleGroup\":{\"RulesSource\":{\"RulesString\":\"pass ip any any\"}}}")
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
call("DescribeRuleGroup", "{\"RuleGroupName\":\"bogus-type-rule-group\"}")
.statusCode(400)
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
void updateRuleGroup_withUnmodelledType_isRejected() {
call("UpdateRuleGroup", "{\"RuleGroupName\":\"bogus-update-rule-group\",\"Type\":\"stateful\","
+ "\"Capacity\":100,\"RuleGroup\":{\"RulesSource\":{\"RulesString\":\"pass ip any any\"}}}")
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
}
@Test
void createRuleGroup_withStatefulDomainType_usesTheStatefulArnPrefix() {
call("CreateRuleGroup", "{\"RuleGroupName\":\"domain-list-rule-group\",\"Type\":\"STATEFUL_DOMAIN\","
+ "\"Capacity\":100,\"RuleGroup\":{\"RulesSource\":{\"RulesString\":\"pass ip any any\"}}}")
.statusCode(200)
.body("RuleGroupResponse.RuleGroupArn", equalTo(
"arn:aws:network-firewall:us-east-1:723679240095:"
+ "stateful-rulegroup/domain-list-rule-group"));
}
@Test
void updateLoggingConfiguration_withUnmodelledLogTypeOrDestinationType_isRejected() {
String name = "LoggingEnumFirewall";
createFirewall(name, "", "subnet-11111111111111113");
call("UpdateLoggingConfiguration", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"LoggingConfiguration\":{\"LogDestinationConfigs\":[{\"LogType\":\"AUDIT\","
+ "\"LogDestinationType\":\"S3\",\"LogDestination\":{\"bucketName\":\"b\"}}]}}")
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
call("UpdateLoggingConfiguration", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"LoggingConfiguration\":{\"LogDestinationConfigs\":[{\"LogType\":\"ALERT\","
+ "\"LogDestinationType\":\"s3\",\"LogDestination\":{\"bucketName\":\"b\"}}]}}")
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"));
call("DescribeLoggingConfiguration", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("LoggingConfiguration.LogDestinationConfigs", empty());
}
@Test
void updateLoggingConfiguration_withModelledEnumValues_isStored() {
String name = "LoggingValidFirewall";
createFirewall(name, "", "subnet-11111111111111114");
call("UpdateLoggingConfiguration", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"LoggingConfiguration\":{\"LogDestinationConfigs\":[{\"LogType\":\"FLOW\","
+ "\"LogDestinationType\":\"CloudWatchLogs\","
+ "\"LogDestination\":{\"logGroup\":\"/aws/nfw\"}}]}}")
.statusCode(200)
.body("LoggingConfiguration.LogDestinationConfigs[0].LogDestinationType",
equalTo("CloudWatchLogs"));
}
@Test
void updateFirewallDescription_whenNeverSet_omitsTheFieldFromTheResponse() {
String name = "NoDescriptionFirewall";
createFirewall(name, "", "subnet-11111111111111115");
call("UpdateFirewallDescription", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("FirewallArn", equalTo(firewallArn(name)))
.body("FirewallName", equalTo(name))
.body("UpdateToken", not(emptyOrNullString()))
.body("$", not(hasKey("Description")));
}
@Test
void updateFirewallAnalysisSettings_whenNeverSet_omitsTheFieldFromTheResponse() {
String name = "NoAnalysisSettingsFirewall";
createFirewall(name, "", "subnet-11111111111111116");
call("UpdateFirewallAnalysisSettings", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("FirewallArn", equalTo(firewallArn(name)))
.body("FirewallName", equalTo(name))
.body("UpdateToken", not(emptyOrNullString()))
.body("$", not(hasKey("EnabledAnalysisTypes")));
}
@Test
void updateFirewallDescription_whenProvided_storesAndEchoesTheValue() {
String name = "DescribedFirewall";
createFirewall(name, "", "subnet-11111111111111117");
call("UpdateFirewallDescription", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"Description\":\"managed by the accelerator\"}")
.statusCode(200)
.body("Description", equalTo("managed by the accelerator"));
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.Description", equalTo("managed by the accelerator"));
}
@Test
void associateFirewallPolicy_withPolicyChangeProtection_isRejected() {
String name = "PolicyProtectedFirewall";
String initialPolicyArn = "arn:aws:network-firewall:us-east-1:723679240095:"
+ "firewall-policy/" + name + "-policy";
createFirewall(name, "\"FirewallPolicyChangeProtection\":true,", "subnet-11111111111111118");
call("CreateFirewallPolicy", "{\"FirewallPolicyName\":\"" + name + "-replacement\","
+ "\"FirewallPolicy\":{\"StatelessDefaultActions\":[\"aws:pass\"],"
+ "\"StatelessFragmentDefaultActions\":[\"aws:pass\"]}}")
.statusCode(200);
call("AssociateFirewallPolicy", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"FirewallPolicyArn\":\"arn:aws:network-firewall:us-east-1:723679240095:"
+ "firewall-policy/" + name + "-replacement\"}")
.statusCode(400)
.body("__type", equalTo("InvalidOperationException"));
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.FirewallPolicyArn", equalTo(initialPolicyArn));
}
@Test
void updateFirewallDescription_omittingDescription_clearsTheStoredValue() {
String name = "ClearDescriptionFirewall";
createFirewall(name, "", "subnet-11111111111111119");
call("UpdateFirewallDescription", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"Description\":\"initial description\"}")
.statusCode(200)
.body("Description", equalTo("initial description"));
call("UpdateFirewallDescription", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("$", not(hasKey("Description")));
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.Description", nullValue());
}
@Test
void updateFirewallAnalysisSettings_omittingTypes_preservesTheStoredValue() {
// Deliberate asymmetry with Description: botocore documents omission as removal for
// UpdateFirewallDescription only. EnabledAnalysisTypes carries no such statement, so
// the stored value is preserved rather than inferring AWS behaviour the model omits.
String name = "PreserveAnalysisFirewall";
createFirewall(name, "", "subnet-1111111111111111a");
call("UpdateFirewallAnalysisSettings", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"EnabledAnalysisTypes\":[\"TLS_SNI\"]}")
.statusCode(200)
.body("EnabledAnalysisTypes", contains("TLS_SNI"));
call("UpdateFirewallAnalysisSettings", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("EnabledAnalysisTypes", contains("TLS_SNI"));
}
private static String firewallArn(String name) {
return "arn:aws:network-firewall:us-east-1:723679240095:firewall/" + name;
}
private static ValidatableResponse call(String action, String body) {
return given()
.contentType(CONTENT_TYPE)
.header("X-Amz-Target", TARGET_PREFIX + action)
.header("Authorization", AUTH_HEADER)
.body(body)
.when()
.post("/")
.then();
}
private static void createFirewall(String name, String extraFields, String... subnetIds) {
StringBuilder mappings = new StringBuilder();
for (String subnetId : subnetIds) {
if (!mappings.isEmpty()) {
mappings.append(',');
}
mappings.append("{\"SubnetId\":\"").append(subnetId).append("\"}");
}
call("CreateFirewall", "{\"FirewallName\":\"" + name + "\","
+ "\"FirewallPolicyArn\":\"arn:aws:network-firewall:us-east-1:723679240095:"
+ "firewall-policy/" + name + "-policy\","
+ "\"VpcId\":\"vpc-0123456789abcdef0\","
+ "\"DeleteProtection\":false,\"SubnetChangeProtection\":false,"
+ "\"FirewallPolicyChangeProtection\":false,"
+ extraFields
+ "\"SubnetMappings\":[" + mappings + "]}")
.statusCode(200);
}
}