fix(networkfirewall): model CreateFirewall* collisions and enforce UpdateToken (#3198)

Name collisions on CreateFirewall/CreateRuleGroup/CreateFirewallPolicy now
raise the modeled InvalidRequestException instead of an unmodeled
ResourceAlreadyExistsException. Every UpdateFirewall*/Associate*/
Disassociate* firewall mutation now checks a caller-supplied UpdateToken
against the firewall's current token and rejects a mismatch with
InvalidTokenException, matching botocore 2020-11-12.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* Fix #2600
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-09-07 21:06:30 -04:00
1 parent d049875aaf
commit 215a80208c
3 files changed
+343 -13

No files matched your search

@@ -126,23 +126,27 @@ public class NetworkFirewallService {
firewall.put("DeleteProtection", request.path("DeleteProtection").asBoolean(true));
firewall.put("AvailabilityZoneChangeProtection",
request.path("AvailabilityZoneChangeProtection").asBoolean(false));
rotateToken(firewall);
firewalls.put(firewallArn, firewall);
return firewallResponse(firewall, region);
}
public ObjectNode describeFirewall(String firewallArn, String firewallName, String region, String accountId) {
public synchronized ObjectNode describeFirewall(String firewallArn, String firewallName, String region,
String accountId) {
requireIdentifier(firewallArn, firewallName);
ObjectNode firewall = find(firewalls, firewallArn, firewallName, "FirewallArn", "FirewallName");
if (firewall == null) {
throw notFound("Firewall", firewallArn == null ? firewallName : firewallArn);
}
return firewallResponse(firewall, region);
ObjectNode response = firewallResponse(firewall, region);
response.put("UpdateToken", ensureToken(firewall));
return response;
}
/**
* Each UpdateFirewall* operation models exactly one mutable field (botocore
* 2020-11-12). Anything else in the raw request — including another operation's
* field, or unmodeled members like SubnetMappings — must not be persisted, matching
* 2020-11-12). Anything else in the raw request, including another operation's
* field, or unmodeled members like SubnetMappings, must not be persisted, matching
* AWS ignoring unmodeled request members and scoping each op to its own field.
*/
private static final Map<String, String> UPDATE_ACTION_FIELDS = Map.of(
@@ -161,10 +165,19 @@ public class NetworkFirewallService {
*/
private static final Set<String> CLEARED_WHEN_OMITTED = Set.of("UpdateFirewallDescription");
public ObjectNode updateFirewall(String action, JsonNode request, String region, String accountId) {
/**
* Synchronized so that validating the caller's token against the firewall's current
* one and rotating to a new token happen as a single atomic step. Without a common
* lock, two overlapping calls can each read and match the same current token before
* either commits its rotation, letting both changes apply when the second one should
* have been rejected as stale. See {@link #associateSubnets} for the sibling case
* this reuses the same lock for.
*/
public synchronized ObjectNode updateFirewall(String action, JsonNode request, String region, String accountId) {
String arn = textOrNull(request, "FirewallArn");
String name = textOrNull(request, "FirewallName");
ObjectNode existing = require(firewalls, arn, name, "Firewall", "FirewallArn", "FirewallName");
requireCurrentToken(existing, request);
String field = UPDATE_ACTION_FIELDS.get(action);
JsonNode value = request.get(field);
if (value != null) {
@@ -172,6 +185,7 @@ public class NetworkFirewallService {
} else if (CLEARED_WHEN_OMITTED.contains(action)) {
existing.remove(field);
}
String newToken = rotateToken(existing);
firewalls.put(existing.path("FirewallArn").asText(), existing);
// Each UpdateFirewall* response is a flat {FirewallArn, FirewallName,
@@ -189,7 +203,7 @@ public class NetworkFirewallService {
if (current != null) {
response.set(field, current.deepCopy());
}
response.put("UpdateToken", UUID.randomUUID().toString());
response.put("UpdateToken", newToken);
return response;
}
@@ -261,6 +275,7 @@ public class NetworkFirewallService {
private ObjectNode firewallForChange(JsonNode request, String protectionField, String protectedResource) {
ObjectNode firewall = require(firewalls, textOrNull(request, "FirewallArn"),
textOrNull(request, "FirewallName"), "Firewall", "FirewallArn", "FirewallName");
requireCurrentToken(firewall, request);
if (firewall.path(protectionField).asBoolean(false)) {
throw new AwsException("InvalidOperationException",
"Firewall has " + protectedResource + " change protection enabled: "
@@ -269,6 +284,57 @@ public class NetworkFirewallService {
return firewall;
}
/**
* botocore 2020-11-12 marks UpdateToken optional on every UpdateFirewall, Associate and
* Disassociate request: omitting it makes an unconditional change, while supplying it
* asks Network Firewall to check it against the firewall's current token and fail with
* InvalidTokenException on a mismatch. See the UpdateFirewallDescription documentation
* for this exact contract.
*/
private void requireCurrentToken(ObjectNode firewall, JsonNode request) {
String providedToken = textOrNull(request, "UpdateToken");
if (providedToken == null) {
return;
}
String currentToken = firewall.path("UpdateToken").asText(null);
if (!providedToken.equals(currentToken)) {
throw new AwsException("InvalidTokenException",
"The token you provided is stale or isn't valid for the operation.", 400);
}
}
/**
* Generates a fresh UpdateToken and stores it directly on the firewall so the next
* mutating call can be checked against it. The token is never a member of the modeled
* Firewall shape, so {@link #firewallResponse} strips it before nesting that object
* under a response's {@code Firewall} field.
*/
private String rotateToken(ObjectNode firewall) {
String token = UUID.randomUUID().toString();
firewall.put("UpdateToken", token);
return token;
}
/**
* A firewall persisted before UpdateToken support was added has no such field, so
* {@code UpdateToken}'s default read is {@code null} here, matching the default
* {@link #requireCurrentToken} compares against. Backfilling a real token on first
* describe, rather than exposing an empty string, keeps the describe-then-submit
* flow working for those firewalls the same way it does for ones created after
* this change. Like every other {@link #rotateToken} caller, the backfilled token
* is written through {@code firewalls.put} so a persistent or hybrid storage
* backend records it; otherwise the token handed to the caller could be lost on
* restart and a later conditional call carrying it would be rejected as stale.
*/
private String ensureToken(ObjectNode firewall) {
String token = firewall.path("UpdateToken").asText(null);
if (token == null || token.isEmpty()) {
token = rotateToken(firewall);
firewalls.put(firewall.path("FirewallArn").asText(), firewall);
}
return token;
}
/**
* Returns a DETACHED copy of the firewall's mapping array so per-element
* validation can reject mid-loop without mutating stored state; the copy is
@@ -299,12 +365,13 @@ public class NetworkFirewallService {
private ObjectNode storeAndRespond(ObjectNode firewall, String field, ArrayNode mappings) {
String firewallArn = firewall.path("FirewallArn").asText();
firewall.set(field, mappings);
String newToken = rotateToken(firewall);
firewalls.put(firewallArn, firewall);
ObjectNode response = objectMapper.createObjectNode();
response.put("FirewallArn", firewallArn);
response.put("FirewallName", firewall.path("FirewallName").asText());
response.set(field, mappings.deepCopy());
response.put("UpdateToken", UUID.randomUUID().toString());
response.put("UpdateToken", newToken);
return response;
}
@@ -435,9 +502,16 @@ public class NetworkFirewallService {
return objectMapper.createObjectNode();
}
/**
* UpdateToken is stored directly on the firewall so {@link #requireCurrentToken} can
* read it back, but botocore's Firewall shape has no such member, so the nested
* {@code Firewall} view built here must have it stripped.
*/
private ObjectNode firewallResponse(ObjectNode firewall, String region) {
ObjectNode response = objectMapper.createObjectNode();
response.set("Firewall", firewall.deepCopy());
ObjectNode firewallView = firewall.deepCopy();
firewallView.remove("UpdateToken");
response.set("Firewall", firewallView);
ObjectNode status = response.putObject("FirewallStatus");
status.put("ConfigurationSyncStateSummary", "IN_SYNC");
status.put("Status", "READY");
@@ -469,9 +543,15 @@ public class NetworkFirewallService {
attachment.put("SubnetId", subnetId);
}
/**
* botocore 2020-11-12 models no {@code *AlreadyExist*} shape for CreateFirewall,
* CreateRuleGroup or CreateFirewallPolicy: their only modeled client-fault error for
* a name collision is InvalidRequestException, so that is what a typed SDK client can
* actually deserialize here.
*/
private void ensureUnique(StorageBackend<String, ObjectNode> store, String arn, String name, String kind) {
if (store.get(arn).isPresent() || find(store, null, name, "ResourceArn", "ResourceName") != null) {
throw new AwsException("ResourceAlreadyExistsException", kind + " already exists: " + name, 400);
throw new AwsException("InvalidRequestException", kind + " already exists: " + name, 400);
}
}
@@ -621,18 +701,21 @@ public class NetworkFirewallService {
}
}
public ObjectNode associateFirewallPolicy(JsonNode request, String region, String accountId) {
/** @see #associateSubnets for why this is synchronized. */
public synchronized ObjectNode associateFirewallPolicy(JsonNode request, String region, String accountId) {
String policyArn = requiredText(request, "FirewallPolicyArn");
ObjectNode firewall =
firewallForChange(request, "FirewallPolicyChangeProtection", "firewall policy");
require(firewallPolicies, policyArn, null, "FirewallPolicy", "ResourceArn", "ResourceName");
String firewallArn = firewall.path("FirewallArn").asText();
firewall.put("FirewallPolicyArn", policyArn);
String newToken = rotateToken(firewall);
firewalls.put(firewallArn, firewall);
ObjectNode response = objectMapper.createObjectNode();
response.put("FirewallArn", firewallArn);
response.put("FirewallName", firewall.path("FirewallName").asText());
response.put("FirewallPolicyArn", policyArn);
response.put("UpdateToken", newToken);
return response;
}
}
@@ -2,16 +2,19 @@ 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.common.AwsException;
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.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -118,4 +121,101 @@ class NetworkFirewallConcurrencyTest {
"every subnet was disassociated by some caller, so none may survive a "
+ "concurrent write-back that resurrects a stale snapshot");
}
/**
* Two concurrent UpdateFirewall* calls carrying the same current token must not both
* succeed: without a common lock around validate-then-rotate, both can read and match
* the same token before either commits its rotation.
*/
@Test
void concurrentUpdateFirewall_onlySingleCallerWithStaleTokenSucceeds() 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");
ObjectNode created = service.createFirewall(create, REGION, ACCOUNT);
String firewallArn = created.path("Firewall").path("FirewallArn").asText();
String currentToken =
service.describeFirewall(firewallArn, null, REGION, ACCOUNT).path("UpdateToken").asText();
ExecutorService pool = Executors.newFixedThreadPool(CALLERS);
CountDownLatch start = new CountDownLatch(1);
List<Future<ObjectNode>> submitted = new ArrayList<>();
try {
for (int caller = 0; caller < CALLERS; caller++) {
int callerIndex = caller;
submitted.add(pool.submit(() -> {
ObjectNode request = mapper.createObjectNode();
request.put("FirewallArn", firewallArn);
request.put("UpdateToken", currentToken);
request.put("Description", "description-" + callerIndex);
start.await();
return service.updateFirewall("UpdateFirewallDescription", request, REGION, ACCOUNT);
}));
}
start.countDown();
AtomicInteger succeeded = new AtomicInteger();
AtomicInteger rejected = new AtomicInteger();
for (Future<ObjectNode> future : submitted) {
try {
future.get(30, TimeUnit.SECONDS);
succeeded.incrementAndGet();
} catch (ExecutionException e) {
if (e.getCause() instanceof AwsException awsException
&& "InvalidTokenException".equals(awsException.getErrorCode())) {
rejected.incrementAndGet();
} else {
throw e;
}
}
}
assertEquals(1, succeeded.get(),
"exactly one caller may validate and rotate the shared current token; a "
+ "nonatomic check-and-rotate lets more than one pass validation");
assertEquals(CALLERS - 1, rejected.get());
} finally {
pool.shutdownNow();
}
}
/**
* A firewall persisted before UpdateToken support existed has no token field.
* DescribeFirewall must backfill a real token rather than reporting the empty
* string {@code JsonNode.asText()} defaults to, since a caller submitting that
* empty string back would otherwise always be rejected by requireCurrentToken's
* null-based default.
*/
@Test
void describeFirewall_backfillsATokenForAFirewallWithoutOne() {
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");
ObjectNode created = service.createFirewall(create, REGION, ACCOUNT);
String firewallArn = created.path("Firewall").path("FirewallArn").asText();
ObjectNode described = service.describeFirewall(firewallArn, null, REGION, ACCOUNT);
String token = described.path("UpdateToken").asText();
assertTrue(token != null && !token.isEmpty(),
"DescribeFirewall must never report an empty UpdateToken");
ObjectNode update = mapper.createObjectNode();
update.put("FirewallArn", firewallArn);
update.put("UpdateToken", token);
update.put("Description", "backfilled-token-round-trip");
ObjectNode updateResponse =
service.updateFirewall("UpdateFirewallDescription", update, REGION, ACCOUNT);
assertEquals("backfilled-token-round-trip", updateResponse.path("Description").asText());
}
}
@@ -278,7 +278,7 @@ class NetworkFirewallIntegrationTest {
@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
// raw request (SubnetMappings here) must not be persisted, otherwise a plain
// UpdateFirewallDescription bypasses SubnetChangeProtection entirely.
String name = "SmuggledMappingsFirewall";
createFirewall(name, "\"SubnetChangeProtection\":true,", "subnet-88888888888888888");
@@ -300,7 +300,7 @@ class NetworkFirewallIntegrationTest {
// 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
// persist it, otherwise DeleteProtection can be flipped without ever calling
// UpdateFirewallDeleteProtection, and DescribeFirewall reports a change that op
// never made.
String name = "SmuggledDeleteProtectionFirewall";
@@ -472,6 +472,21 @@ class NetworkFirewallIntegrationTest {
.body("FirewallStatus.SyncStates", aMapWithSize(6));
}
@Test
void createFirewall_whenAlreadyPresent_isRejectedAsAnInvalidRequest() {
String name = "DuplicateNameFirewall";
createFirewall(name, "", "subnet-11111111111111121");
call("CreateFirewall", "{\"FirewallName\":\"" + name + "\","
+ "\"FirewallPolicyArn\":\"arn:aws:network-firewall:us-east-1:723679240095:"
+ "firewall-policy/" + name + "-other-policy\","
+ "\"VpcId\":\"vpc-0123456789abcdef1\","
+ "\"SubnetMappings\":[{\"SubnetId\":\"subnet-11111111111111122\"}]}")
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", equalTo("Firewall already exists: " + name));
}
@Test
void createRuleGroup_whenAlreadyPresent_namesTheResourceKindInTheError() {
String body = "{\"RuleGroupName\":\"duplicate-rule-group\",\"Type\":\"STATEFUL\","
@@ -480,7 +495,7 @@ class NetworkFirewallIntegrationTest {
call("CreateRuleGroup", body)
.statusCode(400)
.body("__type", equalTo("ResourceAlreadyExistsException"))
.body("__type", equalTo("InvalidRequestException"))
.body("message", equalTo("RuleGroup already exists: duplicate-rule-group"));
}
@@ -675,6 +690,138 @@ class NetworkFirewallIntegrationTest {
.body("EnabledAnalysisTypes", contains("TLS_SNI"));
}
@Test
void describeFirewall_exposesTheCurrentUpdateTokenAtTheTopLevel() {
String name = "TokenExposedFirewall";
createFirewall(name, "", "subnet-11111111111111123");
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("UpdateToken", not(emptyOrNullString()))
.body("Firewall", not(hasKey("UpdateToken")));
}
@Test
void updateFirewallDescription_withTheCurrentToken_succeedsAndRotatesTheToken() {
String name = "CurrentTokenFirewall";
createFirewall(name, "", "subnet-11111111111111124");
String currentToken = currentUpdateToken(name);
String newToken = call("UpdateFirewallDescription", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"UpdateToken\":\"" + currentToken + "\",\"Description\":\"checked in\"}")
.statusCode(200)
.body("Description", equalTo("checked in"))
.body("UpdateToken", not(equalTo(currentToken)))
.extract().path("UpdateToken");
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("UpdateToken", equalTo(newToken));
}
@Test
void updateFirewallDescription_withAStaleToken_isRejectedAndLeavesTheFirewallUntouched() {
String name = "StaleTokenFirewall";
createFirewall(name, "", "subnet-11111111111111125");
call("UpdateFirewallDescription", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"UpdateToken\":\"00000000-0000-0000-0000-000000000000\","
+ "\"Description\":\"should not stick\"}")
.statusCode(400)
.body("__type", equalTo("InvalidTokenException"));
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.Description", nullValue());
}
@Test
void updateFirewallDescription_withoutAToken_appliesUnconditionally() {
String name = "UnconditionalUpdateFirewall";
createFirewall(name, "", "subnet-11111111111111126");
call("UpdateFirewallDescription", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"Description\":\"no token needed\"}")
.statusCode(200)
.body("Description", equalTo("no token needed"));
}
@Test
void associateSubnets_withAStaleToken_isRejectedAndLeavesTheMappingsUntouched() {
String name = "StaleTokenAssociateFirewall";
createFirewall(name, "", "subnet-11111111111111127");
call("AssociateSubnets", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"UpdateToken\":\"00000000-0000-0000-0000-000000000000\","
+ "\"SubnetMappings\":[{\"SubnetId\":\"subnet-11111111111111128\"}]}")
.statusCode(400)
.body("__type", equalTo("InvalidTokenException"));
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.SubnetMappings", hasSize(1));
}
@Test
void associateSubnets_withTheCurrentToken_succeedsAndReturnsANewToken() {
String name = "CurrentTokenAssociateFirewall";
createFirewall(name, "", "subnet-11111111111111129");
String currentToken = currentUpdateToken(name);
call("AssociateSubnets", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"UpdateToken\":\"" + currentToken + "\","
+ "\"SubnetMappings\":[{\"SubnetId\":\"subnet-1111111111111112a\"}]}")
.statusCode(200)
.body("UpdateToken", not(equalTo(currentToken)));
}
@Test
void associateFirewallPolicy_withAStaleToken_isRejectedAndLeavesThePolicyUntouched() {
String name = "StaleTokenPolicyFirewall";
String initialPolicyArn = "arn:aws:network-firewall:us-east-1:723679240095:"
+ "firewall-policy/" + name + "-policy";
createFirewall(name, "", "subnet-1111111111111112b");
call("CreateFirewallPolicy", "{\"FirewallPolicyName\":\"" + name + "-new-policy\","
+ "\"FirewallPolicy\":{\"StatelessDefaultActions\":[\"aws:pass\"],"
+ "\"StatelessFragmentDefaultActions\":[\"aws:pass\"]}}")
.statusCode(200);
call("AssociateFirewallPolicy", "{\"FirewallArn\":\"" + firewallArn(name) + "\","
+ "\"UpdateToken\":\"00000000-0000-0000-0000-000000000000\","
+ "\"FirewallPolicyArn\":\"arn:aws:network-firewall:us-east-1:723679240095:"
+ "firewall-policy/" + name + "-new-policy\"}")
.statusCode(400)
.body("__type", equalTo("InvalidTokenException"));
call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(name) + "\"}")
.statusCode(200)
.body("Firewall.FirewallPolicyArn", equalTo(initialPolicyArn));
}
@Test
void associateFirewallPolicy_returnsTheRotatedUpdateToken() {
String name = "PolicyResponseTokenFirewall";
createFirewall(name, "", "subnet-1111111111111112c");
call("CreateFirewallPolicy", "{\"FirewallPolicyName\":\"" + name + "-new-policy\","
+ "\"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 + "-new-policy\"}")
.statusCode(200)
.body("UpdateToken", not(emptyOrNullString()));
}
private static String currentUpdateToken(String firewallName) {
return call("DescribeFirewall", "{\"FirewallArn\":\"" + firewallArn(firewallName) + "\"}")
.statusCode(200)
.extract().path("UpdateToken");
}
private static String firewallArn(String name) {
return "arn:aws:network-firewall:us-east-1:723679240095:firewall/" + name;
}