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

+3 -2
View File
@@ -178,7 +178,7 @@ LocalStack's community edition [sunset in March 2026](https://blog.localstack.cl
| CodeBuild | Real Docker execution | No |
| Native binary | ~40 MB | No |
**80 AWS services. Broad coverage. Free forever.**
**81 AWS services. Broad coverage. Free forever.**
## Architecture Overview
@@ -226,7 +226,7 @@ Floci supports local emulation for application services, data services, eventing
| Data, analytics, and AI | Athena, Glue, EMR, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Bedrock Runtime, Bedrock AgentCore |
| Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB, ElastiCache |
| Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, IoT Core |
| Security and governance | AWS RAM, Service Quotas, WAF v2, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations |
| Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations |
| Cost and billing | Pricing, Cost Explorer, Cost and Usage Reports, BCM Data Exports |
| Resilience, backup, and config | AWS FIS, AWS Backup, AWS Config, AppConfig, AppConfigData, CloudFormation, Cloud Control API |
@@ -291,6 +291,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
| CodeBuild | In-process with real Docker | Real buildspec execution, CloudWatch logs, S3 artifacts |
| CodeDeploy | In-process with Lambda traffic shifting | Deployment groups, configs, lifecycle hooks, auto-rollback |
| CodePipeline | In-process orchestration | Pipelines, executions, S3 artifacts, approvals, local providers, custom workers |
| AWS Network Firewall | In-process | DescribeFirewall with stable emulated endpoint attachments for infrastructure tooling |
| Service Quotas | In-process | Generated quota catalog with generous static values; real quota codes for CodeBuild and Lambda concurrency |
| AWS RAM | In-process | EnableSharingWithAwsOrganization opt-in |
| AWS Batch | In-process | Compute environments, job queues, job definitions, job submission and lifecycle |
@@ -155,13 +155,15 @@ floci:
enforcement-enabled: false # Set to true to enforce IAM policies on all requests
seed-deployer-principal: false # Set to true to create a local floci-deployer admin principal
networkfirewall:
enabled: true
servicequotas:
enabled: true
ram:
enabled: true
elasticache:
enabled: true
proxy-base-port: 6379
@@ -457,6 +457,7 @@ These services spawn Docker containers. They require access to the Docker socket
| `FLOCI_SERVICES_CODEBUILD_ENABLED` | `true` | Enable the CodeBuild service |
| `FLOCI_SERVICES_CODEBUILD_DOCKER_NETWORK` | _(none)_ | Docker network for CodeBuild build containers |
| `FLOCI_SERVICES_CODEDEPLOY_ENABLED` | `true` | Enable the CodeDeploy service |
| `FLOCI_SERVICES_NETWORKFIREWALL_ENABLED` | `true` | Enable the AWS Network Firewall service |
| `FLOCI_SERVICES_SERVICEQUOTAS_ENABLED` | `true` | Enable the Service Quotas service |
| `FLOCI_SERVICES_RAM_ENABLED` | `true` | Enable the AWS RAM service |
| `FLOCI_SERVICES_BACKUP_ENABLED` | `true` | Enable the AWS Backup service |
+2 -2
View File
@@ -12,7 +12,7 @@ Floci is a fast, free, and open-source local AWS service emulator built for deve
## Supported Services
Floci emulates 80 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details.
Floci emulates 81 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details.
| Service | Protocol |
|---|---|
@@ -117,7 +117,7 @@ docker compose up -d
aws --endpoint-url http://localhost:4566 s3 mb s3://my-bucket
```
All 80 AWS services are immediately available at `http://localhost:4566`.
All 81 AWS services are immediately available at `http://localhost:4566`.
[Get started →](getting-started/quick-start.md){ .md-button .md-button--primary }
[View services →](services/index.md){ .md-button }
+2 -1
View File
@@ -1,6 +1,6 @@
# Services Overview
Floci emulates 80 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification.
Floci emulates 81 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification.
This page is the canonical reference for supported service and operation counts. Some services expose separate control-plane and data-plane rows below. Other docs (and the README) should link here rather than duplicating the table.
@@ -85,6 +85,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [AWS Batch](batch.md) | `/v1/...` | REST JSON | 10 |
| [CodeDeploy](codedeploy.md) | `POST /` + `X-Amz-Target: CodeDeploy_20141006.*` | JSON 1.1 | 30 |
| [CodePipeline](codepipeline.md) | `POST /` + `X-Amz-Target: CodePipeline_20150709.*` | JSON 1.1 | 44 |
| [AWS Network Firewall](network-firewall.md) | `POST /` + `X-Amz-Target: NetworkFirewall_20201112.*` | JSON 1.0 | 27 |
| [AWS Service Catalog](service-catalog.md) | `POST /` + `X-Amz-Target: AWS242ServiceCatalogService.*` | JSON 1.1 | 89 |
| [Service Quotas](servicequotas.md) | `POST /` + `X-Amz-Target: ServiceQuotasV20190624.*` | JSON 1.1 | 5 |
| [AWS RAM](ram.md) | `POST /{operationname}` (lowercase), `DELETE /deleteresourceshare` | REST JSON | 12 |
+49
View File
@@ -0,0 +1,49 @@
# AWS Network Firewall
**Protocol:** AWS JSON 1.0
**Signing name:** `network-firewall`
Floci persists Network Firewall rule groups, firewall policies, firewalls, and
logging configurations. Firewall status is immediately `READY`; endpoint IDs are
stable control-plane identifiers derived from the firewall ARN and its configured
subnets. Floci does not run a packet-inspection data plane.
## Supported Actions
<!-- floci:actions:start -->
| Action | Description |
| --- | --- |
| `CreateRuleGroup` | Creates a stateful or stateless rule group. |
| `DescribeRuleGroup` | Returns a rule group's definition and metadata. |
| `UpdateRuleGroup` | Updates a rule group's rules and settings. |
| `DeleteRuleGroup` | Deletes the specified rule group. |
| `ListRuleGroups` | Lists the rule groups in the account. |
| `CreateFirewallPolicy` | Creates a firewall policy referencing rule groups. |
| `DescribeFirewallPolicy` | Returns a firewall policy's definition and metadata. |
| `UpdateFirewallPolicy` | Updates a firewall policy's definition. |
| `DeleteFirewallPolicy` | Deletes the specified firewall policy. |
| `ListFirewallPolicies` | Lists the firewall policies in the account. |
| `CreateFirewall` | Creates a firewall; status is immediately READY with stable endpoint IDs. |
| `DescribeFirewall` | Returns the firewall's configuration and sync state. |
| `DeleteFirewall` | Deletes the specified firewall. |
| `ListFirewalls` | Lists the firewalls in the account. |
| `UpdateFirewallDeleteProtection` | Sets the firewall's delete-protection flag. |
| `UpdateFirewallPolicyChangeProtection` | Sets the firewall's policy-change-protection flag. |
| `UpdateSubnetChangeProtection` | Sets the firewall's subnet-change-protection flag. |
| `UpdateAvailabilityZoneChangeProtection` | Sets the firewall's Availability-Zone-change-protection flag. |
| `UpdateFirewallDescription` | Updates the firewall's description. |
| `UpdateFirewallAnalysisSettings` | Updates the firewall's traffic-analysis settings. |
| `AssociateSubnets` | Attaches subnets to the firewall, creating endpoint attachments. |
| `DisassociateSubnets` | Detaches subnets from the firewall. |
| `AssociateAvailabilityZones` | Attaches Availability Zones to the firewall. |
| `DisassociateAvailabilityZones` | Detaches Availability Zones from the firewall. |
| `UpdateLoggingConfiguration` | Creates or updates the firewall's logging configuration. |
| `DescribeLoggingConfiguration` | Returns the firewall's logging configuration. |
| `AssociateFirewallPolicy` | Sets Firewall.FirewallPolicyArn on the stored firewall. |
<!-- floci:actions:end -->
## Limitations
- **`AssociateFirewallPolicy` does not validate `FirewallPolicyChangeProtection`.**
AWS rejects the call when the firewall has policy-change protection enabled; Floci
applies the new `FirewallPolicyArn` unconditionally.
@@ -672,6 +672,7 @@ public interface EmulatorConfig {
RumServiceConfig rum();
GuardDutyServiceConfig guardduty();
EmrServerlessServiceConfig emrserverless();
NetworkFirewallServiceConfig networkfirewall();
ServiceCatalogServiceConfig servicecatalog();
SsoAdminServiceConfig ssoadmin();
ServiceQuotasServiceConfig servicequotas();
@@ -732,6 +733,11 @@ public interface EmulatorConfig {
boolean enabled();
}
interface NetworkFirewallServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface ServiceCatalogServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -42,6 +42,7 @@ import io.github.hectorvent.floci.services.kinesisanalytics.KinesisAnalyticsV2Js
import io.github.hectorvent.floci.services.kms.KmsJsonHandler;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerJsonHandler;
import io.github.hectorvent.floci.services.organizations.OrganizationsJsonHandler;
import io.github.hectorvent.floci.services.networkfirewall.NetworkFirewallJsonHandler;
import io.github.hectorvent.floci.services.servicecatalog.ServiceCatalogJsonHandler;
import io.github.hectorvent.floci.services.servicequotas.ServiceQuotasJsonHandler;
import io.github.hectorvent.floci.services.ssm.Ec2MessagesJsonHandler;
@@ -106,6 +107,7 @@ public class AwsJson11Controller {
private final ConfigServiceJsonHandler configServiceJsonHandler;
private final CloudTrailJsonHandler cloudTrailJsonHandler;
private final LightsailJsonHandler lightsailJsonHandler;
private final NetworkFirewallJsonHandler networkFirewallJsonHandler;
private final ServiceCatalogJsonHandler serviceCatalogJsonHandler;
private final CloudControlJsonHandler cloudControlJsonHandler;
private final ApplicationAutoScalingJsonHandler applicationAutoScalingJsonHandler;
@@ -147,6 +149,7 @@ public class AwsJson11Controller {
ConfigServiceJsonHandler configServiceJsonHandler,
CloudTrailJsonHandler cloudTrailJsonHandler,
LightsailJsonHandler lightsailJsonHandler,
NetworkFirewallJsonHandler networkFirewallJsonHandler,
ServiceCatalogJsonHandler serviceCatalogJsonHandler,
CloudControlJsonHandler cloudControlJsonHandler,
ApplicationAutoScalingJsonHandler applicationAutoScalingJsonHandler,
@@ -192,6 +195,7 @@ public class AwsJson11Controller {
this.configServiceJsonHandler = configServiceJsonHandler;
this.cloudTrailJsonHandler = cloudTrailJsonHandler;
this.lightsailJsonHandler = lightsailJsonHandler;
this.networkFirewallJsonHandler = networkFirewallJsonHandler;
this.serviceCatalogJsonHandler = serviceCatalogJsonHandler;
this.cloudControlJsonHandler = cloudControlJsonHandler;
this.applicationAutoScalingJsonHandler = applicationAutoScalingJsonHandler;
@@ -269,6 +273,8 @@ public class AwsJson11Controller {
case "cloudtrail" -> cloudTrailJsonHandler.handle(action, request, region);
case "application-autoscaling" -> applicationAutoScalingJsonHandler.handle(action, request, region);
case "lightsail" -> lightsailJsonHandler.handle(action, request, region);
case "network-firewall" -> networkFirewallJsonHandler.handle(
action, request, region, regionResolver.getAccountId());
case "servicecatalog" -> serviceCatalogJsonHandler.handle(
action, request, region, regionResolver.getAccountId());
case "cloudcontrol" -> cloudControlJsonHandler.handle(action, request, region);
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsJ
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbResponses;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamsJsonHandler;
import io.github.hectorvent.floci.services.networkfirewall.NetworkFirewallJsonHandler;
import io.github.hectorvent.floci.services.sns.SnsJsonHandler;
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsJsonHandler;
@@ -47,6 +48,7 @@ public class AwsJsonController {
private final CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler;
private final CloudControlJsonHandler cloudControlJsonHandler;
private final SwfJsonHandler swfJsonHandler;
private final NetworkFirewallJsonHandler networkFirewallJsonHandler;
@Inject
public AwsJsonController(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,
@@ -57,7 +59,8 @@ public class AwsJsonController {
StepFunctionsJsonHandler sfnJsonHandler,
CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler,
CloudControlJsonHandler cloudControlJsonHandler,
SwfJsonHandler swfJsonHandler) {
SwfJsonHandler swfJsonHandler,
NetworkFirewallJsonHandler networkFirewallJsonHandler) {
this.objectMapper = objectMapper;
this.strictBodyReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
this.catalog = catalog;
@@ -70,6 +73,7 @@ public class AwsJsonController {
this.cloudWatchMetricsJsonHandler = cloudWatchMetricsJsonHandler;
this.cloudControlJsonHandler = cloudControlJsonHandler;
this.swfJsonHandler = swfJsonHandler;
this.networkFirewallJsonHandler = networkFirewallJsonHandler;
}
@POST
@@ -117,6 +121,8 @@ public class AwsJsonController {
case "swf" -> swfJsonHandler.handle(action, request, region);
case "monitoring" -> cloudWatchMetricsJsonHandler.handle(action, request, region);
case "cloudcontrol" -> cloudControlJsonHandler.handle(action, request, region);
case "network-firewall" -> networkFirewallJsonHandler.handle(
action, request, region, regionResolver.getAccountId());
default -> null;
};
// catalog.matchTarget is protocol-agnostic: a JSON 1.1 target
@@ -519,6 +519,10 @@ public class ResolvedServiceCatalog {
config.storage().services().guardduty().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("guardduty"), Set.of(), Set.of(GuardDutyController.class)),
descriptor("network-firewall", "networkfirewall", config.services().networkfirewall().enabled(), true,
"networkfirewall", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("NetworkFirewall_20201112."), Set.of("network-firewall"), Set.of(), Set.of()),
descriptor("servicecatalog", "servicecatalog", config.services().servicecatalog().enabled(), true,
"servicecatalog", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
@@ -0,0 +1,71 @@
package io.github.hectorvent.floci.services.networkfirewall;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
@ApplicationScoped
public class NetworkFirewallJsonHandler {
private final NetworkFirewallService service;
@Inject
public NetworkFirewallJsonHandler(NetworkFirewallService service) {
this.service = service;
}
public Response handle(String action, JsonNode request, String region, String accountId) {
return switch (action) {
case "CreateRuleGroup" -> ok(service.createRuleGroup(request, region, accountId));
case "DescribeRuleGroup" -> ok(service.describeRuleGroup(
textOrNull(request, "RuleGroupArn"), textOrNull(request, "RuleGroupName")));
case "UpdateRuleGroup" -> ok(service.updateRuleGroup(request, region, accountId));
case "DeleteRuleGroup" -> ok(service.deleteRuleGroup(
textOrNull(request, "RuleGroupArn"), textOrNull(request, "RuleGroupName")));
case "ListRuleGroups" -> ok(service.listRuleGroups(textOrNull(request, "Type")));
case "CreateFirewallPolicy" -> ok(service.createFirewallPolicy(request, region, accountId));
case "DescribeFirewallPolicy" -> ok(service.describeFirewallPolicy(
textOrNull(request, "FirewallPolicyArn"), textOrNull(request, "FirewallPolicyName")));
case "UpdateFirewallPolicy" -> ok(service.updateFirewallPolicy(request, region, accountId));
case "DeleteFirewallPolicy" -> ok(service.deleteFirewallPolicy(
textOrNull(request, "FirewallPolicyArn"), textOrNull(request, "FirewallPolicyName")));
case "ListFirewallPolicies" -> ok(service.listFirewallPolicies());
case "CreateFirewall" -> ok(service.createFirewall(request, region, accountId));
case "DescribeFirewall" -> Response.ok(service.describeFirewall(
textOrNull(request, "FirewallArn"),
textOrNull(request, "FirewallName"),
region,
accountId)).build();
case "DeleteFirewall" -> ok(service.deleteFirewall(
textOrNull(request, "FirewallArn"), textOrNull(request, "FirewallName"), region));
case "ListFirewalls" -> ok(service.listFirewalls(request));
case "UpdateFirewallDeleteProtection", "UpdateFirewallPolicyChangeProtection",
"UpdateSubnetChangeProtection", "UpdateAvailabilityZoneChangeProtection",
"UpdateFirewallDescription", "UpdateFirewallAnalysisSettings"
-> ok(service.updateFirewall(action, request, region, accountId));
case "AssociateSubnets" -> ok(service.associateSubnets(request));
case "DisassociateSubnets" -> ok(service.disassociateSubnets(request));
case "AssociateAvailabilityZones" -> ok(service.associateAvailabilityZones(request));
case "DisassociateAvailabilityZones" -> ok(service.disassociateAvailabilityZones(request));
case "UpdateLoggingConfiguration" -> ok(service.putLoggingConfiguration(request));
case "DescribeLoggingConfiguration" -> ok(service.describeLoggingConfiguration(
textOrNull(request, "FirewallArn"), textOrNull(request, "FirewallName")));
case "AssociateFirewallPolicy" -> ok(service.associateFirewallPolicy(request, region, accountId));
default -> Response.status(400)
.entity(new AwsErrorResponse("UnknownOperationException",
"Unknown operation: NetworkFirewall_20201112." + action))
.build();
};
}
private static Response ok(JsonNode entity) {
return Response.ok(entity).build();
}
private static String textOrNull(JsonNode request, String field) {
JsonNode value = request == null ? null : request.get(field);
return value == null || value.isNull() ? null : value.asText();
}
}
@@ -0,0 +1,638 @@
package io.github.hectorvent.floci.services.networkfirewall;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Comparator;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
@ApplicationScoped
public class NetworkFirewallService {
private static final int AVAILABILITY_ZONES_PER_REGION = 6;
private static final Set<String> RULE_GROUP_TYPES =
Set.of("STATELESS", "STATEFUL", "STATEFUL_DOMAIN");
private static final Set<String> LOG_TYPES = Set.of("ALERT", "FLOW", "TLS");
private static final Set<String> LOG_DESTINATION_TYPES =
Set.of("S3", "CloudWatchLogs", "KinesisDataFirehose");
private final ObjectMapper objectMapper;
private final StorageBackend<String, ObjectNode> ruleGroups;
private final StorageBackend<String, ObjectNode> firewallPolicies;
private final StorageBackend<String, ObjectNode> firewalls;
private final StorageBackend<String, ObjectNode> loggingConfigurations;
@Inject
public NetworkFirewallService(ObjectMapper objectMapper, StorageFactory storageFactory) {
this(objectMapper,
storageFactory.create("networkfirewall", "network-firewall-rule-groups.json",
new TypeReference<Map<String, ObjectNode>>() {}),
storageFactory.create("networkfirewall", "network-firewall-policies.json",
new TypeReference<Map<String, ObjectNode>>() {}),
storageFactory.create("networkfirewall", "network-firewall-firewalls.json",
new TypeReference<Map<String, ObjectNode>>() {}),
storageFactory.create("networkfirewall", "network-firewall-logging.json",
new TypeReference<Map<String, ObjectNode>>() {}));
}
NetworkFirewallService(ObjectMapper objectMapper,
StorageBackend<String, ObjectNode> ruleGroups,
StorageBackend<String, ObjectNode> firewallPolicies,
StorageBackend<String, ObjectNode> firewalls,
StorageBackend<String, ObjectNode> loggingConfigurations) {
this.objectMapper = objectMapper;
this.ruleGroups = ruleGroups;
this.firewallPolicies = firewallPolicies;
this.firewalls = firewalls;
this.loggingConfigurations = loggingConfigurations;
}
public ObjectNode createRuleGroup(JsonNode request, String region, String accountId) {
return createNamed(request, "RuleGroupName", "RuleGroup", "RuleGroupResponse",
"RuleGroupArn", "RuleGroupId", ruleGroupArn(request, region, accountId), ruleGroups);
}
public ObjectNode describeRuleGroup(String arn, String name) {
return describeNamed(ruleGroups, arn, name, "RuleGroup");
}
public ObjectNode updateRuleGroup(JsonNode request, String region, String accountId) {
deleteIfPresent(ruleGroups, textOrNull(request, "RuleGroupArn"), textOrNull(request, "RuleGroupName"));
return createRuleGroup(request, region, accountId);
}
public ObjectNode deleteRuleGroup(String arn, String name) {
deleteRequired(ruleGroups, arn, name, "RuleGroup");
return objectMapper.createObjectNode();
}
public ObjectNode listRuleGroups(String type) {
return listNamed(ruleGroups, "RuleGroups", "Arn", "Name", type, "Type");
}
public ObjectNode createFirewallPolicy(JsonNode request, String region, String accountId) {
String name = requiredText(request, "FirewallPolicyName");
String arn = arn(region, accountId, "firewall-policy", name);
return createNamed(request, "FirewallPolicyName", "FirewallPolicy", "FirewallPolicyResponse",
"FirewallPolicyArn", "FirewallPolicyId", arn, firewallPolicies);
}
public ObjectNode describeFirewallPolicy(String arn, String name) {
return describeNamed(firewallPolicies, arn, name, "FirewallPolicy");
}
public ObjectNode updateFirewallPolicy(JsonNode request, String region, String accountId) {
deleteIfPresent(firewallPolicies, textOrNull(request, "FirewallPolicyArn"),
textOrNull(request, "FirewallPolicyName"));
return createFirewallPolicy(request, region, accountId);
}
public ObjectNode deleteFirewallPolicy(String arn, String name) {
deleteRequired(firewallPolicies, arn, name, "FirewallPolicy");
return objectMapper.createObjectNode();
}
public ObjectNode listFirewallPolicies() {
return listNamed(firewallPolicies, "FirewallPolicies", "Arn", "Name", null, null);
}
public ObjectNode createFirewall(JsonNode request, String region, String accountId) {
String name = requiredText(request, "FirewallName");
String firewallArn = arn(region, accountId, "firewall", name);
ensureUnique(firewalls, firewallArn, name, "Firewall");
ObjectNode firewall = copyObject(request);
firewall.remove("UpdateToken");
firewall.put("FirewallArn", firewallArn);
firewall.put("FirewallId", deterministicHex(firewallArn, 32));
firewall.put("FirewallName", name);
firewall.put("FirewallPolicyChangeProtection", request.path("FirewallPolicyChangeProtection").asBoolean(true));
firewall.put("SubnetChangeProtection", request.path("SubnetChangeProtection").asBoolean(true));
firewall.put("DeleteProtection", request.path("DeleteProtection").asBoolean(true));
firewall.put("AvailabilityZoneChangeProtection",
request.path("AvailabilityZoneChangeProtection").asBoolean(false));
firewalls.put(firewallArn, firewall);
return firewallResponse(firewall, region);
}
public 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);
}
/**
* 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
* AWS ignoring unmodeled request members and scoping each op to its own field.
*/
private static final Map<String, String> UPDATE_ACTION_FIELDS = Map.of(
"UpdateFirewallDescription", "Description",
"UpdateFirewallDeleteProtection", "DeleteProtection",
"UpdateSubnetChangeProtection", "SubnetChangeProtection",
"UpdateFirewallPolicyChangeProtection", "FirewallPolicyChangeProtection",
"UpdateAvailabilityZoneChangeProtection", "AvailabilityZoneChangeProtection",
"UpdateFirewallAnalysisSettings", "EnabledAnalysisTypes");
/**
* Botocore documents omission as removal for UpdateFirewallDescription alone:
* "If you omit this setting, Network Firewall removes the description for the
* firewall." EnabledAnalysisTypes carries no equivalent statement, so an omitted
* value there is preserved rather than inferring behaviour the model never states.
*/
private static final Set<String> CLEARED_WHEN_OMITTED = Set.of("UpdateFirewallDescription");
public 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");
String field = UPDATE_ACTION_FIELDS.get(action);
JsonNode value = request.get(field);
if (value != null) {
existing.set(field, value.deepCopy());
} else if (CLEARED_WHEN_OMITTED.contains(action)) {
existing.remove(field);
}
firewalls.put(existing.path("FirewallArn").asText(), existing);
// Each UpdateFirewall* response is a flat {FirewallArn, FirewallName,
// <field>, UpdateToken} shape (botocore 2020-11-12) -- distinct from
// CreateFirewall/DescribeFirewall's nested {Firewall, FirewallStatus}
// envelope that firewallResponse() builds.
ObjectNode response = objectMapper.createObjectNode();
response.put("FirewallArn", existing.path("FirewallArn").asText());
response.put("FirewallName", existing.path("FirewallName").asText());
// Description and EnabledAnalysisTypes are optional on their own update ops
// (botocore 2020-11-12 marks no required members), so a firewall created
// without one has nothing to echo -- omit the member rather than serialising
// the MissingNode that path() returns as an explicit null.
JsonNode current = existing.get(field);
if (current != null) {
response.set(field, current.deepCopy());
}
response.put("UpdateToken", UUID.randomUUID().toString());
return response;
}
public ObjectNode deleteFirewall(String arn, String name, String region) {
ObjectNode existing = require(firewalls, arn, name, "Firewall", "FirewallArn", "FirewallName");
String firewallArn = existing.path("FirewallArn").asText();
if (existing.path("DeleteProtection").asBoolean(false)) {
throw new AwsException("InvalidOperationException",
"Firewall has delete protection enabled: " + firewallArn, 400);
}
ObjectNode response = firewallResponse(existing, region);
firewalls.delete(firewallArn);
loggingConfigurations.delete(firewallArn);
return response;
}
/**
* The four association operations are synchronized because {@link #mappingsOf}
* hands out a detached copy and {@link #storeAndRespond} replaces the whole
* field with it: the read-modify-write is only atomic under a common lock, and
* without one the later of two overlapping calls silently discards the earlier
* caller's mapping.
*/
public synchronized ObjectNode associateSubnets(JsonNode request) {
ObjectNode firewall = firewallForChange(request, "SubnetChangeProtection", "subnet");
ArrayNode requestedMappings = requiredArray(request, "SubnetMappings");
ArrayNode mappings = mappingsOf(firewall, "SubnetMappings");
for (JsonNode requested : requestedMappings) {
addMapping(mappings, "SubnetId", requiredText(requested, "SubnetId"), requested);
}
return storeAndRespond(firewall, "SubnetMappings", mappings);
}
/** @see #associateSubnets for why this is synchronized. */
public synchronized ObjectNode disassociateSubnets(JsonNode request) {
ObjectNode firewall = firewallForChange(request, "SubnetChangeProtection", "subnet");
ArrayNode requestedIds = requiredArray(request, "SubnetIds");
ArrayNode mappings = mappingsOf(firewall, "SubnetMappings");
for (JsonNode subnetId : requestedIds) {
removeMapping(mappings, "SubnetId", subnetId.asText());
}
return storeAndRespond(firewall, "SubnetMappings", mappings);
}
/** @see #associateSubnets for why this is synchronized. */
public synchronized ObjectNode associateAvailabilityZones(JsonNode request) {
ObjectNode firewall =
firewallForChange(request, "AvailabilityZoneChangeProtection", "Availability Zone");
ArrayNode requestedMappings = requiredArray(request, "AvailabilityZoneMappings");
ArrayNode mappings = mappingsOf(firewall, "AvailabilityZoneMappings");
for (JsonNode requested : requestedMappings) {
addMapping(mappings, "AvailabilityZone", requiredText(requested, "AvailabilityZone"), requested);
}
return storeAndRespond(firewall, "AvailabilityZoneMappings", mappings);
}
/** @see #associateSubnets for why this is synchronized. */
public synchronized ObjectNode disassociateAvailabilityZones(JsonNode request) {
ObjectNode firewall =
firewallForChange(request, "AvailabilityZoneChangeProtection", "Availability Zone");
ArrayNode requestedMappings = requiredArray(request, "AvailabilityZoneMappings");
ArrayNode mappings = mappingsOf(firewall, "AvailabilityZoneMappings");
for (JsonNode requested : requestedMappings) {
removeMapping(mappings, "AvailabilityZone", requiredText(requested, "AvailabilityZone"));
}
return storeAndRespond(firewall, "AvailabilityZoneMappings", mappings);
}
private ObjectNode firewallForChange(JsonNode request, String protectionField, String protectedResource) {
ObjectNode firewall = require(firewalls, textOrNull(request, "FirewallArn"),
textOrNull(request, "FirewallName"), "Firewall", "FirewallArn", "FirewallName");
if (firewall.path(protectionField).asBoolean(false)) {
throw new AwsException("InvalidOperationException",
"Firewall has " + protectedResource + " change protection enabled: "
+ firewall.path("FirewallArn").asText(), 400);
}
return firewall;
}
/**
* 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
* attached and persisted only by {@link #storeAndRespond}.
*/
private ArrayNode mappingsOf(ObjectNode firewall, String field) {
JsonNode existing = firewall.path(field);
return existing.isArray() ? ((ArrayNode) existing).deepCopy() : objectMapper.createArrayNode();
}
private void addMapping(ArrayNode mappings, String memberField, String member, JsonNode mapping) {
for (JsonNode existing : mappings) {
if (member.equals(existing.path(memberField).asText(null))) {
return;
}
}
mappings.add(mapping.deepCopy());
}
private void removeMapping(ArrayNode mappings, String memberField, String member) {
for (int index = mappings.size() - 1; index >= 0; index--) {
if (member.equals(mappings.get(index).path(memberField).asText(null))) {
mappings.remove(index);
}
}
}
private ObjectNode storeAndRespond(ObjectNode firewall, String field, ArrayNode mappings) {
String firewallArn = firewall.path("FirewallArn").asText();
firewall.set(field, mappings);
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());
return response;
}
public ObjectNode listFirewalls(JsonNode request) {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode result = response.putArray("Firewalls");
List<String> vpcIds = request != null && request.path("VpcIds").isArray()
? java.util.stream.StreamSupport.stream(request.path("VpcIds").spliterator(), false)
.map(JsonNode::asText).toList()
: List.of();
firewalls.scan(key -> true).stream()
.filter(firewall -> vpcIds.isEmpty() || vpcIds.contains(firewall.path("VpcId").asText()))
.sorted(Comparator.comparing(firewall -> firewall.path("FirewallName").asText()))
.forEach(firewall -> result.add(objectMapper.createObjectNode()
.put("FirewallArn", firewall.path("FirewallArn").asText())
.put("FirewallName", firewall.path("FirewallName").asText())));
return response;
}
public ObjectNode putLoggingConfiguration(JsonNode request) {
String arn = resolveFirewallArn(request);
ObjectNode existing = require(firewalls, arn, textOrNull(request, "FirewallName"),
"Firewall", "FirewallArn", "FirewallName");
validateLoggingConfiguration(request.path("LoggingConfiguration"));
ObjectNode stored = objectMapper.createObjectNode();
stored.put("FirewallArn", existing.path("FirewallArn").asText());
stored.put("FirewallName", existing.path("FirewallName").asText());
stored.set("LoggingConfiguration", request.path("LoggingConfiguration").deepCopy());
if (request.has("EnableMonitoringDashboard")) {
stored.set("EnableMonitoringDashboard", request.get("EnableMonitoringDashboard").deepCopy());
}
loggingConfigurations.put(existing.path("FirewallArn").asText(), stored);
return stored.deepCopy();
}
/**
* The whole LoggingConfiguration is stored verbatim, so the two enums inside each
* LogDestinationConfig have to be checked here: LogType (ALERT/FLOW/TLS) and LogDestinationType
* (S3/CloudWatchLogs/KinesisDataFirehose, case-sensitive as the model spells them).
*/
private void validateLoggingConfiguration(JsonNode loggingConfiguration) {
if (loggingConfiguration == null || !loggingConfiguration.isObject()) {
return;
}
for (JsonNode config : loggingConfiguration.path("LogDestinationConfigs")) {
requireEnum(textOrNull(config, "LogType"), LOG_TYPES, "LogType");
requireEnum(textOrNull(config, "LogDestinationType"), LOG_DESTINATION_TYPES,
"LogDestinationType");
}
}
public ObjectNode describeLoggingConfiguration(String arn, String name) {
ObjectNode firewall = require(firewalls, arn, name, "Firewall", "FirewallArn", "FirewallName");
ObjectNode logging = loggingConfigurations.get(firewall.path("FirewallArn").asText()).orElse(null);
if (logging == null) {
ObjectNode empty = objectMapper.createObjectNode();
empty.put("FirewallArn", firewall.path("FirewallArn").asText());
empty.put("FirewallName", firewall.path("FirewallName").asText());
empty.set("LoggingConfiguration", objectMapper.createObjectNode()
.set("LogDestinationConfigs", objectMapper.createArrayNode()));
return empty;
}
return logging.deepCopy();
}
public ObjectNode deleteLoggingConfiguration(String arn, String name) {
ObjectNode firewall = require(firewalls, arn, name, "Firewall", "FirewallArn", "FirewallName");
loggingConfigurations.delete(firewall.path("FirewallArn").asText());
return objectMapper.createObjectNode();
}
public ObjectNode findFirewall(String arn) {
return firewalls.get(arn).map(ObjectNode::deepCopy).orElse(null);
}
private ObjectNode createNamed(JsonNode request, String nameField, String requestBodyField,
String responseField, String arnField, String idField,
String resourceArn, StorageBackend<String, ObjectNode> store) {
String name = requiredText(request, nameField);
ensureUnique(store, resourceArn, name, requestBodyField);
ObjectNode responseInfo = copyObject(request);
JsonNode body = responseInfo.remove(requestBodyField);
responseInfo.remove("UpdateToken");
responseInfo.put(arnField, resourceArn);
responseInfo.put(idField, deterministicHex(resourceArn, 32));
responseInfo.put(nameField, name);
responseInfo.put("ResourceArn", resourceArn);
responseInfo.put("ResourceName", name);
ObjectNode stored = objectMapper.createObjectNode();
if (body != null && !body.isMissingNode()) {
stored.set(requestBodyField, body.deepCopy());
}
stored.set(responseField, responseInfo);
stored.put("UpdateToken", UUID.randomUUID().toString());
store.put(resourceArn, stored);
return stored.deepCopy();
}
private ObjectNode describeNamed(StorageBackend<String, ObjectNode> store, String arn, String name,
String bodyField) {
ObjectNode stored = require(store, arn, name, bodyField, "ResourceArn", "ResourceName");
return stored.deepCopy();
}
private ObjectNode listNamed(StorageBackend<String, ObjectNode> store, String responseField,
String arnField, String nameField, String filter, String filterField) {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode array = response.putArray(responseField);
store.scan(key -> true).stream()
.map(this::resourceMetadata)
.filter(node -> filter == null || filter.equals(node.path(filterField).asText()))
.sorted(Comparator.comparing(node -> node.path("ResourceName").asText()))
.forEach(node -> array.add(objectMapper.createObjectNode()
.put(arnField, node.path("ResourceArn").asText())
.put(nameField, node.path("ResourceName").asText())));
return response;
}
private JsonNode resourceMetadata(JsonNode stored) {
if (stored.hasNonNull("ResourceArn")) {
return stored;
}
for (JsonNode child : stored) {
if (child.isObject() && child.hasNonNull("ResourceArn")) {
return child;
}
}
return objectMapper.createObjectNode();
}
private ObjectNode firewallResponse(ObjectNode firewall, String region) {
ObjectNode response = objectMapper.createObjectNode();
response.set("Firewall", firewall.deepCopy());
ObjectNode status = response.putObject("FirewallStatus");
status.put("ConfigurationSyncStateSummary", "IN_SYNC");
status.put("Status", "READY");
ObjectNode syncStates = status.putObject("SyncStates");
JsonNode mappings = firewall.path("SubnetMappings");
// Only a firewall created without any SubnetMappings gets synthetic endpoints; once the
// field exists, disassociating every subnet must leave the sync states empty.
if (mappings.isArray()) {
int index = 0;
for (JsonNode mapping : mappings) {
addAttachment(syncStates, region + (char) ('a' + index++),
mapping.path("SubnetId").asText(), firewall.path("FirewallArn").asText());
}
} else {
for (int index = 0; index < AVAILABILITY_ZONES_PER_REGION; index++) {
String availabilityZone = region + (char) ('a' + index);
String subnetId = "subnet-" + deterministicHex(
firewall.path("FirewallArn").asText() + "|subnet|" + availabilityZone, 17);
addAttachment(syncStates, availabilityZone, subnetId, firewall.path("FirewallArn").asText());
}
}
return response;
}
private void addAttachment(ObjectNode syncStates, String availabilityZone, String subnetId, String arn) {
ObjectNode attachment = syncStates.putObject(availabilityZone).putObject("Attachment");
attachment.put("EndpointId", "vpce-" + deterministicHex(arn + "|" + availabilityZone, 17));
attachment.put("Status", "READY");
attachment.put("SubnetId", subnetId);
}
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);
}
}
private ObjectNode require(StorageBackend<String, ObjectNode> store, String arn, String name,
String kind, String arnField, String nameField) {
requireIdentifier(arn, name);
ObjectNode result = find(store, arn, name, arnField, nameField);
if (result == null) {
throw notFound(kind, arn == null ? name : arn);
}
return result;
}
private ObjectNode find(StorageBackend<String, ObjectNode> store, String arn, String name,
String arnField, String nameField) {
if (arn != null && !arn.isBlank()) {
ObjectNode direct = store.get(arn).orElse(null);
if (direct != null) {
return direct;
}
}
if (name == null || name.isBlank()) {
return null;
}
return store.scan(key -> true).stream()
.filter(node -> containsValue(node, nameField, name))
.findFirst().orElse(null);
}
private boolean containsValue(JsonNode node, String field, String expected) {
if (expected.equals(node.path(field).asText(null))) {
return true;
}
for (JsonNode child : node) {
if (child.isObject() && expected.equals(child.path(field).asText(null))) {
return true;
}
}
return false;
}
private void deleteRequired(StorageBackend<String, ObjectNode> store, String arn, String name, String kind) {
ObjectNode stored = require(store, arn, name, kind, "ResourceArn", "ResourceName");
store.delete(resourceArn(stored));
}
private void deleteIfPresent(StorageBackend<String, ObjectNode> store, String arn, String name) {
ObjectNode stored = find(store, arn, name, "ResourceArn", "ResourceName");
if (stored != null) {
store.delete(resourceArn(stored));
}
}
private String resourceArn(JsonNode stored) {
if (stored.hasNonNull("ResourceArn")) {
return stored.path("ResourceArn").asText();
}
for (JsonNode child : stored) {
if (child.isObject() && child.hasNonNull("ResourceArn")) {
return child.path("ResourceArn").asText();
}
}
throw new IllegalStateException("Stored Network Firewall resource has no ARN");
}
/**
* The model enumerates {@code Type} as STATELESS, STATEFUL or STATEFUL_DOMAIN, and the value is
* both persisted and folded into the ARN. Only STATELESS gets the stateless ARN prefix; the two
* stateful variants share {@code stateful-rulegroup}, as AWS does. Left unchecked, any unmodelled
* value silently fell through to the stateful prefix and was stored as a rule group AWS would
* have rejected.
*/
private String ruleGroupArn(JsonNode request, String region, String accountId) {
String type = requiredText(request, "Type");
requireEnum(type, RULE_GROUP_TYPES, "Type");
String prefix = "STATELESS".equals(type) ? "stateless-rulegroup" : "stateful-rulegroup";
return arn(region, accountId, prefix, requiredText(request, "RuleGroupName"));
}
private static void requireEnum(String value, Set<String> allowed, String field) {
if (!allowed.contains(value)) {
throw new AwsException("InvalidRequestException",
field + " must be one of " + allowed + ".", 400);
}
}
private String resolveFirewallArn(JsonNode request) {
String arn = textOrNull(request, "FirewallArn");
if (arn != null) {
return arn;
}
String name = textOrNull(request, "FirewallName");
ObjectNode firewall = find(firewalls, null, name, "FirewallArn", "FirewallName");
return firewall == null ? null : firewall.path("FirewallArn").asText();
}
private ObjectNode copyObject(JsonNode request) {
if (request == null || !request.isObject()) {
throw new AwsException("InvalidRequestException", "A JSON request object is required.", 400);
}
return ((ObjectNode) request).deepCopy();
}
private static String requiredText(JsonNode request, String field) {
String value = textOrNull(request, field);
if (value == null || value.isBlank()) {
throw new AwsException("InvalidRequestException", field + " is required.", 400);
}
return value;
}
private static ArrayNode requiredArray(JsonNode request, String field) {
JsonNode value = request == null ? null : request.get(field);
if (value == null || !value.isArray() || value.isEmpty()) {
throw new AwsException("InvalidRequestException", field + " is required.", 400);
}
return (ArrayNode) value;
}
private static void requireIdentifier(String arn, String name) {
if ((arn == null || arn.isBlank()) && (name == null || name.isBlank())) {
throw new AwsException("InvalidRequestException",
"Either a resource name or ARN must be specified.", 400);
}
}
private static AwsException notFound(String kind, String identifier) {
return new AwsException("ResourceNotFoundException", kind + " not found: " + identifier, 400);
}
private static String arn(String region, String accountId, String type, String name) {
return "arn:aws:network-firewall:" + region + ":" + accountId + ":" + type + "/" + name;
}
static String textOrNull(JsonNode request, String field) {
JsonNode value = request == null ? null : request.get(field);
return value == null || value.isNull() ? null : value.asText();
}
static String deterministicHex(String value, int length) {
try {
byte[] digest = MessageDigest.getInstance("SHA-256")
.digest(value.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(digest).substring(0, length);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 unavailable", e);
}
}
public 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);
firewalls.put(firewallArn, firewall);
ObjectNode response = objectMapper.createObjectNode();
response.put("FirewallArn", firewallArn);
response.put("FirewallName", firewall.path("FirewallName").asText());
response.put("FirewallPolicyArn", policyArn);
return response;
}
}
+2
View File
@@ -543,6 +543,8 @@ floci:
enabled: true
rum:
enabled: true
networkfirewall:
enabled: true
servicecatalog:
enabled: true
guardduty:
@@ -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);
}
}
+2
View File
@@ -337,6 +337,8 @@ floci:
enabled: true
rum:
enabled: true
networkfirewall:
enabled: true
servicecatalog:
enabled: true
guardduty:
+4
View File
@@ -108,6 +108,10 @@ services:
doc: docs/services/neptune.md
sources:
- { path: src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneQueryHandler.java, mode: switch }
- service: networkfirewall
doc: docs/services/network-firewall.md
sources:
- { path: src/main/java/io/github/hectorvent/floci/services/networkfirewall/NetworkFirewallJsonHandler.java, mode: switch }
- service: ram
doc: docs/services/ram.md
sources: