From 8027e400a444de67a96a14e53723d6c40e499dd4 Mon Sep 17 00:00:00 2001 From: Gajendra Malviya Date: Fri, 16 Oct 2026 17:16:43 +0530 Subject: [PATCH 1/2] fix(aws-networkfirewall): close real-cloud parity gaps in #1455 --- .../enforce_authz_networkfirewall_test.go | 78 ++ docs/coverage/aws/networkfirewall.md | 100 ++- docs/coverage/coverage.json | 142 ++++ docs/coverage/nongoals/networkfirewall.md | 9 + docs/services.md | 4 +- internal/settle/settle.go | 2 + .../aws/networkfirewall/analysis_report.go | 114 +++ providers/aws/networkfirewall/capacity.go | 77 ++ .../aws/networkfirewall/concurrency_test.go | 248 ++++++ .../aws/networkfirewall/families_test.go | 528 +++++++++++++ providers/aws/networkfirewall/firewall.go | 557 ++++++++++++++ .../aws/networkfirewall/flow_operation.go | 222 ++++++ providers/aws/networkfirewall/logging.go | 221 ++++++ providers/aws/networkfirewall/metadata.go | 123 +++ .../aws/networkfirewall/networkfirewall.go | 713 ++---------------- .../networkfirewall/networkfirewall_test.go | 303 ++++---- providers/aws/networkfirewall/pagination.go | 34 + providers/aws/networkfirewall/policy.go | 278 +++++++ .../aws/networkfirewall/policy_actions.go | 246 ++++++ .../aws/networkfirewall/reference_test.go | 395 ++++++++++ .../aws/networkfirewall/resource_policy.go | 194 +++++ providers/aws/networkfirewall/rule_group.go | 318 ++++++++ providers/aws/networkfirewall/snapshot.go | 149 +++- .../aws/networkfirewall/snapshot_test.go | 135 ++-- providers/aws/networkfirewall/tags.go | 131 ++++ .../aws/networkfirewall/tls_inspection.go | 226 ++++++ providers/aws/networkfirewall/token.go | 25 + providers/aws/networkfirewall/token_test.go | 324 ++++++++ providers/aws/networkfirewall/validation.go | 115 +++ .../aws/networkfirewall/validation_test.go | 324 ++++++++ .../vpc_endpoint_association.go | 157 ++++ .../aws/networkfirewall_discovery_test.go | 67 ++ providers/aws/rgt_discovery.go | 91 ++- server/aws/networkfirewall/analysis_report.go | 96 +++ .../aws/networkfirewall/availability_zones.go | 48 ++ .../aws/networkfirewall/change_protection.go | 121 +++ server/aws/networkfirewall/depth.go | 258 +++---- server/aws/networkfirewall/dispatch_test.go | 210 ++++++ server/aws/networkfirewall/errors.go | 45 ++ server/aws/networkfirewall/flow_operation.go | 194 +++++ server/aws/networkfirewall/handler.go | 137 ++-- server/aws/networkfirewall/logging.go | 120 +++ server/aws/networkfirewall/metadata.go | 111 +++ server/aws/networkfirewall/operations.go | 449 +++-------- server/aws/networkfirewall/policy.go | 258 +++++++ server/aws/networkfirewall/resource_policy.go | 75 ++ server/aws/networkfirewall/rule_group.go | 219 ++++++ server/aws/networkfirewall/sdk_parity_test.go | 708 +++++++++++++++++ .../aws/networkfirewall/sdk_roundtrip_test.go | 28 +- server/aws/networkfirewall/tls_inspection.go | 181 +++++ .../vpc_endpoint_association.go | 156 ++++ .../driver/availability_zones.go | 43 ++ .../networkfirewall/driver/capabilities.go | 195 +++++ services/networkfirewall/driver/driver.go | 214 ++++-- services/networkfirewall/driver/errors.go | 59 ++ 55 files changed, 9083 insertions(+), 1492 deletions(-) create mode 100644 contrib/server/enforce_authz_networkfirewall_test.go create mode 100644 docs/coverage/nongoals/networkfirewall.md create mode 100644 providers/aws/networkfirewall/analysis_report.go create mode 100644 providers/aws/networkfirewall/capacity.go create mode 100644 providers/aws/networkfirewall/concurrency_test.go create mode 100644 providers/aws/networkfirewall/families_test.go create mode 100644 providers/aws/networkfirewall/firewall.go create mode 100644 providers/aws/networkfirewall/flow_operation.go create mode 100644 providers/aws/networkfirewall/logging.go create mode 100644 providers/aws/networkfirewall/metadata.go create mode 100644 providers/aws/networkfirewall/pagination.go create mode 100644 providers/aws/networkfirewall/policy.go create mode 100644 providers/aws/networkfirewall/policy_actions.go create mode 100644 providers/aws/networkfirewall/reference_test.go create mode 100644 providers/aws/networkfirewall/resource_policy.go create mode 100644 providers/aws/networkfirewall/rule_group.go create mode 100644 providers/aws/networkfirewall/tags.go create mode 100644 providers/aws/networkfirewall/tls_inspection.go create mode 100644 providers/aws/networkfirewall/token.go create mode 100644 providers/aws/networkfirewall/token_test.go create mode 100644 providers/aws/networkfirewall/validation.go create mode 100644 providers/aws/networkfirewall/validation_test.go create mode 100644 providers/aws/networkfirewall/vpc_endpoint_association.go create mode 100644 providers/aws/networkfirewall_discovery_test.go create mode 100644 server/aws/networkfirewall/analysis_report.go create mode 100644 server/aws/networkfirewall/availability_zones.go create mode 100644 server/aws/networkfirewall/change_protection.go create mode 100644 server/aws/networkfirewall/dispatch_test.go create mode 100644 server/aws/networkfirewall/errors.go create mode 100644 server/aws/networkfirewall/flow_operation.go create mode 100644 server/aws/networkfirewall/logging.go create mode 100644 server/aws/networkfirewall/metadata.go create mode 100644 server/aws/networkfirewall/policy.go create mode 100644 server/aws/networkfirewall/resource_policy.go create mode 100644 server/aws/networkfirewall/rule_group.go create mode 100644 server/aws/networkfirewall/sdk_parity_test.go create mode 100644 server/aws/networkfirewall/tls_inspection.go create mode 100644 server/aws/networkfirewall/vpc_endpoint_association.go create mode 100644 services/networkfirewall/driver/availability_zones.go create mode 100644 services/networkfirewall/driver/capabilities.go create mode 100644 services/networkfirewall/driver/errors.go diff --git a/contrib/server/enforce_authz_networkfirewall_test.go b/contrib/server/enforce_authz_networkfirewall_test.go new file mode 100644 index 000000000..7c14a8865 --- /dev/null +++ b/contrib/server/enforce_authz_networkfirewall_test.go @@ -0,0 +1,78 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "io" + "net/http" + "strings" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4" +) + +// signedJSONTarget sends a SigV4-signed AWS JSON 1.0 request for the given +// X-Amz-Target and returns the status and body. +func signedJSONTarget(t *testing.T, endpoint string, c aws.Credentials, service, target, body string) (int, string) { + t.Helper() + + req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, endpoint+"/", strings.NewReader(body)) + if err != nil { + t.Fatalf("new request: %v", err) + } + + req.Header.Set("Content-Type", "application/x-amz-json-1.0") + req.Header.Set("X-Amz-Target", target) + + sum := sha256.Sum256([]byte(body)) + if err := v4.NewSigner().SignHTTP(context.Background(), c, req, hex.EncodeToString(sum[:]), service, "us-east-1", time.Now()); err != nil { + t.Fatalf("sign: %v", err) + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("do: %v", err) + } + defer resp.Body.Close() + + raw, _ := io.ReadAll(resp.Body) + + return resp.StatusCode, string(raw) +} + +// TestEnforceAuthNetworkFirewall proves the operations added for the Network +// Firewall parity work are authorised per IAM action under --enforce-auth: a +// user allowed only network-firewall:DescribeFirewall passes the gate on that +// operation (the handler then answers its own 400 for the unknown firewall) and +// is refused on the new ones, while an administrator is allowed everywhere. +func TestEnforceAuthNetworkFirewall(t *testing.T) { + endpoint, stop := enforceAuthServer(t) + defer stop() + + boot := clientsFor(t, endpoint, seedBootUser(t, endpoint)) + reader := boot.newUser(t, "fw-reader", allowDoc("network-firewall:DescribeFirewall")) + const prefix = "NetworkFirewall_20201112." + + for _, op := range []string{ + "UpdateFirewallDescription", "UpdateSubnetChangeProtection", "CreateTLSInspectionConfiguration", + "CreateVpcEndpointAssociation", "PutResourcePolicy", "StartFlowCapture", "StartAnalysisReport", + } { + status, body := signedJSONTarget(t, endpoint, reader, "network-firewall", prefix+op, `{}`) + if status != http.StatusForbidden || !strings.Contains(body, "AccessDenied") { + t.Fatalf("%s as a describe-only user: %d %s, want 403 AccessDenied", op, status, body) + } + + status, body = signedJSONTarget(t, endpoint, boot.cred, "network-firewall", prefix+op, `{}`) + if status == http.StatusForbidden { + t.Fatalf("%s as the administrator: %d %s, want the handler's own answer", op, status, body) + } + } + + status, body := signedJSONTarget(t, endpoint, reader, "network-firewall", prefix+"DescribeFirewall", `{"FirewallName":"ghost"}`) + if status == http.StatusForbidden || !strings.Contains(body, "ResourceNotFoundException") { + t.Fatalf("DescribeFirewall as the allowed user: %d %s, want the handler's ResourceNotFoundException", status, body) + } +} diff --git a/docs/coverage/aws/networkfirewall.md b/docs/coverage/aws/networkfirewall.md index 6afd375a9..5a1d27706 100644 --- a/docs/coverage/aws/networkfirewall.md +++ b/docs/coverage/aws/networkfirewall.md @@ -31,6 +31,104 @@ AWS's `networkfirewall` service ยท portable interface `driver.NetworkFirewall` | `UpdateLoggingConfiguration` | | | `UpdateRuleGroup` | | +## Optional capabilities + +Discovered by type assertion; only some providers implement these. + +### AnalysisReports + +AnalysisReports covers the analysis report family. + +| Operation | Description | +| --- | --- | +| `GetAnalysisReport` | GetAnalysisReport returns one report (its results are always empty). | +| `ListAnalysisReports` | | +| `StartAnalysisReport` | | + +### AvailabilityZones + +AvailabilityZones covers the Availability-Zone associations of a transit + +| Operation | Description | +| --- | --- | +| `AssociateAvailabilityZones` | | +| `DisassociateAvailabilityZones` | | + +### FirewallSettings + +FirewallSettings covers the firewall-level setters. + +| Operation | Description | +| --- | --- | +| `UpdateAvailabilityZoneChangeProtection` | | +| `UpdateFirewallAnalysisSettings` | | +| `UpdateFirewallDescription` | | +| `UpdateFirewallPolicyChangeProtection` | | +| `UpdateSubnetChangeProtection` | | + +### FlowOperations + +FlowOperations covers the flow capture / flush family. + +| Operation | Description | +| --- | --- | +| `DescribeFlowOperation` | | +| `ListFlowOperationResults` | ListFlowOperationResults returns the operation and its (always empty, there is no | +| `ListFlowOperations` | | +| `StartFlowCapture` | | +| `StartFlowFlush` | | + +### Metadata + +Metadata covers the read-only metadata/summary operations. + +| Operation | Description | +| --- | --- | +| `DescribeFirewallMetadata` | | +| `DescribeRuleGroupMetadata` | | +| `DescribeRuleGroupSummary` | | + +### ResourcePolicies + +ResourcePolicies covers the resource-sharing IAM policies attached to a rule + +| Operation | Description | +| --- | --- | +| `DeleteResourcePolicy` | | +| `DescribeResourcePolicy` | | +| `PutResourcePolicy` | | + +### TLSInspection + +TLSInspection covers the TLS inspection configuration family. + +| Operation | Description | +| --- | --- | +| `CreateTLSInspectionConfiguration` | | +| `DeleteTLSInspectionConfiguration` | | +| `DescribeTLSInspectionConfiguration` | | +| `ListTLSInspectionConfigurations` | | +| `UpdateTLSInspectionConfiguration` | | + +### VPCEndpointAssociations + +VPCEndpointAssociations covers the VPC endpoint association family. + +| Operation | Description | +| --- | --- | +| `CreateVpcEndpointAssociation` | | +| `DeleteVpcEndpointAssociation` | | +| `DescribeVpcEndpointAssociation` | | +| `ListVpcEndpointAssociations` | | + ## Not in scope -_Not documented yet. See the [emulator boundary](../../../README.md) for cloudemu-wide non-goals._ +- Not implemented (the operations answer `InvalidRequestException: unknown operation`): the proxy family (`CreateProxy`, `CreateProxyConfiguration`, `CreateProxyRuleGroup`, `CreateProxyRules`, the matching describe, update, delete and list operations, `AttachRuleGroupsToProxyConfiguration`, `DetachRuleGroupsFromProxyConfiguration`, `UpdateProxyRulePriorities`, `UpdateProxyRuleGroupPriorities`), the container association family (`CreateContainerAssociation` and its describe, update, delete and list operations), the transit gateway attachment operations (`AcceptNetworkFirewallTransitGatewayAttachment`, `RejectNetworkFirewallTransitGatewayAttachment`, `DeleteNetworkFirewallTransitGatewayAttachment`) and `UpdateFirewallEncryptionConfiguration`. `EncryptionConfiguration` on create and update requests is accepted and ignored. +- There is no packet data plane. Flow capture and flush operations are accepted and complete (immediately, or after the settle window under `--async-settle`) but their results list no flows. Analysis reports complete with no results. Nothing is published to the `AWS/NetworkFirewall` CloudWatch namespace, and the logging configuration is validated and stored but no alert, flow or TLS log is delivered to S3, CloudWatch Logs or Kinesis Data Firehose. +- Checks that need another service are not made: the VPC, subnet and Availability Zone ids a firewall or VPC endpoint association names are syntax-checked only, and the certificates, certificate authorities, KMS keys, log destinations and IAM principals named in TLS inspection configurations, logging configurations and resource policies are not looked up. Resource policies are validated (JSON, allowed actions per resource kind) and stored but never evaluated; sharing through Resource Access Manager is not modeled. +- Availability Zones are synthesized. A VPC firewall gets one zone per subnet in the order the subnets were added (`a`, `b`, ...) and a VPC endpoint association gets a zone derived from its subnet id; the real zone of a subnet is not known. +- A transit gateway-attached firewall can be created, described and have Availability Zones associated and disassociated, but no transit gateway attachment is created, so its status never reports a transit gateway attachment sync state. +- Firewalls, policies, rule groups and TLS inspection configurations are `READY` or `ACTIVE` as soon as they are created; there is no `PROVISIONING` period. `DryRun` and `AnalyzeRuleGroup` on create and update requests are accepted and ignored, so a dry run really makes the change and no rule group analysis results are produced. +- Rule content is stored and returned byte for byte. Only the parts needed for capacity and summaries are read: stateful rules (one unit per rule in `RulesString`, `StatefulRules` and `RulesSourceList` targets) and stateless rules (the product of the element counts of the match settings, as the CreateRuleGroup reference describes). Suricata syntax, rule variables and reference sets are not validated, and a rule group whose rules need more than its `Capacity` is rejected with `InvalidRequestException` (the exception real AWS uses for this is unconfirmed). +- Behaviours the AWS reference does not state were chosen conservatively and are unconfirmed against the live service: a duplicate name answers `InvalidRequestException` (the one exception every Create operation models); deleting a firewall that still has VPC endpoint associations is refused with `InvalidOperationException`; describing or deleting a resource policy that does not exist answers `ResourceNotFoundException`; `DescribeRuleGroupSummary` on a stateless rule group answers `InvalidRequestException` and reports only the options named in the rule group's `SummaryConfiguration`; tagging a resource does not change its update token; a request that gives both a name and an ARN uses the name. +- List operations take `MaxResults` (1 to 100, default 100) and `NextToken`, an opaque offset over results sorted by name, so it is only stable while the list does not change between pages. `ListRuleGroups` filters on `Type`, `Scope` and `ManagedType`; the emulator holds no AWS-managed rule groups, so `Scope=MANAGED` or any `ManagedType` returns an empty list. diff --git a/docs/coverage/coverage.json b/docs/coverage/coverage.json index 2ae466bf1..6b6c3109e 100644 --- a/docs/coverage/coverage.json +++ b/docs/coverage/coverage.json @@ -12531,6 +12531,148 @@ "name": "UpdateRuleGroup" } ], + "optionalCapabilities": [ + { + "name": "AnalysisReports", + "doc": "AnalysisReports covers the analysis report family.", + "operations": [ + { + "name": "GetAnalysisReport", + "doc": "GetAnalysisReport returns one report (its results are always empty)." + }, + { + "name": "ListAnalysisReports" + }, + { + "name": "StartAnalysisReport" + } + ] + }, + { + "name": "AvailabilityZones", + "doc": "AvailabilityZones covers the Availability-Zone associations of a transit", + "operations": [ + { + "name": "AssociateAvailabilityZones" + }, + { + "name": "DisassociateAvailabilityZones" + } + ] + }, + { + "name": "FirewallSettings", + "doc": "FirewallSettings covers the firewall-level setters.", + "operations": [ + { + "name": "UpdateAvailabilityZoneChangeProtection" + }, + { + "name": "UpdateFirewallAnalysisSettings" + }, + { + "name": "UpdateFirewallDescription" + }, + { + "name": "UpdateFirewallPolicyChangeProtection" + }, + { + "name": "UpdateSubnetChangeProtection" + } + ] + }, + { + "name": "FlowOperations", + "doc": "FlowOperations covers the flow capture / flush family.", + "operations": [ + { + "name": "DescribeFlowOperation" + }, + { + "name": "ListFlowOperationResults", + "doc": "ListFlowOperationResults returns the operation and its (always empty, there is no" + }, + { + "name": "ListFlowOperations" + }, + { + "name": "StartFlowCapture" + }, + { + "name": "StartFlowFlush" + } + ] + }, + { + "name": "Metadata", + "doc": "Metadata covers the read-only metadata/summary operations.", + "operations": [ + { + "name": "DescribeFirewallMetadata" + }, + { + "name": "DescribeRuleGroupMetadata" + }, + { + "name": "DescribeRuleGroupSummary" + } + ] + }, + { + "name": "ResourcePolicies", + "doc": "ResourcePolicies covers the resource-sharing IAM policies attached to a rule", + "operations": [ + { + "name": "DeleteResourcePolicy" + }, + { + "name": "DescribeResourcePolicy" + }, + { + "name": "PutResourcePolicy" + } + ] + }, + { + "name": "TLSInspection", + "doc": "TLSInspection covers the TLS inspection configuration family.", + "operations": [ + { + "name": "CreateTLSInspectionConfiguration" + }, + { + "name": "DeleteTLSInspectionConfiguration" + }, + { + "name": "DescribeTLSInspectionConfiguration" + }, + { + "name": "ListTLSInspectionConfigurations" + }, + { + "name": "UpdateTLSInspectionConfiguration" + } + ] + }, + { + "name": "VPCEndpointAssociations", + "doc": "VPCEndpointAssociations covers the VPC endpoint association family.", + "operations": [ + { + "name": "CreateVpcEndpointAssociation" + }, + { + "name": "DeleteVpcEndpointAssociation" + }, + { + "name": "DescribeVpcEndpointAssociation" + }, + { + "name": "ListVpcEndpointAssociations" + } + ] + } + ], "providers": { "aws": "NetworkFirewall" } diff --git a/docs/coverage/nongoals/networkfirewall.md b/docs/coverage/nongoals/networkfirewall.md new file mode 100644 index 000000000..c01c4f30b --- /dev/null +++ b/docs/coverage/nongoals/networkfirewall.md @@ -0,0 +1,9 @@ +- Not implemented (the operations answer `InvalidRequestException: unknown operation`): the proxy family (`CreateProxy`, `CreateProxyConfiguration`, `CreateProxyRuleGroup`, `CreateProxyRules`, the matching describe, update, delete and list operations, `AttachRuleGroupsToProxyConfiguration`, `DetachRuleGroupsFromProxyConfiguration`, `UpdateProxyRulePriorities`, `UpdateProxyRuleGroupPriorities`), the container association family (`CreateContainerAssociation` and its describe, update, delete and list operations), the transit gateway attachment operations (`AcceptNetworkFirewallTransitGatewayAttachment`, `RejectNetworkFirewallTransitGatewayAttachment`, `DeleteNetworkFirewallTransitGatewayAttachment`) and `UpdateFirewallEncryptionConfiguration`. `EncryptionConfiguration` on create and update requests is accepted and ignored. +- There is no packet data plane. Flow capture and flush operations are accepted and complete (immediately, or after the settle window under `--async-settle`) but their results list no flows. Analysis reports complete with no results. Nothing is published to the `AWS/NetworkFirewall` CloudWatch namespace, and the logging configuration is validated and stored but no alert, flow or TLS log is delivered to S3, CloudWatch Logs or Kinesis Data Firehose. +- Checks that need another service are not made: the VPC, subnet and Availability Zone ids a firewall or VPC endpoint association names are syntax-checked only, and the certificates, certificate authorities, KMS keys, log destinations and IAM principals named in TLS inspection configurations, logging configurations and resource policies are not looked up. Resource policies are validated (JSON, allowed actions per resource kind) and stored but never evaluated; sharing through Resource Access Manager is not modeled. +- Availability Zones are synthesized. A VPC firewall gets one zone per subnet in the order the subnets were added (`a`, `b`, ...) and a VPC endpoint association gets a zone derived from its subnet id; the real zone of a subnet is not known. +- A transit gateway-attached firewall can be created, described and have Availability Zones associated and disassociated, but no transit gateway attachment is created, so its status never reports a transit gateway attachment sync state. +- Firewalls, policies, rule groups and TLS inspection configurations are `READY` or `ACTIVE` as soon as they are created; there is no `PROVISIONING` period. `DryRun` and `AnalyzeRuleGroup` on create and update requests are accepted and ignored, so a dry run really makes the change and no rule group analysis results are produced. +- Rule content is stored and returned byte for byte. Only the parts needed for capacity and summaries are read: stateful rules (one unit per rule in `RulesString`, `StatefulRules` and `RulesSourceList` targets) and stateless rules (the product of the element counts of the match settings, as the CreateRuleGroup reference describes). Suricata syntax, rule variables and reference sets are not validated, and a rule group whose rules need more than its `Capacity` is rejected with `InvalidRequestException` (the exception real AWS uses for this is unconfirmed). +- Behaviours the AWS reference does not state were chosen conservatively and are unconfirmed against the live service: a duplicate name answers `InvalidRequestException` (the one exception every Create operation models); deleting a firewall that still has VPC endpoint associations is refused with `InvalidOperationException`; describing or deleting a resource policy that does not exist answers `ResourceNotFoundException`; `DescribeRuleGroupSummary` on a stateless rule group answers `InvalidRequestException` and reports only the options named in the rule group's `SummaryConfiguration`; tagging a resource does not change its update token; a request that gives both a name and an ARN uses the name. +- List operations take `MaxResults` (1 to 100, default 100) and `NextToken`, an opaque offset over results sorted by name, so it is only stable while the list does not change between pages. `ListRuleGroups` filters on `Type`, `Scope` and `ManagedType`; the emulator holds no AWS-managed rule groups, so `Scope=MANAGED` or any `ManagedType` returns an empty list. diff --git a/docs/services.md b/docs/services.md index a52a5315b..6927450ee 100644 --- a/docs/services.md +++ b/docs/services.md @@ -3959,7 +3959,7 @@ delete) is still enforced. | Serverless | 26 | | Networking | 51 | | Networking: AWS-specific (Transit Gateway / VPN / DHCP / prefix lists / egress-only IGW / endpoint services / Client VPN / Traffic Mirroring / Network Insights / VPC Block Public Access / IPAM full incl. discovery/BYOASN/BYOIP/resolver/policy + AWS/IPAM metrics) | 162 | -| Network Firewall: AWS | 20 | +| Network Firewall: AWS | 23 (+30 optional) | | Monitoring | 12 | | IAM | 35 | | DNS | 15 | @@ -4005,7 +4005,7 @@ delete) is still enforced. | Data Integration: AWS Glue | 299 | | Threat Detection: Amazon GuardDuty | 87 | | Streaming: Amazon MSK | 59 | -| **Grand Total** | **2842** (+227 optional) | +| **Grand Total** | **2845** (+257 optional) | Optional operations are capabilities a driver may implement but is not required to; see the sections marked "optional capability". They are counted separately diff --git a/internal/settle/settle.go b/internal/settle/settle.go index dcbffda5a..0a093742a 100644 --- a/internal/settle/settle.go +++ b/internal/settle/settle.go @@ -74,6 +74,8 @@ const ( DefaultBedrockIngestionSettle = 2 * time.Second // Bedrock KB ingestion job IN_PROGRESS->COMPLETE + DefaultFlowOperationSettle = 2 * time.Second // Network Firewall flow operation IN_PROGRESS->COMPLETED + // S3 RestoreObject ongoing-request="true"->"false", by retrieval tier. DefaultRestoreExpeditedSettle = 1 * time.Second DefaultRestoreStandardSettle = 3 * time.Second diff --git a/providers/aws/networkfirewall/analysis_report.go b/providers/aws/networkfirewall/analysis_report.go new file mode 100644 index 000000000..016e3e4e3 --- /dev/null +++ b/providers/aws/networkfirewall/analysis_report.go @@ -0,0 +1,114 @@ +package networkfirewall + +import ( + "context" + "sort" + + cerrors "github.com/stackshy/cloudemu/v2/errors" + "github.com/stackshy/cloudemu/v2/internal/idgen" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +const reportCompleted = "COMPLETED" + +// StartAnalysisReport requests a traffic analysis report. The analysis type has +// to be enabled on the firewall; with no data plane the report has no results. +func (m *Mock) StartAnalysisReport(_ context.Context, firewallName, firewallARN, analysisType string) (*nfdriver.AnalysisReport, error) { + m.mu.Lock() + defer m.mu.Unlock() + + fw, err := m.reportFirewall(firewallName, firewallARN) + if err != nil { + return nil, err + } + + if !oneOf(analysisType, analysisTypes...) { + return nil, invalid("AnalysisType %q is not valid", analysisType) + } + + if !oneOf(analysisType, fw.EnabledAnalysisTypes...) { + return nil, invalid("analysis type %s is not enabled on firewall %q", analysisType, fw.Name) + } + + rep := &nfdriver.AnalysisReport{ + ID: idgen.UUID(), FirewallARN: fw.ARN, AnalysisType: analysisType, + Status: reportCompleted, ReportTime: m.now(), + } + m.analysisReports.Set(rep.ID, rep) + + out := *rep + + return &out, nil +} + +// ListAnalysisReports lists the analysis reports of a firewall, oldest first. +func (m *Mock) ListAnalysisReports( + _ context.Context, firewallName, firewallARN string, opts nfdriver.ListOptions, +) ([]nfdriver.AnalysisReport, string, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + fw, err := m.reportFirewall(firewallName, firewallARN) + if err != nil { + return nil, "", err + } + + var matched []*nfdriver.AnalysisReport + + for _, r := range m.analysisReports.SortedValues() { + if r.FirewallARN == fw.ARN { + matched = append(matched, r) + } + } + + sort.SliceStable(matched, func(i, j int) bool { return matched[i].ReportTime.Before(matched[j].ReportTime) }) + + items, next, err := paginate(matched, opts) + if err != nil { + return nil, "", err + } + + out := make([]nfdriver.AnalysisReport, 0, len(items)) + for _, r := range items { + out = append(out, *r) + } + + return out, next, nil +} + +// GetAnalysisReport returns one analysis report (it never has results). +func (m *Mock) GetAnalysisReport(_ context.Context, firewallName, firewallARN, reportID string) (*nfdriver.AnalysisReport, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + fw, err := m.reportFirewall(firewallName, firewallARN) + if err != nil { + return nil, err + } + + if reportID == "" { + return nil, invalid("AnalysisReportId is required") + } + + rep, ok := m.analysisReports.Get(reportID) + if !ok || rep.FirewallARN != fw.ARN { + return nil, cerrors.Newf(cerrors.NotFound, "analysis report %q not found", reportID) + } + + out := *rep + + return &out, nil +} + +func (m *Mock) reportFirewall(name, arn string) (*nfdriver.Firewall, error) { + if err := requireIdentifier("Firewall", name, arn); err != nil { + return nil, err + } + + fw, ok := m.lookupFirewall(name, arn) + if !ok { + return nil, cerrors.Newf(cerrors.NotFound, "firewall %q not found", nonEmpty(name, arn)) + } + + return fw, nil +} diff --git a/providers/aws/networkfirewall/capacity.go b/providers/aws/networkfirewall/capacity.go new file mode 100644 index 000000000..61573705b --- /dev/null +++ b/providers/aws/networkfirewall/capacity.go @@ -0,0 +1,77 @@ +package networkfirewall + +import ( + "encoding/json" + "strings" +) + +// ruleSource is the part of a rule group payload the emulator reads to work out +// the capacity the rules consume (everything else is stored untouched). +type ruleSource struct { + RulesSource struct { + RulesString string `json:"RulesString"` + StatefulRules []json.RawMessage `json:"StatefulRules"` + RulesSourceList struct { + Targets []string `json:"Targets"` + } `json:"RulesSourceList"` + Stateless struct { + Rules []struct { + RuleDefinition struct { + MatchAttributes map[string][]json.RawMessage `json:"MatchAttributes"` + } `json:"RuleDefinition"` + } `json:"StatelessRules"` + } `json:"StatelessRulesAndCustomActions"` + } `json:"RulesSource"` +} + +// maxRulesStringLen is the AWS limit on a Suricata rules string. +const maxRulesStringLen = 2000000 + +// consumedCapacity validates a rule group payload and returns the capacity units its rules consume, per the AWS +// CreateRuleGroup reference: a stateful rule group needs one unit per rule; a +// stateless rule needs the product of the element counts of its match settings +// (an unset setting counts 1) and the group needs the sum over its rules. +func consumedCapacity(raw json.RawMessage) (int, error) { + if len(raw) == 0 { + return 0, nil + } + + var src ruleSource + if err := json.Unmarshal(raw, &src); err != nil { + return 0, invalid("RuleGroup is not valid: %v", err) + } + + if len(src.RulesSource.RulesString) > maxRulesStringLen { + return 0, invalid("RulesString exceeds %d characters", maxRulesStringLen) + } + + total := len(src.RulesSource.StatefulRules) + len(src.RulesSource.RulesSourceList.Targets) + + for _, line := range strings.Split(src.RulesSource.RulesString, "\n") { + if isRuleLine(line) { + total++ + } + } + + for _, r := range src.RulesSource.Stateless.Rules { + cost := 1 + + for _, elems := range r.RuleDefinition.MatchAttributes { + if len(elems) > 1 { + cost *= len(elems) + } + } + + total += cost + } + + return total, nil +} + +// isRuleLine reports whether a Suricata rules-string line is a rule (not blank +// and not a comment). +func isRuleLine(line string) bool { + t := strings.TrimSpace(line) + + return t != "" && !strings.HasPrefix(t, "#") +} diff --git a/providers/aws/networkfirewall/concurrency_test.go b/providers/aws/networkfirewall/concurrency_test.go new file mode 100644 index 000000000..a483f9b29 --- /dev/null +++ b/providers/aws/networkfirewall/concurrency_test.go @@ -0,0 +1,248 @@ +package networkfirewall + +import ( + "fmt" + "sync" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + cerrors "github.com/stackshy/cloudemu/v2/errors" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +const racers = 50 + +// runRacers calls fn from racers goroutines and counts successes and +// "already exists" losers. +func runRacers(fn func() error) (wins, losers int32) { + var ( + wg sync.WaitGroup + w, l atomic.Int32 + ) + + for i := 0; i < racers; i++ { + wg.Add(1) + + go func() { + defer wg.Done() + + switch err := fn(); { + case err == nil: + w.Add(1) + case cerrors.IsAlreadyExists(err): + l.Add(1) + } + }() + } + + wg.Wait() + + return w.Load(), l.Load() +} + +func TestCreate_50SameName_ExactlyOneWins(t *testing.T) { + m := newMock() + pol := seedPolicy(t, m, "pol-1") + + creates := map[string]func() error{ + "firewall": func() error { + _, err := m.CreateFirewall(bg, nfdriver.CreateFirewallConfig{Name: "fw", PolicyARN: pol.ARN, VPCID: "vpc-1a"}) + return err + }, + "policy": func() error { + _, err := m.CreateFirewallPolicy(bg, refPolicy("same", nil, nil)) + return err + }, + "rule group": func() error { + _, err := m.CreateRuleGroup(bg, nfdriver.CreateRuleGroupConfig{Name: "rg", Type: "STATEFUL", Capacity: 1}) + return err + }, + "tls": func() error { + _, err := m.CreateTLSInspectionConfiguration(bg, nfdriver.CreateTLSInspectionConfig{Name: "tls", Configuration: tlsConfigJSON("c")}) + return err + }, + } + + for name, create := range creates { + t.Run(name, func(t *testing.T) { + wins, losers := runRacers(create) + assert.EqualValues(t, 1, wins) + assert.EqualValues(t, racers-1, losers) + }) + } +} + +func TestRuleGroup_DeleteVsPolicyReference_Race(t *testing.T) { + for round := 0; round < 25; round++ { + m := newMock() + rg := seedRuleGroup(t, m, "rg", "STATEFUL", 5) + pol := seedPolicy(t, m, "pol") + + var wg sync.WaitGroup + + wg.Add(2) + + go func() { + defer wg.Done() + + _, _ = m.UpdateFirewallPolicy(bg, "pol", "", nfdriver.UpdateFirewallPolicyConfig{ + UpdateToken: pol.UpdateToken, StatelessDefaultActions: standardActions, StatelessFragmentDefaultActions: standardActions, + StatefulRuleGroupReferences: []nfdriver.RuleGroupReference{{ResourceARN: rg.ARN}}, + }) + }() + + go func() { + defer wg.Done() + + _, _ = m.DeleteRuleGroup(bg, "rg", "", "STATEFUL") + }() + + wg.Wait() + + // Whatever order won, a policy never points at a deleted rule group. + got, err := m.DescribeFirewallPolicy(bg, "pol", "") + require.NoError(t, err) + + for _, ref := range got.StatefulRuleGroupReferences { + _, err := m.DescribeRuleGroup(bg, "", ref.ResourceARN, "") + assert.NoError(t, err, "round %d: dangling reference", round) + } + } +} + +func TestCreateVsDelete_NoOrphans(t *testing.T) { + for round := 0; round < 25; round++ { + m := newMock() + _, fw := seedStack(t, m) + + var wg sync.WaitGroup + + wg.Add(2) + + go func() { + defer wg.Done() + + _, _ = m.CreateVpcEndpointAssociation(bg, nfdriver.CreateVPCEndpointAssociationConfig{ + FirewallARN: fw.ARN, VPCID: "vpc-2b", SubnetID: "subnet-9", + }) + }() + + go func() { + defer wg.Done() + + _, _ = m.DeleteFirewall(bg, "fw-1", "") + }() + + wg.Wait() + + // Either the association exists and the firewall survived (delete refused), + // or the firewall is gone and no association points at it. + _, fwErr := m.DescribeFirewall(bg, "fw-1", "") + assocs, _, err := m.ListVpcEndpointAssociations(bg, "", nfdriver.ListOptions{}) + require.NoError(t, err) + + if fwErr != nil { + assert.Empty(t, assocs, "round %d: association orphaned by firewall delete", round) + } + } +} + +func TestDeepCopy_MutateReturned_NoAlias(t *testing.T) { + m := newMock() + pol, fw := seedStack(t, m) + + _, err := m.CreateFirewallPolicy(bg, nfdriver.CreateFirewallPolicyConfig{ + Name: "deep", StatelessDefaultActions: []string{"aws:pass"}, StatelessFragmentDefaultActions: standardActions, + Tags: map[string]string{"k": "v"}, Extra: nfdriver.PolicyExtra{StatelessCustomActions: []byte(`[]`)}, + }) + require.NoError(t, err) + + rg, err := m.CreateRuleGroup(bg, nfdriver.CreateRuleGroupConfig{ + Name: "rg", Type: "STATEFUL", Capacity: 5, Rules: rulesString("r1"), Tags: map[string]string{"k": "v"}, + SummaryRuleOptions: []string{"SID"}, + }) + require.NoError(t, err) + + require.NoError(t, m.UpdateLoggingConfiguration(bg, "fw-1", &nfdriver.LoggingConfiguration{ + Destinations: []nfdriver.LogDestinationConfig{s3Dest("FLOW", "b")}, + })) + + var wg sync.WaitGroup + + for i := 0; i < 20; i++ { + wg.Add(2) + + go func() { + defer wg.Done() + + // Mutators scribble on everything they were handed. + got, _ := m.DescribeFirewall(bg, "fw-1", "") + got.SubnetIDs[0] = "scribbled" + got.Tags = map[string]string{"x": "y"} + + p, _ := m.DescribeFirewallPolicy(bg, "deep", "") + p.StatelessDefaultActions[0] = "scribbled" + p.Tags["k"] = "scribbled" + p.Extra.StatelessCustomActions[0] = 'X' + + r, _ := m.DescribeRuleGroup(bg, "rg", "", "STATEFUL") + r.Rules[0] = 'X' + r.Tags["k"] = "scribbled" + r.SummaryRuleOptions[0] = "scribbled" + + l, _ := m.DescribeLoggingConfiguration(bg, "fw-1") + l.Destinations[0].LogDestination["bucketName"] = "scribbled" + }() + + go func() { + defer wg.Done() + + _, _ = m.DescribeFirewall(bg, "fw-1", "") + _, _, _ = m.ListFirewallPolicies(bg, nfdriver.ListOptions{}) + _, _, _ = m.ListRuleGroups(bg, nfdriver.RuleGroupFilter{}, nfdriver.ListOptions{}) + _, _ = m.DescribeLoggingConfiguration(bg, "fw-1") + }() + } + + wg.Wait() + + gotFw, _ := m.DescribeFirewall(bg, "fw-1", "") + assert.Equal(t, []string{"subnet-1"}, gotFw.SubnetIDs) + assert.Empty(t, gotFw.Tags) + + gotPol, _ := m.DescribeFirewallPolicy(bg, "deep", "") + assert.Equal(t, []string{"aws:pass"}, gotPol.StatelessDefaultActions) + assert.Equal(t, map[string]string{"k": "v"}, gotPol.Tags) + assert.Equal(t, "[]", string(gotPol.Extra.StatelessCustomActions)) + + gotRg, _ := m.DescribeRuleGroup(bg, "rg", "", "STATEFUL") + assert.Equal(t, rg.Rules, gotRg.Rules) + assert.Equal(t, map[string]string{"k": "v"}, gotRg.Tags) + assert.Equal(t, []string{"SID"}, gotRg.SummaryRuleOptions) + + gotLog, _ := m.DescribeLoggingConfiguration(bg, "fw-1") + assert.Equal(t, "b", gotLog.Destinations[0].LogDestination["bucketName"]) + + _, _ = pol, fw +} + +func TestCreateFirewall_CallerSliceNotRetained(t *testing.T) { + m := newMock() + pol := seedPolicy(t, m, "pol-1") + + subnets := []string{"subnet-1"} + tags := map[string]string{"a": "b"} + + _, err := m.CreateFirewall(bg, nfdriver.CreateFirewallConfig{Name: "fw", PolicyARN: pol.ARN, VPCID: "vpc-1a", SubnetIDs: subnets, Tags: tags}) + require.NoError(t, err) + + subnets[0] = fmt.Sprint("mutated") + tags["a"] = "mutated" + + got, _ := m.DescribeFirewall(bg, "fw", "") + assert.Equal(t, []string{"subnet-1"}, got.SubnetIDs) + assert.Equal(t, "b", got.Tags["a"]) +} diff --git a/providers/aws/networkfirewall/families_test.go b/providers/aws/networkfirewall/families_test.go new file mode 100644 index 000000000..4b24a7669 --- /dev/null +++ b/providers/aws/networkfirewall/families_test.go @@ -0,0 +1,528 @@ +package networkfirewall + +import ( + "encoding/json" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stackshy/cloudemu/v2/config" + cerrors "github.com/stackshy/cloudemu/v2/errors" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +func tlsConfigJSON(certARNs ...string) json.RawMessage { + certs := make([]map[string]string, 0, len(certARNs)) + for _, a := range certARNs { + certs = append(certs, map[string]string{"ResourceArn": a}) + } + + b, _ := json.Marshal(map[string]any{"ServerCertificateConfigurations": []map[string]any{{"ServerCertificates": certs}}}) + + return b +} + +func policyDoc(actions ...string) string { + b, _ := json.Marshal(map[string]any{ + "Version": "2012-10-17", + "Statement": []map[string]any{{ + "Effect": "Allow", "Principal": map[string]string{"AWS": "arn:aws:iam::111122223333:root"}, + "Action": actions, "Resource": "*", + }}, + }) + + return string(b) +} + +func TestResourcePolicy_PutDescribeDelete_AllTypes(t *testing.T) { + m := newMock() + pol, fw := seedStack(t, m) + rg := seedRuleGroup(t, m, "rg-1", "STATEFUL", 5) + sl := seedRuleGroup(t, m, "rg-sl", "STATELESS", 5) + + cases := map[string]struct{ arn, action string }{ + "rule group": {rg.ARN, "network-firewall:CreateFirewallPolicy"}, + "stateless rule group": {sl.ARN, "network-firewall:ListRuleGroups"}, + "firewall policy": {pol.ARN, "network-firewall:AssociateFirewallPolicy"}, + "firewall": {fw.ARN, "network-firewall:ListFirewalls"}, + } + + for name, c := range cases { + t.Run(name, func(t *testing.T) { + doc := policyDoc(c.action) + require.NoError(t, m.PutResourcePolicy(bg, c.arn, doc)) + + got, err := m.DescribeResourcePolicy(bg, c.arn) + require.NoError(t, err) + assert.JSONEq(t, doc, got) + + require.NoError(t, m.DeleteResourcePolicy(bg, c.arn)) + + _, err = m.DescribeResourcePolicy(bg, c.arn) + assert.True(t, cerrors.IsNotFound(err), "after delete: %v", err) + }) + } +} + +func TestResourcePolicy_Validation(t *testing.T) { + m := newMock() + pol, fw := seedStack(t, m) + + err := m.PutResourcePolicy(bg, pol.ARN, "{not json") + requireException(t, err, nfdriver.ExInvalidResourcePolicy) + + err = m.PutResourcePolicy(bg, pol.ARN, policyDoc("network-firewall:ListFirewalls")) + requireException(t, err, nfdriver.ExInvalidResourcePolicy) + + err = m.PutResourcePolicy(bg, pol.ARN, `{"Version":"2012-10-17","Statement":[]}`) + requireException(t, err, nfdriver.ExInvalidResourcePolicy) + + err = m.PutResourcePolicy(bg, fw.ARN, `{"Statement":[{"Effect":"Allow"}]}`) + requireException(t, err, nfdriver.ExInvalidResourcePolicy) + + err = m.PutResourcePolicy(bg, "arn:aws:network-firewall:us-east-1:000000000000:firewall/ghost", policyDoc("network-firewall:ListFirewalls")) + assert.True(t, cerrors.IsNotFound(err), "%v", err) + + err = m.PutResourcePolicy(bg, "not-an-arn", policyDoc("network-firewall:ListFirewalls")) + assert.True(t, cerrors.IsInvalidArgument(err), "%v", err) + + err = m.PutResourcePolicy(bg, fw.ARN, "") + assert.True(t, cerrors.IsInvalidArgument(err), "%v", err) + + err = m.PutResourcePolicy(bg, fw.ARN, strings.Repeat("x", 395001)) + assert.True(t, cerrors.IsInvalidArgument(err), "%v", err) + + tls, tlsErr := m.CreateTLSInspectionConfiguration(bg, nfdriver.CreateTLSInspectionConfig{Name: "t", Configuration: tlsConfigJSON("c")}) + require.NoError(t, tlsErr) + + err = m.PutResourcePolicy(bg, tls.ARN, policyDoc("network-firewall:ListFirewalls")) + assert.True(t, cerrors.IsInvalidArgument(err), "a TLS configuration cannot be shared: %v", err) +} + +func TestResourcePolicy_RemovedWithResource(t *testing.T) { + m := newMock() + pol := seedPolicy(t, m, "pol-1") + + require.NoError(t, m.PutResourcePolicy(bg, pol.ARN, policyDoc("network-firewall:AssociateFirewallPolicy"))) + _, err := m.DeleteFirewallPolicy(bg, "pol-1", "") + require.NoError(t, err) + + assert.Empty(t, m.resourcePolicies, "no orphaned policy after the resource is deleted") +} + +func TestTLS_CRUD_List_Tagging(t *testing.T) { + m, clock := newClockMock(t) + + created, err := m.CreateTLSInspectionConfiguration(bg, nfdriver.CreateTLSInspectionConfig{ + Name: "tls-1", Description: "d", Configuration: tlsConfigJSON("arn:aws:acm:us-east-1:000000000000:certificate/c1"), + Tags: map[string]string{"a": "b"}, + }) + require.NoError(t, err) + assert.Equal(t, "ACTIVE", created.Status) + assert.Equal(t, []string{"arn:aws:acm:us-east-1:000000000000:certificate/c1"}, created.CertificateARNs) + assert.Regexp(t, uuidPattern, created.UpdateToken) + + clock.Advance(time.Minute) + + updated, err := m.UpdateTLSInspectionConfiguration(bg, "tls-1", "", nfdriver.UpdateTLSInspectionConfig{ + UpdateToken: created.UpdateToken, Description: "d2", Configuration: tlsConfigJSON("c2", "c3"), + }) + require.NoError(t, err) + assert.NotEqual(t, created.UpdateToken, updated.UpdateToken) + assert.True(t, updated.LastModified.After(created.LastModified)) + assert.Len(t, updated.CertificateARNs, 2) + + byARN, err := m.DescribeTLSInspectionConfiguration(bg, "", created.ARN) + require.NoError(t, err) + assert.Equal(t, "d2", byARN.Description) + + require.NoError(t, m.TagResource(bg, created.ARN, map[string]string{"c": "d"})) + + tags, err := m.ListTagsForResource(bg, created.ARN) + require.NoError(t, err) + assert.Equal(t, map[string]string{"a": "b", "c": "d"}, tags) + + items, _, err := m.ListTLSInspectionConfigurations(bg, nfdriver.ListOptions{}) + require.NoError(t, err) + assert.Len(t, items, 1) + + deleted, err := m.DeleteTLSInspectionConfiguration(bg, "tls-1", "") + require.NoError(t, err) + assert.Equal(t, "DELETING", deleted.Status) + + _, err = m.DescribeTLSInspectionConfiguration(bg, "tls-1", "") + assert.True(t, cerrors.IsNotFound(err)) +} + +func TestTLS_Validation(t *testing.T) { + m := newMock() + + cases := map[string]nfdriver.CreateTLSInspectionConfig{ + "no configuration": {Name: "t"}, + "empty configuration": {Name: "t", Configuration: []byte(`{"ServerCertificateConfigurations":[]}`)}, + "malformed": {Name: "t", Configuration: []byte(`{`)}, + "bad name": {Name: "t_1", Configuration: tlsConfigJSON("c")}, + "long description": {Name: "t", Description: strings.Repeat("d", 513), Configuration: tlsConfigJSON("c")}, + } + + for name, cfg := range cases { + t.Run(name, func(t *testing.T) { + _, err := m.CreateTLSInspectionConfiguration(bg, cfg) + assert.True(t, cerrors.IsInvalidArgument(err), "want InvalidArgument, got %v", err) + }) + } + + created, err := m.CreateTLSInspectionConfiguration(bg, nfdriver.CreateTLSInspectionConfig{Name: "t", Configuration: tlsConfigJSON("c")}) + require.NoError(t, err) + + _, err = m.CreateTLSInspectionConfiguration(bg, nfdriver.CreateTLSInspectionConfig{Name: "t", Configuration: tlsConfigJSON("c")}) + assert.True(t, cerrors.IsAlreadyExists(err)) + + _, err = m.UpdateTLSInspectionConfiguration(bg, "t", "", nfdriver.UpdateTLSInspectionConfig{Configuration: tlsConfigJSON("c")}) + assert.True(t, cerrors.IsInvalidArgument(err), "update needs a token: %v", err) + + _, err = m.UpdateTLSInspectionConfiguration(bg, "t", "", nfdriver.UpdateTLSInspectionConfig{ + UpdateToken: "11111111-1111-1111-1111-111111111111", Configuration: tlsConfigJSON("c"), + }) + requireException(t, err, nfdriver.ExInvalidToken) + + _ = created +} + +func TestTLS_InUseByPolicy_BlockedDelete(t *testing.T) { + m := newMock() + + tlsCfg, err := m.CreateTLSInspectionConfiguration(bg, nfdriver.CreateTLSInspectionConfig{Name: "t", Configuration: tlsConfigJSON("c")}) + require.NoError(t, err) + + pol, err := m.CreateFirewallPolicy(bg, nfdriver.CreateFirewallPolicyConfig{ + Name: "p", StatelessDefaultActions: standardActions, StatelessFragmentDefaultActions: standardActions, + TLSInspectionConfigurationARN: tlsCfg.ARN, + }) + require.NoError(t, err) + + got, _ := m.DescribeTLSInspectionConfiguration(bg, "t", "") + assert.Equal(t, 1, got.NumberOfAssociations) + + _, err = m.DeleteTLSInspectionConfiguration(bg, "t", "") + requireException(t, err, nfdriver.ExInvalidOperation) + + _, err = m.DeleteFirewallPolicy(bg, pol.Name, "") + require.NoError(t, err) + + _, err = m.DeleteTLSInspectionConfiguration(bg, "t", "") + require.NoError(t, err) +} + +func TestTLS_NoPrivateMaterialInResponse(t *testing.T) { + m := newMock() + + cfg := []byte(`{"ServerCertificateConfigurations":[{"CertificateAuthorityArn":"arn:aws:acm-pca:us-east-1:000000000000:certificate-authority/ca",` + + `"ServerCertificates":[{"ResourceArn":"arn:aws:acm:us-east-1:000000000000:certificate/c1"}]}]}`) + + got, err := m.CreateTLSInspectionConfiguration(bg, nfdriver.CreateTLSInspectionConfig{Name: "t", Configuration: cfg}) + require.NoError(t, err) + + // Only ARNs are stored and echoed; there is no key or certificate body to leak. + assert.NotContains(t, string(got.Configuration), "PRIVATE KEY") + assert.Equal(t, []string{"arn:aws:acm:us-east-1:000000000000:certificate/c1"}, got.CertificateARNs) +} + +func vpcAssociation(t *testing.T, m *Mock, firewallARN, subnet string) *nfdriver.VPCEndpointAssociation { + t.Helper() + + a, err := m.CreateVpcEndpointAssociation(bg, nfdriver.CreateVPCEndpointAssociationConfig{ + FirewallARN: firewallARN, VPCID: "vpc-2b", SubnetID: subnet, Description: "extra", + }) + require.NoError(t, err) + + return a +} + +func TestVPCEndpointAssociation_CRUD_List_FilterByFirewall(t *testing.T) { + m := newMock() + pol, fw := seedStack(t, m) + other := seedFirewall(t, m, "fw-2", pol.ARN) + + a1 := vpcAssociation(t, m, fw.ARN, "subnet-a") + vpcAssociation(t, m, other.ARN, "subnet-b") + + assert.Equal(t, "READY", a1.Status) + assert.NotEmpty(t, a1.AvailabilityZone) + + got, err := m.DescribeVpcEndpointAssociation(bg, a1.ARN) + require.NoError(t, err) + assert.Equal(t, a1.ID, got.ID) + + again, _ := m.DescribeVpcEndpointAssociation(bg, a1.ARN) + assert.Equal(t, got.AvailabilityZone, again.AvailabilityZone, "stable across reads") + + all, _, err := m.ListVpcEndpointAssociations(bg, "", nfdriver.ListOptions{}) + require.NoError(t, err) + assert.Len(t, all, 2) + + mine, _, err := m.ListVpcEndpointAssociations(bg, fw.ARN, nfdriver.ListOptions{}) + require.NoError(t, err) + require.Len(t, mine, 1) + assert.Equal(t, a1.ARN, mine[0].ARN) + + fwNow, _ := m.DescribeFirewall(bg, "fw-1", "") + assert.Equal(t, 1, fwNow.NumberOfAssociations) + + require.NoError(t, m.TagResource(bg, a1.ARN, map[string]string{"k": "v"})) + + deleted, err := m.DeleteVpcEndpointAssociation(bg, a1.ARN) + require.NoError(t, err) + assert.Equal(t, "DELETING", deleted.Status) + + _, err = m.DescribeVpcEndpointAssociation(bg, a1.ARN) + assert.True(t, cerrors.IsNotFound(err)) +} + +func TestVPCEndpointAssociation_Validation(t *testing.T) { + m := newMock() + _, fw := seedStack(t, m) + + cases := map[string]nfdriver.CreateVPCEndpointAssociationConfig{ + "bad vpc": {FirewallARN: fw.ARN, VPCID: "nope", SubnetID: "s"}, + "no subnet": {FirewallARN: fw.ARN, VPCID: "vpc-2b"}, + "bad ip type": {FirewallARN: fw.ARN, VPCID: "vpc-2b", SubnetID: "s", IPAddressType: "IPV5"}, + "malformed arn": {FirewallARN: "x", VPCID: "vpc-2b", SubnetID: "s"}, + "long description": {FirewallARN: fw.ARN, VPCID: "vpc-2b", SubnetID: "s", Description: strings.Repeat("d", 513)}, + } + + for name, cfg := range cases { + t.Run(name, func(t *testing.T) { + _, err := m.CreateVpcEndpointAssociation(bg, cfg) + assert.True(t, cerrors.IsInvalidArgument(err), "want InvalidArgument, got %v", err) + }) + } + + _, err := m.CreateVpcEndpointAssociation(bg, nfdriver.CreateVPCEndpointAssociationConfig{ + FirewallARN: "arn:aws:network-firewall:us-east-1:000000000000:firewall/ghost", VPCID: "vpc-2b", SubnetID: "s", + }) + assert.True(t, cerrors.IsNotFound(err), "%v", err) +} + +func TestDeleteFirewall_WithAssociations_Blocked(t *testing.T) { + m := newMock() + _, fw := seedStack(t, m) + + a := vpcAssociation(t, m, fw.ARN, "subnet-a") + + _, err := m.DeleteFirewall(bg, "fw-1", "") + requireException(t, err, nfdriver.ExInvalidOperation) + + _, err = m.DeleteVpcEndpointAssociation(bg, a.ARN) + require.NoError(t, err) + + _, err = m.DeleteFirewall(bg, "fw-1", "") + require.NoError(t, err) +} + +func TestMetadata_Firewall_RuleGroup(t *testing.T) { + m, _ := newClockMock(t) + pol, fw := seedStack(t, m) + rg := seedRuleGroup(t, m, "rg-1", "STATEFUL", 7) + + meta, err := m.DescribeFirewallMetadata(bg, fw.ARN) + require.NoError(t, err) + assert.Equal(t, fw.ARN, meta.FirewallARN) + assert.Equal(t, pol.ARN, meta.PolicyARN) + assert.Equal(t, "READY", meta.Status) + assert.Equal(t, []string{"us-east-1a"}, meta.AvailabilityZones) + + _, err = m.DescribeFirewallMetadata(bg, "arn:aws:network-firewall:us-east-1:000000000000:firewall/ghost") + assert.True(t, cerrors.IsNotFound(err)) + + got, err := m.DescribeRuleGroupMetadata(bg, "", rg.ARN, "") + require.NoError(t, err) + assert.Equal(t, 7, got.Capacity) +} + +func TestRuleGroupSummary_ParsesMsgSIDMetadata(t *testing.T) { + m := newMock() + + _, err := m.CreateRuleGroup(bg, nfdriver.CreateRuleGroupConfig{ + Name: "rg", Type: "STATEFUL", Capacity: 10, SummaryRuleOptions: []string{"MSG", "SID", "METADATA"}, + Rules: rulesString( + `# a comment`, + `alert tcp any any -> any 80 (msg:"web hit"; metadata:author tester; sid:100;)`, + `drop udp any any -> any 53 (msg:"dns"; sid:101;)`), + }) + require.NoError(t, err) + + _, sums, err := m.DescribeRuleGroupSummary(bg, "rg", "", "STATEFUL") + require.NoError(t, err) + require.Len(t, sums, 2) + assert.Equal(t, nfdriver.RuleSummary{Msg: "web hit", SID: "100", Metadata: "author tester"}, sums[0]) + assert.Equal(t, nfdriver.RuleSummary{Msg: "dns", SID: "101"}, sums[1]) + + // Only the options named in SummaryConfiguration are populated. + _, err = m.CreateRuleGroup(bg, nfdriver.CreateRuleGroupConfig{ + Name: "rg2", Type: "STATEFUL", Capacity: 10, SummaryRuleOptions: []string{"SID"}, + Rules: rulesString(`alert tcp any any -> any 80 (msg:"web hit"; sid:7;)`), + }) + require.NoError(t, err) + + _, sums, err = m.DescribeRuleGroupSummary(bg, "rg2", "", "STATEFUL") + require.NoError(t, err) + assert.Equal(t, []nfdriver.RuleSummary{{SID: "7"}}, sums) +} + +func TestRuleGroupSummary_Stateless_InvalidRequest(t *testing.T) { + m := newMock() + seedRuleGroup(t, m, "sl", "STATELESS", 3) + + _, _, err := m.DescribeRuleGroupSummary(bg, "sl", "", "STATELESS") + assert.True(t, cerrors.IsInvalidArgument(err), "%v", err) +} + +func TestFlowOperations_StartDescribeListResults(t *testing.T) { + m, clock := newClockMock(t) + _, fw := seedStack(t, m) + scope := nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"} + + capture, err := m.StartFlowCapture(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}) + require.NoError(t, err) + assert.Regexp(t, uuidPattern, capture.ID) + assert.Equal(t, "COMPLETED", capture.Status) + assert.Equal(t, "FLOW_CAPTURE", capture.Type) + + clock.Advance(time.Second) + + flush, err := m.StartFlowFlush(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}) + require.NoError(t, err) + assert.Equal(t, "FLOW_FLUSH", flush.Type) + + got, err := m.DescribeFlowOperation(bg, scope, capture.ID) + require.NoError(t, err) + assert.Equal(t, capture.RequestedAt, got.RequestedAt, "timestamp is stable") + + all, _, err := m.ListFlowOperations(bg, scope, "", nfdriver.ListOptions{}) + require.NoError(t, err) + require.Len(t, all, 2) + assert.Equal(t, capture.ID, all[0].ID, "oldest first") + + onlyFlush, _, err := m.ListFlowOperations(bg, scope, "FLOW_FLUSH", nfdriver.ListOptions{}) + require.NoError(t, err) + require.Len(t, onlyFlush, 1) + assert.Equal(t, flush.ID, onlyFlush[0].ID) + + op, next, err := m.ListFlowOperationResults(bg, scope, capture.ID, nfdriver.ListOptions{}) + require.NoError(t, err) + assert.Equal(t, capture.ID, op.ID) + assert.Empty(t, next, "no data plane, so no flows") +} + +func TestFlowOperations_Validation(t *testing.T) { + m := newMock() + pol, fw := seedStack(t, m) + assoc := vpcAssociation(t, m, fw.ARN, "subnet-a") + other := seedFirewall(t, m, "fw-2", pol.ARN) + + _, err := m.StartFlowCapture(bg, nfdriver.FlowOperationRequest{FirewallARN: "arn:aws:network-firewall:us-east-1:000000000000:firewall/ghost", AvailabilityZone: "us-east-1a"}) + assert.True(t, cerrors.IsNotFound(err), "%v", err) + + _, err = m.StartFlowCapture(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN}) + assert.True(t, cerrors.IsInvalidArgument(err), "no endpoint selector: %v", err) + + _, err = m.StartFlowCapture(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: "eu-west-1a"}) + assert.True(t, cerrors.IsInvalidArgument(err), "zone without an endpoint: %v", err) + + _, err = m.StartFlowCapture(bg, nfdriver.FlowOperationRequest{FirewallARN: other.ARN, VPCEndpointAssociationARN: assoc.ARN}) + assert.True(t, cerrors.IsInvalidArgument(err), "association of another firewall: %v", err) + + neg := int32(-1) + _, err = m.StartFlowFlush(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a", MinimumFlowAgeSeconds: &neg}) + assert.True(t, cerrors.IsInvalidArgument(err), "%v", err) + + _, _, err = m.ListFlowOperations(bg, nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}, "BOGUS", nfdriver.ListOptions{}) + assert.True(t, cerrors.IsInvalidArgument(err), "%v", err) + + _, err = m.DescribeFlowOperation(bg, nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}, "no-such-op") + assert.True(t, cerrors.IsNotFound(err), "%v", err) + + ok, err := m.StartFlowCapture(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, VPCEndpointAssociationARN: assoc.ARN}) + require.NoError(t, err) + + _, err = m.DescribeFlowOperation(bg, nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}, ok.ID) + assert.True(t, cerrors.IsNotFound(err), "an operation of another endpoint is not visible: %v", err) +} + +func TestFlowOperations_AsyncSettle(t *testing.T) { + clock := config.NewFakeClock(time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)) + m := New(config.NewOptions(config.WithClock(clock), config.WithAsyncSettle())) + _, fw := seedStack(t, m) + + op, err := m.StartFlowFlush(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}) + require.NoError(t, err) + assert.Equal(t, "IN_PROGRESS", op.Status) + + clock.Advance(10 * time.Second) + + got, err := m.DescribeFlowOperation(bg, nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}, op.ID) + require.NoError(t, err) + assert.Equal(t, "COMPLETED", got.Status) +} + +func TestAnalysisReport_Start_List_Get(t *testing.T) { + m, clock := newClockMock(t) + _, fw := seedStack(t, m) + + _, err := m.UpdateFirewallAnalysisSettings(bg, "fw-1", []string{"TLS_SNI", "HTTP_HOST"}, "") + require.NoError(t, err) + + r1, err := m.StartAnalysisReport(bg, "fw-1", "", "TLS_SNI") + require.NoError(t, err) + assert.Equal(t, "COMPLETED", r1.Status) + + clock.Advance(time.Minute) + + r2, err := m.StartAnalysisReport(bg, "", fw.ARN, "HTTP_HOST") + require.NoError(t, err) + + list, _, err := m.ListAnalysisReports(bg, "fw-1", "", nfdriver.ListOptions{}) + require.NoError(t, err) + require.Len(t, list, 2) + assert.Equal(t, r1.ID, list[0].ID) + + got, err := m.GetAnalysisReport(bg, "fw-1", "", r2.ID) + require.NoError(t, err) + assert.Equal(t, "HTTP_HOST", got.AnalysisType) + + _, err = m.GetAnalysisReport(bg, "fw-1", "", "ghost") + assert.True(t, cerrors.IsNotFound(err)) +} + +func TestAnalysisReport_TypeNotEnabled(t *testing.T) { + m := newMock() + seedStack(t, m) + + _, err := m.StartAnalysisReport(bg, "fw-1", "", "TLS_SNI") + assert.True(t, cerrors.IsInvalidArgument(err), "analysis not enabled: %v", err) + + _, err = m.UpdateFirewallAnalysisSettings(bg, "fw-1", []string{"NOPE"}, "") + assert.True(t, cerrors.IsInvalidArgument(err), "%v", err) + + _, err = m.StartAnalysisReport(bg, "fw-1", "", "BOGUS") + assert.True(t, cerrors.IsInvalidArgument(err), "%v", err) +} + +func TestFlowAndReportOps_UnknownFirewall(t *testing.T) { + m := newMock() + + _, err := m.StartAnalysisReport(bg, "ghost", "", "TLS_SNI") + assert.True(t, cerrors.IsNotFound(err), "%v", err) + + _, _, err = m.ListAnalysisReports(bg, "ghost", "", nfdriver.ListOptions{}) + assert.True(t, cerrors.IsNotFound(err), "%v", err) + + _, err = m.StartFlowFlush(bg, nfdriver.FlowOperationRequest{ + FirewallARN: "arn:aws:network-firewall:us-east-1:000000000000:firewall/ghost", AvailabilityZone: "a", + }) + assert.True(t, cerrors.IsNotFound(err), "%v", err) +} diff --git a/providers/aws/networkfirewall/firewall.go b/providers/aws/networkfirewall/firewall.go new file mode 100644 index 000000000..1e847f867 --- /dev/null +++ b/providers/aws/networkfirewall/firewall.go @@ -0,0 +1,557 @@ +package networkfirewall + +import ( + "context" + + cerrors "github.com/stackshy/cloudemu/v2/errors" + "github.com/stackshy/cloudemu/v2/internal/idgen" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +// Enum values copied verbatim from the AWS SDK (networkfirewall types). +// +//nolint:gochecknoglobals // immutable enum value sets. +var ( + analysisTypes = []string{"TLS_SNI", "HTTP_HOST"} + ipAddressType = []string{"DUALSTACK", "IPV4", "IPV6"} +) + +//nolint:gocritic // cfg matches the driver signature. +func (m *Mock) CreateFirewall(_ context.Context, cfg nfdriver.CreateFirewallConfig) (*nfdriver.Firewall, error) { + m.mu.Lock() + defer m.mu.Unlock() + + if err := m.validateCreateFirewall(&cfg); err != nil { + return nil, err + } + + fw := &nfdriver.Firewall{ + Name: cfg.Name, + ARN: m.arn("firewall", cfg.Name), + ID: idgen.GenerateID(""), + PolicyARN: cfg.PolicyARN, + VPCID: cfg.VPCID, + SubnetIDs: cloneStrings(cfg.SubnetIDs), + AvailabilityZones: cloneStrings(cfg.AvailabilityZones), + TransitGatewayID: cfg.TransitGatewayID, + Description: cfg.Description, + DeleteProtection: cfg.DeleteProtection, + SubnetChangeProtection: cfg.SubnetChangeProtection, + FirewallPolicyChangeProtection: cfg.FirewallPolicyChangeProtection, + AvailabilityZoneChangeProtection: cfg.AvailabilityZoneChangeProtection, + EnabledAnalysisTypes: cloneStrings(cfg.EnabledAnalysisTypes), + Status: statusReady, + UpdateToken: newToken(), + Tags: copyTags(cfg.Tags), + } + if !m.firewalls.SetIfAbsent(cfg.Name, fw) { + return nil, cerrors.Newf(cerrors.AlreadyExists, "firewall %q already exists", cfg.Name) + } + + return m.outFirewall(fw), nil +} + +func (m *Mock) validateCreateFirewall(cfg *nfdriver.CreateFirewallConfig) error { + if err := validateName("FirewallName", cfg.Name); err != nil { + return err + } + + if err := validateDescription(cfg.Description); err != nil { + return err + } + + if err := validateTags(cfg.Tags); err != nil { + return err + } + + if err := validateARN("FirewallPolicyArn", cfg.PolicyARN); err != nil { + return err + } + + if !m.policyExists(cfg.PolicyARN) { + return invalid("firewall policy %q not found", cfg.PolicyARN) + } + + if err := validateFirewallPlacement(cfg); err != nil { + return err + } + + for _, t := range cfg.EnabledAnalysisTypes { + if !oneOf(t, analysisTypes...) { + return invalid("EnabledAnalysisTypes value %q is not valid", t) + } + } + + if m.firewalls.Has(cfg.Name) { + return cerrors.Newf(cerrors.AlreadyExists, "firewall %q already exists", cfg.Name) + } + + return nil +} + +// validateFirewallPlacement checks where the firewall lives: a VPC (VpcId plus +// subnets) or a transit gateway (TransitGatewayId plus Availability Zones). +func validateFirewallPlacement(cfg *nfdriver.CreateFirewallConfig) error { + if cfg.TransitGatewayID != "" { + if cfg.VPCID != "" || len(cfg.SubnetIDs) > 0 { + return invalid("a transit gateway-attached firewall takes AvailabilityZoneMappings, not VpcId or SubnetMappings") + } + + if len(cfg.AvailabilityZones) == 0 { + return invalid("AvailabilityZoneMappings is required for a transit gateway-attached firewall") + } + + return nil + } + + if len(cfg.AvailabilityZones) > 0 { + return invalid("AvailabilityZoneMappings is only valid with TransitGatewayId") + } + + if cfg.VPCID == "" { + return invalid("VpcId is required") + } + + return validateVPCID(cfg.VPCID) +} + +func (m *Mock) DescribeFirewall(_ context.Context, name, arn string) (*nfdriver.Firewall, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + if err := requireIdentifier("Firewall", name, arn); err != nil { + return nil, err + } + + fw, ok := m.lookupFirewall(name, arn) + if !ok { + return nil, cerrors.Newf(cerrors.NotFound, "firewall %q not found", nonEmpty(name, arn)) + } + + return m.outFirewall(fw), nil +} + +func (m *Mock) DeleteFirewall(_ context.Context, name, arn string) (*nfdriver.Firewall, error) { + m.mu.Lock() + defer m.mu.Unlock() + + if err := requireIdentifier("Firewall", name, arn); err != nil { + return nil, err + } + + fw, ok := m.lookupFirewall(name, arn) + if !ok { + return nil, cerrors.Newf(cerrors.NotFound, "firewall %q not found", nonEmpty(name, arn)) + } + + if fw.DeleteProtection { + return nil, nfdriver.InvalidOperation("firewall %q has delete protection enabled", fw.Name) + } + + if n := m.associationCount(fw.ARN); n > 0 { + return nil, nfdriver.InvalidOperation("firewall %q still has %d VPC endpoint association(s)", fw.Name, n) + } + + out := m.outFirewall(fw) + out.Status = statusDeleting + + m.firewalls.Delete(fw.Name) + m.dropFirewallState(fw) + + return out, nil +} + +// dropFirewallState removes everything keyed by a deleted firewall so no entry +// is orphaned: logging, resource policy, flow operations and analysis reports. +func (m *Mock) dropFirewallState(fw *nfdriver.Firewall) { + delete(m.logging, fw.Name) + delete(m.resourcePolicies, fw.ARN) + + for id, op := range m.flowOperations.All() { + if op.FirewallARN == fw.ARN { + m.flowOperations.Delete(id) + } + } + + for id, rep := range m.analysisReports.All() { + if rep.FirewallARN == fw.ARN { + m.analysisReports.Delete(id) + } + } +} + +func (m *Mock) ListFirewalls(_ context.Context, vpcIDs []string, opts nfdriver.ListOptions) ([]nfdriver.Firewall, string, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + for _, v := range vpcIDs { + if err := validateVPCID(v); err != nil { + return nil, "", err + } + } + + var matched []*nfdriver.Firewall + + for _, f := range m.firewalls.SortedValues() { + if len(vpcIDs) == 0 || oneOf(f.VPCID, vpcIDs...) { + matched = append(matched, f) + } + } + + items, next, err := paginate(matched, opts) + if err != nil { + return nil, "", err + } + + out := make([]nfdriver.Firewall, 0, len(items)) + for _, f := range items { + out = append(out, *m.outFirewall(f)) + } + + return out, next, nil +} + +func (m *Mock) lookupFirewall(name, arn string) (*nfdriver.Firewall, bool) { + if name != "" { + return m.firewalls.Get(name) + } + + for _, f := range m.firewalls.SortedValues() { + if f.ARN == arn { + return f, true + } + } + + return nil, false +} + +// outFirewall returns a deep copy of the stored firewall with its computed +// fields filled in. +func (m *Mock) outFirewall(f *nfdriver.Firewall) *nfdriver.Firewall { + out := *f + out.SubnetIDs = cloneStrings(f.SubnetIDs) + out.AvailabilityZones = cloneStrings(f.AvailabilityZones) + out.EnabledAnalysisTypes = cloneStrings(f.EnabledAnalysisTypes) + out.Tags = copyTags(f.Tags) + out.NumberOfAssociations = m.associationCount(f.ARN) + + return &out +} + +// mutateFirewall runs one update on a firewall as a single critical section: +// existence, the optimistic-lock token (optional: "" is an unconditional +// update), the change itself, then the token rotation. +func (m *Mock) mutateFirewall(name, token string, change func(*nfdriver.Firewall) error) (*nfdriver.Firewall, error) { + m.mu.Lock() + defer m.mu.Unlock() + + fw, err := m.firewallForUpdate(name, token) + if err != nil { + return nil, err + } + + if err := change(fw); err != nil { + return nil, err + } + + fw.UpdateToken = newToken() + + return m.outFirewall(fw), nil +} + +func (m *Mock) firewallForUpdate(name, token string) (*nfdriver.Firewall, error) { + if err := validateName("FirewallName", name); err != nil { + return nil, err + } + + fw, ok := m.firewalls.Get(name) + if !ok { + return nil, cerrors.Newf(cerrors.NotFound, "firewall %q not found", name) + } + + if err := checkToken(fw.UpdateToken, token); err != nil { + return nil, err + } + + return fw, nil +} + +// AssociateFirewallPolicy attaches a firewall policy to a firewall. +func (m *Mock) AssociateFirewallPolicy(_ context.Context, firewallName, policyARN, updateToken string) (*nfdriver.Firewall, error) { + return m.mutateFirewall(firewallName, updateToken, func(fw *nfdriver.Firewall) error { + if fw.FirewallPolicyChangeProtection { + return nfdriver.InvalidOperation("firewall %q has firewall policy change protection enabled", fw.Name) + } + + if err := validateARN("FirewallPolicyArn", policyARN); err != nil { + return err + } + + if !m.policyExists(policyARN) { + return invalid("firewall policy %q not found", policyARN) + } + + fw.PolicyARN = policyARN + + return nil + }) +} + +// AssociateSubnets adds subnet mappings to a VPC-attached firewall. +func (m *Mock) AssociateSubnets( + _ context.Context, + firewallName string, + subnetIDs []string, + updateToken string, +) (*nfdriver.Firewall, error) { + return m.mutateFirewall(firewallName, updateToken, func(fw *nfdriver.Firewall) error { + if err := subnetOpAllowed(fw); err != nil { + return err + } + + if len(subnetIDs) == 0 { + return invalid("SubnetMappings is required") + } + + seen := make(map[string]bool, len(fw.SubnetIDs)) + for _, s := range fw.SubnetIDs { + seen[s] = true + } + + for _, s := range subnetIDs { + if !seen[s] { + fw.SubnetIDs = append(fw.SubnetIDs, s) + seen[s] = true + } + } + + return nil + }) +} + +// DisassociateSubnets removes subnet mappings from a VPC-attached firewall. +func (m *Mock) DisassociateSubnets( + _ context.Context, + firewallName string, + subnetIDs []string, + updateToken string, +) (*nfdriver.Firewall, error) { + return m.mutateFirewall(firewallName, updateToken, func(fw *nfdriver.Firewall) error { + if err := subnetOpAllowed(fw); err != nil { + return err + } + + if len(subnetIDs) == 0 { + return invalid("SubnetIds is required") + } + + remove := make(map[string]bool, len(subnetIDs)) + for _, s := range subnetIDs { + remove[s] = true + } + + kept := fw.SubnetIDs[:0:0] + + for _, s := range fw.SubnetIDs { + if !remove[s] { + kept = append(kept, s) + } + } + + fw.SubnetIDs = kept + + return nil + }) +} + +// subnetOpAllowed gates the subnet associations: a transit gateway-attached +// firewall has no subnets, and a protected firewall refuses changes. +func subnetOpAllowed(fw *nfdriver.Firewall) error { + if fw.TransitGatewayID != "" { + return nfdriver.InvalidOperation("firewall %q is transit gateway-attached; use the Availability Zone operations", fw.Name) + } + + if fw.SubnetChangeProtection { + return nfdriver.InvalidOperation("firewall %q has subnet change protection enabled", fw.Name) + } + + return nil +} + +// UpdateFirewallDeleteProtection toggles delete protection on a firewall. +func (m *Mock) UpdateFirewallDeleteProtection( + _ context.Context, + firewallName string, + enabled bool, + updateToken string, +) (*nfdriver.Firewall, error) { + return m.mutateFirewall(firewallName, updateToken, func(fw *nfdriver.Firewall) error { + fw.DeleteProtection = enabled + + return nil + }) +} + +// UpdateFirewallDescription sets (or, when empty, clears) the description. +func (m *Mock) UpdateFirewallDescription(_ context.Context, firewallName, description, updateToken string) (*nfdriver.Firewall, error) { + return m.mutateFirewall(firewallName, updateToken, func(fw *nfdriver.Firewall) error { + if err := validateDescription(description); err != nil { + return err + } + + fw.Description = description + + return nil + }) +} + +// UpdateSubnetChangeProtection toggles the subnet change protection flag. +func (m *Mock) UpdateSubnetChangeProtection( + _ context.Context, + firewallName string, + enabled bool, + updateToken string, +) (*nfdriver.Firewall, error) { + return m.mutateFirewall(firewallName, updateToken, func(fw *nfdriver.Firewall) error { + fw.SubnetChangeProtection = enabled + + return nil + }) +} + +// UpdateFirewallPolicyChangeProtection toggles the policy change protection flag. +func (m *Mock) UpdateFirewallPolicyChangeProtection( + _ context.Context, + firewallName string, + enabled bool, + updateToken string, +) (*nfdriver.Firewall, error) { + return m.mutateFirewall(firewallName, updateToken, func(fw *nfdriver.Firewall) error { + fw.FirewallPolicyChangeProtection = enabled + + return nil + }) +} + +// UpdateAvailabilityZoneChangeProtection toggles the AZ change protection flag. +func (m *Mock) UpdateAvailabilityZoneChangeProtection( + _ context.Context, + firewallName string, + enabled bool, + updateToken string, +) (*nfdriver.Firewall, error) { + return m.mutateFirewall(firewallName, updateToken, func(fw *nfdriver.Firewall) error { + fw.AvailabilityZoneChangeProtection = enabled + + return nil + }) +} + +// UpdateFirewallAnalysisSettings sets the analysis types enabled on a firewall +// (an empty list disables analysis). +func (m *Mock) UpdateFirewallAnalysisSettings( + _ context.Context, + firewallName string, + types []string, + updateToken string, +) (*nfdriver.Firewall, error) { + return m.mutateFirewall(firewallName, updateToken, func(fw *nfdriver.Firewall) error { + for _, t := range types { + if !oneOf(t, analysisTypes...) { + return invalid("EnabledAnalysisTypes value %q is not valid", t) + } + } + + fw.EnabledAnalysisTypes = cloneStrings(types) + + return nil + }) +} + +// AssociateAvailabilityZones adds Availability Zones to a transit +// gateway-attached firewall. +func (m *Mock) AssociateAvailabilityZones( + _ context.Context, + firewallName string, + zones []string, + updateToken string, +) (*nfdriver.Firewall, error) { + return m.mutateFirewall(firewallName, updateToken, func(fw *nfdriver.Firewall) error { + if err := zoneOpAllowed(fw, zones); err != nil { + return err + } + + seen := make(map[string]bool, len(fw.AvailabilityZones)) + for _, z := range fw.AvailabilityZones { + seen[z] = true + } + + for _, z := range zones { + if !seen[z] { + fw.AvailabilityZones = append(fw.AvailabilityZones, z) + seen[z] = true + } + } + + return nil + }) +} + +// DisassociateAvailabilityZones removes Availability Zones from a transit +// gateway-attached firewall. +func (m *Mock) DisassociateAvailabilityZones( + _ context.Context, + firewallName string, + zones []string, + updateToken string, +) (*nfdriver.Firewall, error) { + return m.mutateFirewall(firewallName, updateToken, func(fw *nfdriver.Firewall) error { + if err := zoneOpAllowed(fw, zones); err != nil { + return err + } + + remove := make(map[string]bool, len(zones)) + + for _, z := range zones { + if !oneOf(z, fw.AvailabilityZones...) { + return invalid("Availability Zone %q is not associated with firewall %q", z, fw.Name) + } + + remove[z] = true + } + + kept := fw.AvailabilityZones[:0:0] + + for _, z := range fw.AvailabilityZones { + if !remove[z] { + kept = append(kept, z) + } + } + + fw.AvailabilityZones = kept + + return nil + }) +} + +func zoneOpAllowed(fw *nfdriver.Firewall, zones []string) error { + if fw.TransitGatewayID == "" { + return nfdriver.InvalidOperation("firewall %q is VPC-attached; use the subnet operations", fw.Name) + } + + if fw.AvailabilityZoneChangeProtection { + return nfdriver.InvalidOperation("firewall %q has Availability Zone change protection enabled", fw.Name) + } + + if len(zones) == 0 { + return invalid("AvailabilityZoneMappings is required") + } + + for _, z := range zones { + if z == "" { + return invalid("AvailabilityZone must not be empty") + } + } + + return nil +} diff --git a/providers/aws/networkfirewall/flow_operation.go b/providers/aws/networkfirewall/flow_operation.go new file mode 100644 index 000000000..8a66b559d --- /dev/null +++ b/providers/aws/networkfirewall/flow_operation.go @@ -0,0 +1,222 @@ +package networkfirewall + +import ( + "context" + "sort" + + cerrors "github.com/stackshy/cloudemu/v2/errors" + "github.com/stackshy/cloudemu/v2/internal/idgen" + "github.com/stackshy/cloudemu/v2/internal/settle" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +const ( + flowCapture = "FLOW_CAPTURE" + flowFlush = "FLOW_FLUSH" + + flowCompleted = "COMPLETED" + flowInProgress = "IN_PROGRESS" +) + +// StartFlowCapture records a flow capture request on a firewall endpoint. +// +//nolint:gocritic // req matches the driver signature. +func (m *Mock) StartFlowCapture(_ context.Context, req nfdriver.FlowOperationRequest) (*nfdriver.FlowOperation, error) { + return m.startFlowOperation(flowCapture, &req) +} + +// StartFlowFlush records a flow flush request on a firewall endpoint. +// +//nolint:gocritic // req matches the driver signature. +func (m *Mock) StartFlowFlush(_ context.Context, req nfdriver.FlowOperationRequest) (*nfdriver.FlowOperation, error) { + return m.startFlowOperation(flowFlush, &req) +} + +func (m *Mock) startFlowOperation(opType string, req *nfdriver.FlowOperationRequest) (*nfdriver.FlowOperation, error) { + m.mu.Lock() + defer m.mu.Unlock() + + scope := nfdriver.FlowOperationScope{ + FirewallARN: req.FirewallARN, AvailabilityZone: req.AvailabilityZone, + VPCEndpointID: req.VPCEndpointID, VPCEndpointAssociationARN: req.VPCEndpointAssociationARN, + } + if err := m.validateFlowScope(scope); err != nil { + return nil, err + } + + if req.MinimumFlowAgeSeconds != nil && *req.MinimumFlowAgeSeconds < 0 { + return nil, invalid("MinimumFlowAgeInSeconds must not be negative") + } + + op := &nfdriver.FlowOperation{ + ID: idgen.UUID(), FirewallARN: req.FirewallARN, Type: opType, Status: flowCompleted, + AvailabilityZone: req.AvailabilityZone, VPCEndpointID: req.VPCEndpointID, + VPCEndpointAssociationARN: req.VPCEndpointAssociationARN, + Filters: cloneRawJSON(req.Filters), RequestedAt: m.now(), + } + + if req.MinimumFlowAgeSeconds != nil { + v := *req.MinimumFlowAgeSeconds + op.MinimumFlowAgeSeconds = &v + } + + m.flowOperations.Set(op.ID, op) + + return m.outFlowOperation(op), nil +} + +// validateFlowScope checks the firewall exists and that the endpoint selector +// (an Availability Zone of the firewall, or a VPC endpoint association of it) +// is valid. +func (m *Mock) validateFlowScope(s nfdriver.FlowOperationScope) error { + if err := validateARN("FirewallArn", s.FirewallARN); err != nil { + return err + } + + fw, ok := m.firewallByARN(s.FirewallARN) + if !ok { + return cerrors.Newf(cerrors.NotFound, "firewall %q not found", s.FirewallARN) + } + + if s.VPCEndpointAssociationARN != "" { + a, err := m.findAssociation(s.VPCEndpointAssociationARN) + if err != nil { + return err + } + + if a.FirewallARN != s.FirewallARN { + return invalid("VPC endpoint association %q does not belong to firewall %q", a.ARN, s.FirewallARN) + } + + return nil + } + + if s.AvailabilityZone == "" { + return invalid("either AvailabilityZone or VpcEndpointAssociationArn is required") + } + + if !oneOf(s.AvailabilityZone, nfdriver.SyncZones(fw, m.opts.Region)...) { + return invalid("firewall %q has no endpoint in Availability Zone %q", fw.Name, s.AvailabilityZone) + } + + return nil +} + +// DescribeFlowOperation returns one flow operation. +func (m *Mock) DescribeFlowOperation(_ context.Context, scope nfdriver.FlowOperationScope, id string) (*nfdriver.FlowOperation, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + op, err := m.findFlowOperation(scope, id) + if err != nil { + return nil, err + } + + return m.outFlowOperation(op), nil +} + +// ListFlowOperations lists the flow operations of a firewall endpoint, optionally +// filtered by type, oldest first. +func (m *Mock) ListFlowOperations( + _ context.Context, scope nfdriver.FlowOperationScope, opType string, opts nfdriver.ListOptions, +) ([]nfdriver.FlowOperation, string, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + if err := m.validateFlowScope(scope); err != nil { + return nil, "", err + } + + if opType != "" && !oneOf(opType, flowFlush, flowCapture) { + return nil, "", invalid("FlowOperationType %q is not valid", opType) + } + + var matched []*nfdriver.FlowOperation + + for _, op := range m.flowOperations.SortedValues() { + if flowInScope(op, scope) && (opType == "" || op.Type == opType) { + matched = append(matched, op) + } + } + + sort.SliceStable(matched, func(i, j int) bool { return matched[i].RequestedAt.Before(matched[j].RequestedAt) }) + + items, next, err := paginate(matched, opts) + if err != nil { + return nil, "", err + } + + out := make([]nfdriver.FlowOperation, 0, len(items)) + for _, op := range items { + out = append(out, *m.outFlowOperation(op)) + } + + return out, next, nil +} + +// ListFlowOperationResults returns the operation; its flows are always empty +// because the emulator has no data plane. The page arguments are validated so a +// caller sees the same errors as against AWS. +func (m *Mock) ListFlowOperationResults( + _ context.Context, scope nfdriver.FlowOperationScope, id string, opts nfdriver.ListOptions, +) (*nfdriver.FlowOperation, string, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + op, err := m.findFlowOperation(scope, id) + if err != nil { + return nil, "", err + } + + if _, _, err := paginate([]struct{}{}, opts); err != nil { + return nil, "", err + } + + return m.outFlowOperation(op), "", nil +} + +func (m *Mock) findFlowOperation(scope nfdriver.FlowOperationScope, id string) (*nfdriver.FlowOperation, error) { + if err := m.validateFlowScope(scope); err != nil { + return nil, err + } + + if id == "" { + return nil, invalid("FlowOperationId is required") + } + + op, ok := m.flowOperations.Get(id) + if !ok || !flowInScope(op, scope) { + return nil, cerrors.Newf(cerrors.NotFound, "flow operation %q not found", id) + } + + return op, nil +} + +func flowInScope(op *nfdriver.FlowOperation, s nfdriver.FlowOperationScope) bool { + if op.FirewallARN != s.FirewallARN { + return false + } + + if s.VPCEndpointAssociationARN != "" { + return op.VPCEndpointAssociationARN == s.VPCEndpointAssociationARN + } + + return op.VPCEndpointAssociationARN == "" && op.AvailabilityZone == s.AvailabilityZone +} + +// outFlowOperation returns a copy whose status reflects --async-settle: the +// operation reports IN_PROGRESS until the settle window has elapsed. +func (m *Mock) outFlowOperation(op *nfdriver.FlowOperation) *nfdriver.FlowOperation { + out := *op + out.Filters = cloneRawJSON(op.Filters) + + if op.MinimumFlowAgeSeconds != nil { + v := *op.MinimumFlowAgeSeconds + out.MinimumFlowAgeSeconds = &v + } + + window := settle.Pending(flowInProgress, op.RequestedAt, m.opts.SettleDuration(settle.DefaultFlowOperationSettle)) + out.Status = window.Observe(m.now(), flowCompleted) + + return &out +} diff --git a/providers/aws/networkfirewall/logging.go b/providers/aws/networkfirewall/logging.go new file mode 100644 index 000000000..f4220a8c2 --- /dev/null +++ b/providers/aws/networkfirewall/logging.go @@ -0,0 +1,221 @@ +package networkfirewall + +import ( + "context" + + cerrors "github.com/stackshy/cloudemu/v2/errors" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +const ( + logDestS3 = "S3" + logDestCloudWatch = "CloudWatchLogs" + logDestFirehose = "KinesisDataFirehose" + maxLogDestConfigs = 3 + + // typeChangeCost counts a LogDestinationType change as the remove plus the add it is. + typeChangeCost = 2 +) + +// Enum values copied verbatim from the AWS SDK (LogType, LogDestinationType). +// +//nolint:gochecknoglobals // immutable enum value sets. +var ( + logTypes = []string{"ALERT", "FLOW", "TLS"} + logDestTypes = []string{logDestS3, logDestCloudWatch, logDestFirehose} + + // logDestKeys lists, per destination type, the required key and the + // optional keys of LogDestination. + logDestRequired = map[string]string{logDestS3: "bucketName", logDestCloudWatch: "logGroup", logDestFirehose: "deliveryStream"} + logDestOptional = map[string]string{logDestS3: "prefix"} +) + +// UpdateLoggingConfiguration sets the firewall's log destinations. As in AWS, +// a single call may add one destination, remove one, or change the destination +// of one entry; an omitted configuration disables logging. +func (m *Mock) UpdateLoggingConfiguration(_ context.Context, firewallName string, cfg *nfdriver.LoggingConfiguration) error { + m.mu.Lock() + defer m.mu.Unlock() + + if err := validateName("FirewallName", firewallName); err != nil { + return err + } + + if !m.firewalls.Has(firewallName) { + return cerrors.Newf(cerrors.NotFound, "firewall %q not found", firewallName) + } + + var next nfdriver.LoggingConfiguration + if cfg != nil { + next = *cfg + } + + if err := validateLogDestinations(next.Destinations); err != nil { + return err + } + + current := m.logging[firewallName] + if current == nil { + current = &nfdriver.LoggingConfiguration{} + } + + if err := checkSingleLogChange(current.Destinations, next.Destinations); err != nil { + return err + } + + dashboard := current.EnableMonitoringDashboard + if next.EnableMonitoringDashboard != nil { + dashboard = next.EnableMonitoringDashboard + } + + if len(next.Destinations) == 0 && dashboard == nil { + delete(m.logging, firewallName) + + return nil + } + + m.logging[firewallName] = &nfdriver.LoggingConfiguration{ + Destinations: cloneLogConfigs(next.Destinations), + EnableMonitoringDashboard: cloneBool(dashboard), + } + + return nil +} + +// DescribeLoggingConfiguration returns the firewall's logging configuration. +func (m *Mock) DescribeLoggingConfiguration(_ context.Context, firewallName string) (*nfdriver.LoggingConfiguration, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + if err := validateName("FirewallName", firewallName); err != nil { + return nil, err + } + + if !m.firewalls.Has(firewallName) { + return nil, cerrors.Newf(cerrors.NotFound, "firewall %q not found", firewallName) + } + + cur := m.logging[firewallName] + if cur == nil { + return &nfdriver.LoggingConfiguration{}, nil + } + + return &nfdriver.LoggingConfiguration{ + Destinations: cloneLogConfigs(cur.Destinations), + EnableMonitoringDashboard: cloneBool(cur.EnableMonitoringDashboard), + }, nil +} + +// validateLogDestinations checks every entry against the SDK enums and the +// per-type destination keys, and enforces one entry per log type, max three. +func validateLogDestinations(cfgs []nfdriver.LogDestinationConfig) error { + if len(cfgs) > maxLogDestConfigs { + return invalid("at most %d log destination configs are allowed, got %d", maxLogDestConfigs, len(cfgs)) + } + + seen := make(map[string]bool, len(cfgs)) + + for _, c := range cfgs { + if !oneOf(c.LogType, logTypes...) { + return invalid("LogType %q is not valid (want one of %v)", c.LogType, logTypes) + } + + if seen[c.LogType] { + return invalid("more than one log destination config for LogType %s", c.LogType) + } + + seen[c.LogType] = true + + if !oneOf(c.LogDestinationType, logDestTypes...) { + return invalid("LogDestinationType %q is not valid (want one of %v)", c.LogDestinationType, logDestTypes) + } + + if err := validateLogDestinationKeys(c); err != nil { + return err + } + } + + return nil +} + +func validateLogDestinationKeys(c nfdriver.LogDestinationConfig) error { + required := logDestRequired[c.LogDestinationType] + if c.LogDestination[required] == "" { + return invalid("LogDestination for %s requires %q", c.LogDestinationType, required) + } + + for k := range c.LogDestination { + if k != required && k != logDestOptional[c.LogDestinationType] { + return invalid("LogDestination key %q is not valid for %s", k, c.LogDestinationType) + } + } + + return nil +} + +// checkSingleLogChange enforces AWS's "one change per call" rule: add one entry, +// remove one entry, or change the LogDestination of one entry. Changing the +// LogDestinationType (or LogType) of an entry is a remove plus an add, so it +// needs two calls. +func checkSingleLogChange(current, next []nfdriver.LogDestinationConfig) error { + have := make(map[string]nfdriver.LogDestinationConfig, len(current)) + for _, c := range current { + have[c.LogType] = c + } + + changes := 0 + + for _, n := range next { + c, ok := have[n.LogType] + + switch { + case !ok: + changes++ + case c.LogDestinationType != n.LogDestinationType: + changes += typeChangeCost + case !sameDestination(c.LogDestination, n.LogDestination): + changes++ + } + + delete(have, n.LogType) + } + + changes += len(have) // entries dropped from the configuration + + if changes > 1 { + return invalid("UpdateLoggingConfiguration accepts one change per call (add one destination, remove one, or change one destination)") + } + + return nil +} + +func sameDestination(a, b map[string]string) bool { + if len(a) != len(b) { + return false + } + + for k, v := range a { + if b[k] != v { + return false + } + } + + return true +} + +func cloneLogConfigs(cfgs []nfdriver.LogDestinationConfig) []nfdriver.LogDestinationConfig { + if len(cfgs) == 0 { + return nil + } + + out := make([]nfdriver.LogDestinationConfig, len(cfgs)) + for i, c := range cfgs { + out[i] = nfdriver.LogDestinationConfig{ + LogType: c.LogType, + LogDestinationType: c.LogDestinationType, + LogDestination: copyTags(c.LogDestination), + } + } + + return out +} diff --git a/providers/aws/networkfirewall/metadata.go b/providers/aws/networkfirewall/metadata.go new file mode 100644 index 000000000..499062af9 --- /dev/null +++ b/providers/aws/networkfirewall/metadata.go @@ -0,0 +1,123 @@ +package networkfirewall + +import ( + "context" + "encoding/json" + "regexp" + "strings" + + cerrors "github.com/stackshy/cloudemu/v2/errors" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +// Suricata rule options a summary reports. +var ( + ruleMsgRE = regexp.MustCompile(`msg:\s*"([^"]*)"\s*;`) + ruleSIDRE = regexp.MustCompile(`sid:\s*(\d+)\s*;`) + ruleMetadataRE = regexp.MustCompile(`metadata:\s*([^;]*);`) +) + +// DescribeFirewallMetadata returns the firewall's metadata, as visible to an +// account a firewall is shared with. +func (m *Mock) DescribeFirewallMetadata(_ context.Context, firewallARN string) (*nfdriver.FirewallMetadata, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + if err := validateARN("FirewallArn", firewallARN); err != nil { + return nil, err + } + + fw, ok := m.firewallByARN(firewallARN) + if !ok { + return nil, cerrors.Newf(cerrors.NotFound, "firewall %q not found", firewallARN) + } + + return &nfdriver.FirewallMetadata{ + FirewallARN: fw.ARN, + PolicyARN: fw.PolicyARN, + Description: fw.Description, + Status: fw.Status, + AvailabilityZones: nfdriver.SyncZones(fw, m.opts.Region), + }, nil +} + +// DescribeRuleGroupMetadata returns the rule group (the wire layer reports its +// metadata subset). +func (m *Mock) DescribeRuleGroupMetadata(_ context.Context, name, arn, ruleType string) (*nfdriver.RuleGroup, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + rg, err := m.findRuleGroup(name, arn, ruleType) + if err != nil { + return nil, err + } + + return m.outRuleGroup(rg), nil +} + +// DescribeRuleGroupSummary returns the rule group and the per-rule summaries +// parsed from its Suricata rules. Only the options listed in the rule group's +// SummaryConfiguration are populated. Only stateful rule groups carry rules text. +func (m *Mock) DescribeRuleGroupSummary( + _ context.Context, name, arn, ruleType string, +) (*nfdriver.RuleGroup, []nfdriver.RuleSummary, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + rg, err := m.findRuleGroup(name, arn, ruleType) + if err != nil { + return nil, nil, err + } + + if rg.Type == ruleTypeStateless { + return nil, nil, invalid("rule group summaries are only available for stateful rule groups") + } + + return m.outRuleGroup(rg), ruleSummaries(rg), nil +} + +func ruleSummaries(rg *nfdriver.RuleGroup) []nfdriver.RuleSummary { + var src ruleSource + if err := json.Unmarshal(rg.Rules, &src); err != nil { + return nil + } + + want := make(map[string]bool, len(rg.SummaryRuleOptions)) + for _, o := range rg.SummaryRuleOptions { + want[o] = true + } + + lines := strings.Split(src.RulesSource.RulesString, "\n") + out := make([]nfdriver.RuleSummary, 0, len(lines)) + + for _, line := range lines { + if !isRuleLine(line) { + continue + } + + var s nfdriver.RuleSummary + if want["MSG"] { + s.Msg = firstGroup(ruleMsgRE, line) + } + + if want["SID"] { + s.SID = firstGroup(ruleSIDRE, line) + } + + if want["METADATA"] { + s.Metadata = strings.TrimSpace(firstGroup(ruleMetadataRE, line)) + } + + out = append(out, s) + } + + return out +} + +func firstGroup(re *regexp.Regexp, s string) string { + if g := re.FindStringSubmatch(s); len(g) > 1 { + return g[1] + } + + return "" +} diff --git a/providers/aws/networkfirewall/networkfirewall.go b/providers/aws/networkfirewall/networkfirewall.go index 63df8be63..281e31953 100644 --- a/providers/aws/networkfirewall/networkfirewall.go +++ b/providers/aws/networkfirewall/networkfirewall.go @@ -2,48 +2,75 @@ package networkfirewall import ( - "context" - "encoding/json" - "fmt" + "strings" "sync" + "time" "github.com/stackshy/cloudemu/v2/config" - cerrors "github.com/stackshy/cloudemu/v2/errors" "github.com/stackshy/cloudemu/v2/internal/idgen" "github.com/stackshy/cloudemu/v2/internal/memstore" nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" ) const ( - ruleTypeStateful = "STATEFUL" - ruleTypeStateless = "STATELESS" + ruleTypeStateful = "STATEFUL" + ruleTypeStateless = "STATELESS" + ruleTypeStatefulDomain = "STATEFUL_DOMAIN" + + statusReady = "READY" + statusDeleting = "DELETING" + statusActive = "ACTIVE" ) -var _ nfdriver.NetworkFirewall = (*Mock)(nil) +var ( + _ nfdriver.NetworkFirewall = (*Mock)(nil) + _ nfdriver.FirewallSettings = (*Mock)(nil) + _ nfdriver.AvailabilityZones = (*Mock)(nil) + _ nfdriver.ResourcePolicies = (*Mock)(nil) + _ nfdriver.TLSInspection = (*Mock)(nil) + _ nfdriver.VPCEndpointAssociations = (*Mock)(nil) + _ nfdriver.Metadata = (*Mock)(nil) + _ nfdriver.FlowOperations = (*Mock)(nil) + _ nfdriver.AnalysisReports = (*Mock)(nil) +) // Mock is the in-memory AWS Network Firewall implementation. Resources are -// keyed by name (unique per account/region, as in the real service). +// keyed by name (unique per account/region, as in the real service); VPC +// endpoint associations by ARN, flow operations and analysis reports by id. // // The stores hand back shared pointers whose fields are mutated in place -// (associate/tag/protection/subnets) and logging is a plain map, so every -// public method serializes on mu: mutators take Lock, readers take RLock. +// (associate/tag/protection/subnets) and logging/resource policies are plain +// maps, so every public method serializes on mu: mutators take Lock, readers +// take RLock, and everything handed out is a deep copy. That single lock also +// makes every create/delete (including its reference checks) atomic, so no +// concurrent pair can both pass a check. type Mock struct { - mu sync.RWMutex - firewalls *memstore.Store[*nfdriver.Firewall] - policies *memstore.Store[*nfdriver.FirewallPolicy] - ruleGroups *memstore.Store[*nfdriver.RuleGroup] - logging map[string][]nfdriver.LogDestinationConfig - opts *config.Options + mu sync.RWMutex + firewalls *memstore.Store[*nfdriver.Firewall] + policies *memstore.Store[*nfdriver.FirewallPolicy] + ruleGroups *memstore.Store[*nfdriver.RuleGroup] + tlsConfigs *memstore.Store[*nfdriver.TLSInspectionConfig] + associations *memstore.Store[*nfdriver.VPCEndpointAssociation] + flowOperations *memstore.Store[*nfdriver.FlowOperation] + analysisReports *memstore.Store[*nfdriver.AnalysisReport] + logging map[string]*nfdriver.LoggingConfiguration + resourcePolicies map[string]string + opts *config.Options } // New creates a new Network Firewall mock. func New(opts *config.Options) *Mock { return &Mock{ - firewalls: memstore.New[*nfdriver.Firewall](), - policies: memstore.New[*nfdriver.FirewallPolicy](), - ruleGroups: memstore.New[*nfdriver.RuleGroup](), - logging: map[string][]nfdriver.LogDestinationConfig{}, - opts: opts, + firewalls: memstore.New[*nfdriver.Firewall](), + policies: memstore.New[*nfdriver.FirewallPolicy](), + ruleGroups: memstore.New[*nfdriver.RuleGroup](), + tlsConfigs: memstore.New[*nfdriver.TLSInspectionConfig](), + associations: memstore.New[*nfdriver.VPCEndpointAssociation](), + flowOperations: memstore.New[*nfdriver.FlowOperation](), + analysisReports: memstore.New[*nfdriver.AnalysisReport](), + logging: map[string]*nfdriver.LoggingConfiguration{}, + resourcePolicies: map[string]string{}, + opts: opts, } } @@ -51,6 +78,24 @@ func (m *Mock) arn(kind, name string) string { return idgen.AWSARN("network-firewall", m.opts.Region, m.opts.AccountID, kind+"/"+name) } +func (m *Mock) now() time.Time { return m.opts.Clock.Now() } + +// newToken mints an update token (an RFC 4122 UUID, the shape AWS documents). +func newToken() string { return idgen.UUID() } + +// arnKind returns the resource segment of a Network Firewall ARN +// ("firewall", "stateful-rulegroup", ...), or "" for anything else. +func arnKind(arn string) string { + parts := strings.SplitN(arn, ":", 6) //nolint:mnd // an ARN has six colon-separated fields + if len(parts) < 6 || parts[2] != "network-firewall" { + return "" + } + + kind, _, _ := strings.Cut(parts[5], "/") + + return kind +} + func copyTags(src map[string]string) map[string]string { if len(src) == 0 { return nil @@ -72,416 +117,25 @@ func cloneStrings(s []string) []string { return append([]string(nil), s...) } -func cloneRawJSON(r json.RawMessage) json.RawMessage { +func cloneRawJSON(r []byte) []byte { if len(r) == 0 { return nil } - out := make(json.RawMessage, len(r)) + out := make([]byte, len(r)) copy(out, r) return out } -func cloneRuleGroupRefs(refs []nfdriver.RuleGroupReference) []nfdriver.RuleGroupReference { - if len(refs) == 0 { +func cloneBool(b *bool) *bool { + if b == nil { return nil } - return append([]nfdriver.RuleGroupReference(nil), refs...) -} - -// ---- Firewalls ---- - -//nolint:gocritic // cfg matches the driver signature. -func (m *Mock) CreateFirewall(_ context.Context, cfg nfdriver.CreateFirewallConfig) (*nfdriver.Firewall, error) { - m.mu.Lock() - defer m.mu.Unlock() - - if cfg.Name == "" { - return nil, cerrors.New(cerrors.InvalidArgument, "FirewallName is required") - } - - if m.firewalls.Has(cfg.Name) { - return nil, cerrors.Newf(cerrors.AlreadyExists, "firewall %q already exists", cfg.Name) - } - - if cfg.PolicyARN != "" && !m.policyExists(cfg.PolicyARN) { - return nil, cerrors.Newf(cerrors.InvalidArgument, "firewall policy %q not found", cfg.PolicyARN) - } - - fw := &nfdriver.Firewall{ - Name: cfg.Name, - ARN: m.arn("firewall", cfg.Name), - ID: idgen.GenerateID(""), - PolicyARN: cfg.PolicyARN, - VPCID: cfg.VPCID, - SubnetIDs: cloneStrings(cfg.SubnetIDs), - Description: cfg.Description, - DeleteProtection: cfg.DeleteProtection, - Status: "READY", - Tags: copyTags(cfg.Tags), - } - m.firewalls.Set(cfg.Name, fw) - - out := cloneFirewall(fw) - - return &out, nil -} - -func (m *Mock) DescribeFirewall(_ context.Context, name, arn string) (*nfdriver.Firewall, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - fw, ok := m.lookupFirewall(name, arn) - if !ok { - return nil, cerrors.Newf(cerrors.NotFound, "firewall %q not found", nonEmpty(name, arn)) - } - - out := cloneFirewall(fw) - - return &out, nil -} - -func (m *Mock) DeleteFirewall(_ context.Context, name, arn string) (*nfdriver.Firewall, error) { - m.mu.Lock() - defer m.mu.Unlock() - - fw, ok := m.lookupFirewall(name, arn) - if !ok { - return nil, cerrors.Newf(cerrors.NotFound, "firewall %q not found", nonEmpty(name, arn)) - } - - if fw.DeleteProtection { - return nil, cerrors.Newf(cerrors.FailedPrecondition, "firewall %q has delete protection enabled", fw.Name) - } - - fw.Status = "DELETING" - m.firewalls.Delete(fw.Name) - - out := cloneFirewall(fw) - - return &out, nil -} - -func (m *Mock) ListFirewalls(_ context.Context) ([]nfdriver.Firewall, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - all := m.firewalls.SortedValues() - out := make([]nfdriver.Firewall, 0, len(all)) - - for _, f := range all { - out = append(out, cloneFirewall(f)) - } - - return out, nil -} - -func (m *Mock) lookupFirewall(name, arn string) (*nfdriver.Firewall, bool) { - if name != "" { - return m.firewalls.Get(name) - } - - for _, f := range m.firewalls.SortedValues() { - if f.ARN == arn { - return f, true - } - } - - return nil, false -} - -func cloneFirewall(f *nfdriver.Firewall) nfdriver.Firewall { - out := *f - out.SubnetIDs = cloneStrings(f.SubnetIDs) - out.Tags = copyTags(f.Tags) - - return out -} - -// ---- Firewall Policies ---- - -//nolint:gocritic // cfg matches the driver signature. -func (m *Mock) CreateFirewallPolicy(_ context.Context, cfg nfdriver.CreateFirewallPolicyConfig) (*nfdriver.FirewallPolicy, error) { - m.mu.Lock() - defer m.mu.Unlock() - - if cfg.Name == "" { - return nil, cerrors.New(cerrors.InvalidArgument, "FirewallPolicyName is required") - } - - if m.policies.Has(cfg.Name) { - return nil, cerrors.Newf(cerrors.AlreadyExists, "firewall policy %q already exists", cfg.Name) - } - - p := &nfdriver.FirewallPolicy{ - Name: cfg.Name, - ARN: m.arn("firewall-policy", cfg.Name), - ID: idgen.GenerateID(""), - Description: cfg.Description, - StatelessDefaultActions: cloneStrings(cfg.StatelessDefaultActions), - StatelessFragmentDefaultActions: cloneStrings(cfg.StatelessFragmentDefaultActions), - StatefulRuleGroupReferences: cloneRuleGroupRefs(cfg.StatefulRuleGroupReferences), - StatelessRuleGroupReferences: cloneRuleGroupRefs(cfg.StatelessRuleGroupReferences), - Tags: copyTags(cfg.Tags), - } - m.policies.Set(cfg.Name, p) - - out := cloneFirewallPolicy(p) + v := *b - return &out, nil -} - -func (m *Mock) DescribeFirewallPolicy(_ context.Context, name, arn string) (*nfdriver.FirewallPolicy, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - p, ok := m.lookupPolicy(name, arn) - if !ok { - return nil, cerrors.Newf(cerrors.NotFound, "firewall policy %q not found", nonEmpty(name, arn)) - } - - out := cloneFirewallPolicy(p) - - return &out, nil -} - -//nolint:gocritic // cfg matches the driver signature. -func (m *Mock) UpdateFirewallPolicy( - _ context.Context, name, arn string, cfg nfdriver.UpdateFirewallPolicyConfig, -) (*nfdriver.FirewallPolicy, error) { - m.mu.Lock() - defer m.mu.Unlock() - - p, ok := m.lookupPolicy(name, arn) - if !ok { - return nil, cerrors.Newf(cerrors.NotFound, "firewall policy %q not found", nonEmpty(name, arn)) - } - - p.Description = cfg.Description - p.StatelessDefaultActions = cloneStrings(cfg.StatelessDefaultActions) - p.StatelessFragmentDefaultActions = cloneStrings(cfg.StatelessFragmentDefaultActions) - p.StatefulRuleGroupReferences = cloneRuleGroupRefs(cfg.StatefulRuleGroupReferences) - p.StatelessRuleGroupReferences = cloneRuleGroupRefs(cfg.StatelessRuleGroupReferences) - - out := cloneFirewallPolicy(p) - - return &out, nil -} - -func (m *Mock) DeleteFirewallPolicy(_ context.Context, name, arn string) (*nfdriver.FirewallPolicy, error) { - m.mu.Lock() - defer m.mu.Unlock() - - p, ok := m.lookupPolicy(name, arn) - if !ok { - return nil, cerrors.Newf(cerrors.NotFound, "firewall policy %q not found", nonEmpty(name, arn)) - } - - if m.policyInUse(p.ARN) { - return nil, cerrors.Newf(cerrors.FailedPrecondition, "firewall policy %q is in use by a firewall", p.Name) - } - - m.policies.Delete(p.Name) - - out := cloneFirewallPolicy(p) - - return &out, nil -} - -func (m *Mock) ListFirewallPolicies(_ context.Context) ([]nfdriver.FirewallPolicy, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - all := m.policies.SortedValues() - out := make([]nfdriver.FirewallPolicy, 0, len(all)) - - for _, p := range all { - out = append(out, cloneFirewallPolicy(p)) - } - - return out, nil -} - -func (m *Mock) lookupPolicy(name, arn string) (*nfdriver.FirewallPolicy, bool) { - if name != "" { - return m.policies.Get(name) - } - - for _, p := range m.policies.SortedValues() { - if p.ARN == arn { - return p, true - } - } - - return nil, false -} - -// policyExists reports whether a firewall policy with the given ARN is present. -func (m *Mock) policyExists(arn string) bool { - for _, p := range m.policies.SortedValues() { - if p.ARN == arn { - return true - } - } - - return false -} - -// policyInUse reports whether any firewall references the policy ARN. -func (m *Mock) policyInUse(arn string) bool { - for _, f := range m.firewalls.SortedValues() { - if f.PolicyARN == arn { - return true - } - } - - return false -} - -func cloneFirewallPolicy(p *nfdriver.FirewallPolicy) nfdriver.FirewallPolicy { - out := *p - out.StatelessDefaultActions = cloneStrings(p.StatelessDefaultActions) - out.StatelessFragmentDefaultActions = cloneStrings(p.StatelessFragmentDefaultActions) - out.StatefulRuleGroupReferences = cloneRuleGroupRefs(p.StatefulRuleGroupReferences) - out.StatelessRuleGroupReferences = cloneRuleGroupRefs(p.StatelessRuleGroupReferences) - out.Tags = copyTags(p.Tags) - - return out -} - -// ---- Rule Groups ---- - -func (m *Mock) CreateRuleGroup(_ context.Context, cfg nfdriver.CreateRuleGroupConfig) (*nfdriver.RuleGroup, error) { - m.mu.Lock() - defer m.mu.Unlock() - - if cfg.Name == "" { - return nil, cerrors.New(cerrors.InvalidArgument, "RuleGroupName is required") - } - - if cfg.Type != ruleTypeStateful && cfg.Type != ruleTypeStateless { - return nil, cerrors.New(cerrors.InvalidArgument, "Type must be STATEFUL or STATELESS") - } - - key := ruleGroupKey(cfg.Name, cfg.Type) - if m.ruleGroups.Has(key) { - return nil, cerrors.Newf(cerrors.AlreadyExists, "rule group %q already exists", cfg.Name) - } - - rgKind := "stateful-rulegroup" - if cfg.Type == ruleTypeStateless { - rgKind = "stateless-rulegroup" - } - - rg := &nfdriver.RuleGroup{ - Name: cfg.Name, - ARN: m.arn(rgKind, cfg.Name), - ID: idgen.GenerateID(""), - Type: cfg.Type, - Capacity: cfg.Capacity, - Description: cfg.Description, - Rules: cloneRawJSON(cfg.Rules), - Tags: copyTags(cfg.Tags), - } - m.ruleGroups.Set(key, rg) - - out := cloneRuleGroup(rg) - - return &out, nil -} - -func (m *Mock) DescribeRuleGroup(_ context.Context, name, arn, ruleType string) (*nfdriver.RuleGroup, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - rg, ok := m.lookupRuleGroup(name, arn, ruleType) - if !ok { - return nil, cerrors.Newf(cerrors.NotFound, "rule group %q not found", nonEmpty(name, arn)) - } - - out := cloneRuleGroup(rg) - - return &out, nil -} - -//nolint:gocritic // cfg matches the driver signature. -func (m *Mock) UpdateRuleGroup( - _ context.Context, name, arn, ruleType string, cfg nfdriver.UpdateRuleGroupConfig, -) (*nfdriver.RuleGroup, error) { - m.mu.Lock() - defer m.mu.Unlock() - - rg, ok := m.lookupRuleGroup(name, arn, ruleType) - if !ok { - return nil, cerrors.Newf(cerrors.NotFound, "rule group %q not found", nonEmpty(name, arn)) - } - - rg.Description = cfg.Description - if len(cfg.Rules) > 0 { - rg.Rules = cloneRawJSON(cfg.Rules) - } - - out := cloneRuleGroup(rg) - - return &out, nil -} - -func (m *Mock) DeleteRuleGroup(_ context.Context, name, arn, ruleType string) (*nfdriver.RuleGroup, error) { - m.mu.Lock() - defer m.mu.Unlock() - - rg, ok := m.lookupRuleGroup(name, arn, ruleType) - if !ok { - return nil, cerrors.Newf(cerrors.NotFound, "rule group %q not found", nonEmpty(name, arn)) - } - - m.ruleGroups.Delete(ruleGroupKey(rg.Name, rg.Type)) - - out := cloneRuleGroup(rg) - - return &out, nil -} - -func (m *Mock) ListRuleGroups(_ context.Context) ([]nfdriver.RuleGroup, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - all := m.ruleGroups.SortedValues() - out := make([]nfdriver.RuleGroup, 0, len(all)) - - for _, rg := range all { - out = append(out, cloneRuleGroup(rg)) - } - - return out, nil -} - -func (m *Mock) lookupRuleGroup(name, arn, ruleType string) (*nfdriver.RuleGroup, bool) { - if name != "" && ruleType != "" { - return m.ruleGroups.Get(ruleGroupKey(name, ruleType)) - } - - for _, rg := range m.ruleGroups.SortedValues() { - if (name != "" && rg.Name == name) || (arn != "" && rg.ARN == arn) { - return rg, true - } - } - - return nil, false -} - -func ruleGroupKey(name, ruleType string) string { - return fmt.Sprintf("%s/%s", ruleType, name) -} - -func cloneRuleGroup(rg *nfdriver.RuleGroup) nfdriver.RuleGroup { - out := *rg - out.Rules = cloneRawJSON(rg.Rules) - out.Tags = copyTags(rg.Tags) - - return out + return &v } func nonEmpty(a, b string) string { @@ -491,226 +145,3 @@ func nonEmpty(a, b string) string { return b } - -// ---- Firewall depth: associations, protection, logging, tags ---- - -// AssociateFirewallPolicy attaches a firewall policy to a firewall. -func (m *Mock) AssociateFirewallPolicy(_ context.Context, firewallName, policyARN string) (*nfdriver.Firewall, error) { - m.mu.Lock() - defer m.mu.Unlock() - - fw, ok := m.firewalls.Get(firewallName) - if !ok { - return nil, cerrors.Newf(cerrors.NotFound, "firewall %q not found", firewallName) - } - - if !m.policyExists(policyARN) { - return nil, cerrors.Newf(cerrors.InvalidArgument, "firewall policy %q not found", policyARN) - } - - fw.PolicyARN = policyARN - - out := cloneFirewall(fw) - - return &out, nil -} - -// AssociateSubnets adds subnet mappings to a firewall. -func (m *Mock) AssociateSubnets(_ context.Context, firewallName string, subnetIDs []string) (*nfdriver.Firewall, error) { - m.mu.Lock() - defer m.mu.Unlock() - - fw, ok := m.firewalls.Get(firewallName) - if !ok { - return nil, cerrors.Newf(cerrors.NotFound, "firewall %q not found", firewallName) - } - - seen := make(map[string]bool, len(fw.SubnetIDs)) - for _, s := range fw.SubnetIDs { - seen[s] = true - } - - for _, s := range subnetIDs { - if !seen[s] { - fw.SubnetIDs = append(fw.SubnetIDs, s) - seen[s] = true - } - } - - out := cloneFirewall(fw) - - return &out, nil -} - -// DisassociateSubnets removes subnet mappings from a firewall. -func (m *Mock) DisassociateSubnets(_ context.Context, firewallName string, subnetIDs []string) (*nfdriver.Firewall, error) { - m.mu.Lock() - defer m.mu.Unlock() - - fw, ok := m.firewalls.Get(firewallName) - if !ok { - return nil, cerrors.Newf(cerrors.NotFound, "firewall %q not found", firewallName) - } - - remove := make(map[string]bool, len(subnetIDs)) - for _, s := range subnetIDs { - remove[s] = true - } - - kept := fw.SubnetIDs[:0:0] - - for _, s := range fw.SubnetIDs { - if !remove[s] { - kept = append(kept, s) - } - } - - fw.SubnetIDs = kept - - out := cloneFirewall(fw) - - return &out, nil -} - -// UpdateFirewallDeleteProtection toggles delete protection on a firewall. -func (m *Mock) UpdateFirewallDeleteProtection(_ context.Context, firewallName string, enabled bool) (*nfdriver.Firewall, error) { - m.mu.Lock() - defer m.mu.Unlock() - - fw, ok := m.firewalls.Get(firewallName) - if !ok { - return nil, cerrors.Newf(cerrors.NotFound, "firewall %q not found", firewallName) - } - - fw.DeleteProtection = enabled - - out := cloneFirewall(fw) - - return &out, nil -} - -// UpdateLoggingConfiguration sets the firewall's log destination configs. -func (m *Mock) UpdateLoggingConfiguration(_ context.Context, firewallName string, configs []nfdriver.LogDestinationConfig) error { - m.mu.Lock() - defer m.mu.Unlock() - - if !m.firewalls.Has(firewallName) { - return cerrors.Newf(cerrors.NotFound, "firewall %q not found", firewallName) - } - - m.logging[firewallName] = cloneLogConfigs(configs) - - return nil -} - -// DescribeLoggingConfiguration returns the firewall's log destination configs. -func (m *Mock) DescribeLoggingConfiguration(_ context.Context, firewallName string) ([]nfdriver.LogDestinationConfig, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - if !m.firewalls.Has(firewallName) { - return nil, cerrors.Newf(cerrors.NotFound, "firewall %q not found", firewallName) - } - - return cloneLogConfigs(m.logging[firewallName]), nil -} - -func cloneLogConfigs(cfgs []nfdriver.LogDestinationConfig) []nfdriver.LogDestinationConfig { - if len(cfgs) == 0 { - return nil - } - - out := make([]nfdriver.LogDestinationConfig, len(cfgs)) - for i, c := range cfgs { - out[i] = nfdriver.LogDestinationConfig{ - LogType: c.LogType, - LogDestinationType: c.LogDestinationType, - LogDestination: copyTags(c.LogDestination), - } - } - - return out -} - -// TagResource adds tags to a firewall / policy / rule group by ARN. -func (m *Mock) TagResource(_ context.Context, arn string, tags map[string]string) error { - m.mu.Lock() - defer m.mu.Unlock() - - if t := m.taggableByARN(arn); t != nil { - for k, v := range tags { - t[k] = v - } - - return nil - } - - return cerrors.Newf(cerrors.NotFound, "resource %q not found", arn) -} - -// UntagResource removes tags from a firewall / policy / rule group by ARN. -func (m *Mock) UntagResource(_ context.Context, arn string, keys []string) error { - m.mu.Lock() - defer m.mu.Unlock() - - t := m.taggableByARN(arn) - if t == nil { - return cerrors.Newf(cerrors.NotFound, "resource %q not found", arn) - } - - for _, k := range keys { - delete(t, k) - } - - return nil -} - -// ListTagsForResource returns a copy of the tags on the resource with the given -// ARN (firewall, policy, or rule group). -func (m *Mock) ListTagsForResource(_ context.Context, arn string) (map[string]string, error) { - m.mu.Lock() - defer m.mu.Unlock() - - t := m.taggableByARN(arn) - if t == nil { - return nil, cerrors.Newf(cerrors.NotFound, "resource %q not found", arn) - } - - return copyTags(t), nil -} - -// taggableByARN returns the mutable Tags map of the resource with the given ARN, -// creating it if nil, or nil when no resource matches. -func (m *Mock) taggableByARN(arn string) map[string]string { - for _, f := range m.firewalls.SortedValues() { - if f.ARN == arn { - if f.Tags == nil { - f.Tags = map[string]string{} - } - - return f.Tags - } - } - - for _, p := range m.policies.SortedValues() { - if p.ARN == arn { - if p.Tags == nil { - p.Tags = map[string]string{} - } - - return p.Tags - } - } - - for _, rg := range m.ruleGroups.SortedValues() { - if rg.ARN == arn { - if rg.Tags == nil { - rg.Tags = map[string]string{} - } - - return rg.Tags - } - } - - return nil -} diff --git a/providers/aws/networkfirewall/networkfirewall_test.go b/providers/aws/networkfirewall/networkfirewall_test.go index f9d41a43b..821d9d542 100644 --- a/providers/aws/networkfirewall/networkfirewall_test.go +++ b/providers/aws/networkfirewall/networkfirewall_test.go @@ -2,8 +2,13 @@ package networkfirewall import ( "context" + "encoding/json" "sync" "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/stackshy/cloudemu/v2/config" cerrors "github.com/stackshy/cloudemu/v2/errors" @@ -12,174 +17,205 @@ import ( func newMock() *Mock { return New(config.NewOptions()) } -// logConfigs builds LogDestinationConfig entries carrying only LogType, for -// tests that don't care about the destination fields. -func logConfigs(logTypes ...string) []nfdriver.LogDestinationConfig { - out := make([]nfdriver.LogDestinationConfig, 0, len(logTypes)) - for _, lt := range logTypes { - out = append(out, nfdriver.LogDestinationConfig{LogType: lt}) +// newClockMock returns a mock on a FakeClock so time-dependent output is exact. +func newClockMock(t *testing.T) (*Mock, *config.FakeClock) { + t.Helper() + + clock := config.NewFakeClock(time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)) + + return New(config.NewOptions(config.WithClock(clock))), clock +} + +var ( + bg = context.Background() + + standardActions = []string{"aws:forward_to_sfe"} +) + +func seedPolicy(t *testing.T, m *Mock, name string) *nfdriver.FirewallPolicy { + t.Helper() + + p, err := m.CreateFirewallPolicy(bg, nfdriver.CreateFirewallPolicyConfig{ + Name: name, StatelessDefaultActions: standardActions, StatelessFragmentDefaultActions: standardActions, + }) + require.NoError(t, err) + + return p +} + +func seedFirewall(t *testing.T, m *Mock, name, policyARN string) *nfdriver.Firewall { + t.Helper() + + fw, err := m.CreateFirewall(bg, nfdriver.CreateFirewallConfig{ + Name: name, PolicyARN: policyARN, VPCID: "vpc-1a2b", SubnetIDs: []string{"subnet-1"}, + }) + require.NoError(t, err) + + return fw +} + +func seedRuleGroup(t *testing.T, m *Mock, name, ruleType string, capacity int) *nfdriver.RuleGroup { + t.Helper() + + rg, err := m.CreateRuleGroup(bg, nfdriver.CreateRuleGroupConfig{Name: name, Type: ruleType, Capacity: capacity}) + require.NoError(t, err) + + return rg +} + +// seedStack creates a policy and a firewall using it. +func seedStack(t *testing.T, m *Mock) (*nfdriver.FirewallPolicy, *nfdriver.Firewall) { + t.Helper() + + p := seedPolicy(t, m, "pol-1") + + return p, seedFirewall(t, m, "fw-1", p.ARN) +} + +// requireException asserts err carries the given Network Firewall exception. +func requireException(t *testing.T, err error, want string) { + t.Helper() + + got, ok := nfdriver.ExceptionOf(err) + require.True(t, ok, "expected typed exception %s, got %v", want, err) + assert.Equal(t, want, got) +} + +func logDest(logType, destType string, dest map[string]string) nfdriver.LogDestinationConfig { + return nfdriver.LogDestinationConfig{LogType: logType, LogDestinationType: destType, LogDestination: dest} +} + +func s3Dest(logType, bucket string) nfdriver.LogDestinationConfig { + return logDest(logType, "S3", map[string]string{"bucketName": bucket}) +} + +func rulesString(lines ...string) json.RawMessage { + body := "" + for _, l := range lines { + body += l + "\n" } - return out + b, _ := json.Marshal(map[string]any{"RulesSource": map[string]any{"RulesString": body}}) + + return b } func TestFirewallLifecycle(t *testing.T) { m := newMock() - ctx := context.Background() + pol := seedPolicy(t, m, "pol-1") - if _, err := m.CreateFirewall(ctx, nfdriver.CreateFirewallConfig{}); !cerrors.IsInvalidArgument(err) { - t.Fatalf("firewall without name: got %v, want InvalidArgument", err) - } + _, err := m.CreateFirewall(bg, nfdriver.CreateFirewallConfig{}) + assert.True(t, cerrors.IsInvalidArgument(err), "firewall without name: %v", err) - fw, err := m.CreateFirewall(ctx, nfdriver.CreateFirewallConfig{ - Name: "fw-1", VPCID: "vpc-1", SubnetIDs: []string{"subnet-1"}, DeleteProtection: true, + fw, err := m.CreateFirewall(bg, nfdriver.CreateFirewallConfig{ + Name: "fw-1", PolicyARN: pol.ARN, VPCID: "vpc-1a", SubnetIDs: []string{"subnet-1"}, DeleteProtection: true, }) - if err != nil || fw.ARN == "" || fw.Status != "READY" { - t.Fatalf("CreateFirewall: %v %+v", err, fw) - } + require.NoError(t, err) + assert.NotEmpty(t, fw.ARN) + assert.Equal(t, "READY", fw.Status) - if _, err := m.CreateFirewall(ctx, nfdriver.CreateFirewallConfig{Name: "fw-1"}); !cerrors.IsAlreadyExists(err) { - t.Fatalf("duplicate firewall: got %v, want AlreadyExists", err) - } + _, err = m.CreateFirewall(bg, nfdriver.CreateFirewallConfig{Name: "fw-1", PolicyARN: pol.ARN, VPCID: "vpc-1a"}) + assert.True(t, cerrors.IsAlreadyExists(err), "duplicate firewall: %v", err) - // Delete protection blocks deletion. - if _, err := m.DeleteFirewall(ctx, "fw-1", ""); !cerrors.IsFailedPrecondition(err) { - t.Fatalf("delete protected firewall: got %v, want FailedPrecondition", err) - } + _, err = m.DeleteFirewall(bg, "fw-1", "") + requireException(t, err, nfdriver.ExInvalidOperation) - // Lookup by ARN works too. - got, err := m.DescribeFirewall(ctx, "", fw.ARN) - if err != nil || got.Name != "fw-1" { - t.Fatalf("DescribeFirewall by ARN: %v %+v", err, got) - } + got, err := m.DescribeFirewall(bg, "", fw.ARN) + require.NoError(t, err) + assert.Equal(t, "fw-1", got.Name) - list, _ := m.ListFirewalls(ctx) - if len(list) != 1 { - t.Fatalf("ListFirewalls: %+v", list) - } + list, next, err := m.ListFirewalls(bg, nil, nfdriver.ListOptions{}) + require.NoError(t, err) + assert.Len(t, list, 1) + assert.Empty(t, next) } func TestFirewallPolicyAndRuleGroup(t *testing.T) { m := newMock() - ctx := context.Background() - pol, err := m.CreateFirewallPolicy(ctx, nfdriver.CreateFirewallPolicyConfig{ - Name: "pol-1", StatelessDefaultActions: []string{"aws:forward_to_sfe"}, - }) - if err != nil || pol.ID == "" { - t.Fatalf("CreateFirewallPolicy: %v %+v", err, pol) - } + pol := seedPolicy(t, m, "pol-1") + assert.NotEmpty(t, pol.ID) - if _, err := m.DescribeFirewallPolicy(ctx, "pol-1", ""); err != nil { - t.Fatalf("DescribeFirewallPolicy: %v", err) - } + _, err := m.DescribeFirewallPolicy(bg, "pol-1", "") + require.NoError(t, err) - if _, err := m.DeleteFirewallPolicy(ctx, "pol-1", ""); err != nil { - t.Fatalf("DeleteFirewallPolicy: %v", err) - } + _, err = m.DeleteFirewallPolicy(bg, "pol-1", "") + require.NoError(t, err) - // Rule group: type is validated. - if _, err := m.CreateRuleGroup(ctx, nfdriver.CreateRuleGroupConfig{Name: "rg", Type: "BOGUS"}); !cerrors.IsInvalidArgument(err) { - t.Fatalf("bad rule group type: got %v, want InvalidArgument", err) - } + _, err = m.CreateRuleGroup(bg, nfdriver.CreateRuleGroupConfig{Name: "rg", Type: "BOGUS", Capacity: 1}) + assert.True(t, cerrors.IsInvalidArgument(err), "bad rule group type: %v", err) - rg, err := m.CreateRuleGroup(ctx, nfdriver.CreateRuleGroupConfig{Name: "rg-1", Type: "STATEFUL", Capacity: 100}) - if err != nil { - t.Fatalf("CreateRuleGroup: %v", err) - } + rg := seedRuleGroup(t, m, "rg-1", "STATEFUL", 100) - got, err := m.DescribeRuleGroup(ctx, "rg-1", "", "STATEFUL") - if err != nil || got.Capacity != 100 { - t.Fatalf("DescribeRuleGroup: %v %+v", err, got) - } + got, err := m.DescribeRuleGroup(bg, "rg-1", "", "STATEFUL") + require.NoError(t, err) + assert.Equal(t, 100, got.Capacity) - if _, err := m.DeleteRuleGroup(ctx, rg.Name, "", "STATEFUL"); err != nil { - t.Fatalf("DeleteRuleGroup: %v", err) - } + _, err = m.DeleteRuleGroup(bg, rg.Name, "", "STATEFUL") + require.NoError(t, err) - if _, err := m.DescribeRuleGroup(ctx, "rg-1", "", "STATEFUL"); !cerrors.IsNotFound(err) { - t.Fatalf("describe deleted rule group: got %v, want NotFound", err) - } + _, err = m.DescribeRuleGroup(bg, "rg-1", "", "STATEFUL") + assert.True(t, cerrors.IsNotFound(err), "describe deleted rule group: %v", err) } func TestFirewallDepth(t *testing.T) { m := newMock() - ctx := context.Background() + pol, fw := seedStack(t, m) + other := seedPolicy(t, m, "pol-2") - pol, err := m.CreateFirewallPolicy(ctx, nfdriver.CreateFirewallPolicyConfig{Name: "pol-dep"}) - if err != nil { - t.Fatalf("CreateFirewallPolicy: %v", err) - } + _, err := m.AssociateFirewallPolicy(bg, "fw-1", "arn:aws:network-firewall:us-east-1:000000000000:firewall-policy/nope", "") + assert.True(t, cerrors.IsInvalidArgument(err), "associate missing policy: %v", err) - fw, err := m.CreateFirewall(ctx, nfdriver.CreateFirewallConfig{Name: "fw-1", SubnetIDs: []string{"subnet-1"}}) - if err != nil { - t.Fatalf("CreateFirewall: %v", err) - } + _, err = m.AssociateFirewallPolicy(bg, "fw-1", other.ARN, "") + require.NoError(t, err) - // Associating a nonexistent policy is rejected. - if _, err := m.AssociateFirewallPolicy(ctx, "fw-1", "arn:nope"); !cerrors.IsInvalidArgument(err) { - t.Fatalf("associate missing policy: got %v, want InvalidArgument", err) - } + // pol-1 is free again; pol-2 is now in use. + _, err = m.DeleteFirewallPolicy(bg, "pol-2", "") + requireException(t, err, nfdriver.ExInvalidOperation) - if _, err := m.AssociateFirewallPolicy(ctx, "fw-1", pol.ARN); err != nil { - t.Fatalf("AssociateFirewallPolicy: %v", err) - } + _, err = m.DeleteFirewallPolicy(bg, "pol-1", "") + require.NoError(t, err) - // The policy is now in use, so deleting it is blocked. - if _, err := m.DeleteFirewallPolicy(ctx, "pol-dep", ""); !cerrors.IsFailedPrecondition(err) { - t.Fatalf("delete in-use policy: got %v, want FailedPrecondition", err) - } + _ = pol - assoc, err := m.AssociateSubnets(ctx, "fw-1", []string{"subnet-1", "subnet-2"}) - if err != nil || len(assoc.SubnetIDs) != 2 { - t.Fatalf("AssociateSubnets: %v %+v", err, assoc) - } + assoc, err := m.AssociateSubnets(bg, "fw-1", []string{"subnet-1", "subnet-2"}, "") + require.NoError(t, err) + assert.Len(t, assoc.SubnetIDs, 2) - dis, err := m.DisassociateSubnets(ctx, "fw-1", []string{"subnet-1"}) - if err != nil || len(dis.SubnetIDs) != 1 || dis.SubnetIDs[0] != "subnet-2" { - t.Fatalf("DisassociateSubnets: %v %+v", err, dis) - } + dis, err := m.DisassociateSubnets(bg, "fw-1", []string{"subnet-1"}, "") + require.NoError(t, err) + assert.Equal(t, []string{"subnet-2"}, dis.SubnetIDs) - prot, err := m.UpdateFirewallDeleteProtection(ctx, "fw-1", true) - if err != nil || !prot.DeleteProtection { - t.Fatalf("UpdateFirewallDeleteProtection: %v %+v", err, prot) - } + prot, err := m.UpdateFirewallDeleteProtection(bg, "fw-1", true, "") + require.NoError(t, err) + assert.True(t, prot.DeleteProtection) - if err := m.UpdateLoggingConfiguration(ctx, "fw-1", logConfigs("FLOW", "ALERT")); err != nil { - t.Fatalf("UpdateLoggingConfiguration: %v", err) - } + require.NoError(t, m.UpdateLoggingConfiguration(bg, "fw-1", &nfdriver.LoggingConfiguration{ + Destinations: []nfdriver.LogDestinationConfig{s3Dest("FLOW", "b")}, + })) + require.NoError(t, m.UpdateLoggingConfiguration(bg, "fw-1", &nfdriver.LoggingConfiguration{ + Destinations: []nfdriver.LogDestinationConfig{s3Dest("FLOW", "b"), s3Dest("ALERT", "b")}, + })) - logs, err := m.DescribeLoggingConfiguration(ctx, "fw-1") - if err != nil || len(logs) != 2 { - t.Fatalf("DescribeLoggingConfiguration: %v %+v", err, logs) - } + logs, err := m.DescribeLoggingConfiguration(bg, "fw-1") + require.NoError(t, err) + assert.Len(t, logs.Destinations, 2) - if err := m.TagResource(ctx, fw.ARN, map[string]string{"env": "prod"}); err != nil { - t.Fatalf("TagResource: %v", err) - } + require.NoError(t, m.TagResource(bg, fw.ARN, map[string]string{"env": "prod"})) - got, _ := m.DescribeFirewall(ctx, "fw-1", "") - if got.Tags["env"] != "prod" { - t.Fatalf("tag not applied: %+v", got.Tags) - } + got, _ := m.DescribeFirewall(bg, "fw-1", "") + assert.Equal(t, "prod", got.Tags["env"]) - if err := m.UntagResource(ctx, fw.ARN, []string{"env"}); err != nil { - t.Fatalf("UntagResource: %v", err) - } + require.NoError(t, m.UntagResource(bg, fw.ARN, []string{"env"})) - got, _ = m.DescribeFirewall(ctx, "fw-1", "") - if _, ok := got.Tags["env"]; ok { - t.Fatalf("tag not removed: %+v", got.Tags) - } + got, _ = m.DescribeFirewall(bg, "fw-1", "") + assert.NotContains(t, got.Tags, "env") - // Unknown firewall / ARN error paths. - if _, err := m.AssociateFirewallPolicy(ctx, "missing", "x"); !cerrors.IsNotFound(err) { - t.Fatalf("associate missing firewall: got %v, want NotFound", err) - } + _, err = m.AssociateFirewallPolicy(bg, "missing", pol.ARN, "") + assert.True(t, cerrors.IsNotFound(err), "associate missing firewall: %v", err) - if err := m.TagResource(ctx, "arn:nope", map[string]string{"a": "b"}); !cerrors.IsNotFound(err) { - t.Fatalf("tag unknown arn: got %v, want NotFound", err) - } + err = m.TagResource(bg, "arn:aws:network-firewall:us-east-1:000000000000:firewall/nope", map[string]string{"a": "b"}) + assert.True(t, cerrors.IsNotFound(err), "tag unknown arn: %v", err) } // TestFirewallConcurrentAccess exercises the mutex under the race detector: @@ -187,26 +223,23 @@ func TestFirewallDepth(t *testing.T) { // "concurrent map writes". Run with -race for it to be meaningful. func TestFirewallConcurrentAccess(t *testing.T) { m := newMock() - ctx := context.Background() - - if _, err := m.CreateFirewall(ctx, nfdriver.CreateFirewallConfig{Name: "fw-1"}); err != nil { - t.Fatalf("CreateFirewall: %v", err) - } - - fw, _ := m.DescribeFirewall(ctx, "fw-1", "") + _, fw := seedStack(t, m) var wg sync.WaitGroup + for i := 0; i < 20; i++ { wg.Add(1) go func() { defer wg.Done() - _ = m.UpdateLoggingConfiguration(ctx, "fw-1", logConfigs("FLOW", "ALERT")) - _, _ = m.DescribeLoggingConfiguration(ctx, "fw-1") - _, _ = m.DescribeFirewall(ctx, "fw-1", "") - _ = m.TagResource(ctx, fw.ARN, map[string]string{"k": "v"}) - _, _ = m.ListFirewalls(ctx) + _ = m.UpdateLoggingConfiguration(bg, "fw-1", &nfdriver.LoggingConfiguration{ + Destinations: []nfdriver.LogDestinationConfig{s3Dest("FLOW", "b")}, + }) + _, _ = m.DescribeLoggingConfiguration(bg, "fw-1") + _, _ = m.DescribeFirewall(bg, "fw-1", "") + _ = m.TagResource(bg, fw.ARN, map[string]string{"k": "v"}) + _, _, _ = m.ListFirewalls(bg, nil, nfdriver.ListOptions{}) }() } diff --git a/providers/aws/networkfirewall/pagination.go b/providers/aws/networkfirewall/pagination.go new file mode 100644 index 000000000..4f64cc06a --- /dev/null +++ b/providers/aws/networkfirewall/pagination.go @@ -0,0 +1,34 @@ +package networkfirewall + +import ( + cerrors "github.com/stackshy/cloudemu/v2/errors" + "github.com/stackshy/cloudemu/v2/internal/pagination" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +const ( + defaultPageSize = 100 + maxPageSize = 100 +) + +// paginate slices one page out of items (already in deterministic order) using +// the caller's MaxResults (1-100, default 100) and NextToken. A bad range or an +// undecodable token is a request error, never "page 1". +func paginate[T any](items []T, opts nfdriver.ListOptions) (page []T, nextToken string, err error) { + size := opts.MaxResults + + switch { + case size == 0: + size = defaultPageSize + case size < 1 || size > maxPageSize: + return nil, "", cerrors.Newf(cerrors.InvalidArgument, "MaxResults must be between 1 and %d", maxPageSize) + } + + pg, err := pagination.Paginate(items, opts.NextToken, size) + if err != nil { + // The only way Paginate fails is an undecodable token. + return nil, "", cerrors.New(cerrors.InvalidArgument, "NextToken is not valid") + } + + return pg.Items, pg.NextPageToken, nil +} diff --git a/providers/aws/networkfirewall/policy.go b/providers/aws/networkfirewall/policy.go new file mode 100644 index 000000000..f5b3ae6b6 --- /dev/null +++ b/providers/aws/networkfirewall/policy.go @@ -0,0 +1,278 @@ +package networkfirewall + +import ( + "context" + + cerrors "github.com/stackshy/cloudemu/v2/errors" + "github.com/stackshy/cloudemu/v2/internal/idgen" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +//nolint:gocritic // cfg matches the driver signature. +func (m *Mock) CreateFirewallPolicy(_ context.Context, cfg nfdriver.CreateFirewallPolicyConfig) (*nfdriver.FirewallPolicy, error) { + m.mu.Lock() + defer m.mu.Unlock() + + if err := validateName("FirewallPolicyName", cfg.Name); err != nil { + return nil, err + } + + if err := validateTags(cfg.Tags); err != nil { + return nil, err + } + + spec := policySpec{ + description: cfg.Description, statelessDefault: cfg.StatelessDefaultActions, + statelessFragmentDefault: cfg.StatelessFragmentDefaultActions, statefulDefault: cfg.StatefulDefaultActions, + statefulRefs: cfg.StatefulRuleGroupReferences, statelessRefs: cfg.StatelessRuleGroupReferences, + tlsARN: cfg.TLSInspectionConfigurationARN, extra: cfg.Extra, + } + if err := m.validatePolicy(&spec, nil); err != nil { + return nil, err + } + + p := &nfdriver.FirewallPolicy{ + Name: cfg.Name, + ARN: m.arn("firewall-policy", cfg.Name), + ID: idgen.GenerateID(""), + Description: cfg.Description, + StatelessDefaultActions: cloneStrings(cfg.StatelessDefaultActions), + StatelessFragmentDefaultActions: cloneStrings(cfg.StatelessFragmentDefaultActions), + StatefulDefaultActions: cloneStrings(cfg.StatefulDefaultActions), + StatefulRuleGroupReferences: cloneRuleGroupRefs(cfg.StatefulRuleGroupReferences), + StatelessRuleGroupReferences: cloneRuleGroupRefs(cfg.StatelessRuleGroupReferences), + TLSInspectionConfigurationARN: cfg.TLSInspectionConfigurationARN, + Extra: clonePolicyExtra(&cfg.Extra), + Status: statusActive, + LastModified: m.now(), + UpdateToken: newToken(), + Tags: copyTags(cfg.Tags), + } + if !m.policies.SetIfAbsent(cfg.Name, p) { + return nil, cerrors.Newf(cerrors.AlreadyExists, "firewall policy %q already exists", cfg.Name) + } + + return m.outPolicy(p), nil +} + +func (m *Mock) DescribeFirewallPolicy(_ context.Context, name, arn string) (*nfdriver.FirewallPolicy, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + if err := requireIdentifier("FirewallPolicy", name, arn); err != nil { + return nil, err + } + + p, ok := m.lookupPolicy(name, arn) + if !ok { + return nil, cerrors.Newf(cerrors.NotFound, "firewall policy %q not found", nonEmpty(name, arn)) + } + + return m.outPolicy(p), nil +} + +//nolint:gocritic // cfg matches the driver signature. +func (m *Mock) UpdateFirewallPolicy( + _ context.Context, name, arn string, cfg nfdriver.UpdateFirewallPolicyConfig, +) (*nfdriver.FirewallPolicy, error) { + m.mu.Lock() + defer m.mu.Unlock() + + if err := requireIdentifier("FirewallPolicy", name, arn); err != nil { + return nil, err + } + + if err := requireToken(cfg.UpdateToken); err != nil { + return nil, err + } + + p, ok := m.lookupPolicy(name, arn) + if !ok { + return nil, cerrors.Newf(cerrors.NotFound, "firewall policy %q not found", nonEmpty(name, arn)) + } + + if err := checkToken(p.UpdateToken, cfg.UpdateToken); err != nil { + return nil, err + } + + spec := policySpec{ + description: cfg.Description, statelessDefault: cfg.StatelessDefaultActions, + statelessFragmentDefault: cfg.StatelessFragmentDefaultActions, statefulDefault: cfg.StatefulDefaultActions, + statefulRefs: cfg.StatefulRuleGroupReferences, statelessRefs: cfg.StatelessRuleGroupReferences, + tlsARN: cfg.TLSInspectionConfigurationARN, extra: cfg.Extra, + } + if err := m.validatePolicy(&spec, p); err != nil { + return nil, err + } + + p.Description = cfg.Description + p.StatelessDefaultActions = cloneStrings(cfg.StatelessDefaultActions) + p.StatelessFragmentDefaultActions = cloneStrings(cfg.StatelessFragmentDefaultActions) + p.StatefulDefaultActions = cloneStrings(cfg.StatefulDefaultActions) + p.StatefulRuleGroupReferences = cloneRuleGroupRefs(cfg.StatefulRuleGroupReferences) + p.StatelessRuleGroupReferences = cloneRuleGroupRefs(cfg.StatelessRuleGroupReferences) + p.TLSInspectionConfigurationARN = cfg.TLSInspectionConfigurationARN + p.Extra = clonePolicyExtra(&cfg.Extra) + p.LastModified = m.now() + p.UpdateToken = newToken() + + return m.outPolicy(p), nil +} + +func (m *Mock) DeleteFirewallPolicy(_ context.Context, name, arn string) (*nfdriver.FirewallPolicy, error) { + m.mu.Lock() + defer m.mu.Unlock() + + if err := requireIdentifier("FirewallPolicy", name, arn); err != nil { + return nil, err + } + + p, ok := m.lookupPolicy(name, arn) + if !ok { + return nil, cerrors.Newf(cerrors.NotFound, "firewall policy %q not found", nonEmpty(name, arn)) + } + + if m.policyInUse(p.ARN) { + return nil, nfdriver.InvalidOperation("firewall policy %q is in use by a firewall", p.Name) + } + + out := m.outPolicy(p) + out.Status = statusDeleting + + m.policies.Delete(p.Name) + delete(m.resourcePolicies, p.ARN) + + return out, nil +} + +func (m *Mock) ListFirewallPolicies(_ context.Context, opts nfdriver.ListOptions) ([]nfdriver.FirewallPolicy, string, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + items, next, err := paginate(m.policies.SortedValues(), opts) + if err != nil { + return nil, "", err + } + + out := make([]nfdriver.FirewallPolicy, 0, len(items)) + for _, p := range items { + out = append(out, *m.outPolicy(p)) + } + + return out, next, nil +} + +func (m *Mock) lookupPolicy(name, arn string) (*nfdriver.FirewallPolicy, bool) { + if name != "" { + return m.policies.Get(name) + } + + for _, p := range m.policies.SortedValues() { + if p.ARN == arn { + return p, true + } + } + + return nil, false +} + +// policyExists reports whether a firewall policy with the given ARN is present. +func (m *Mock) policyExists(arn string) bool { + for _, p := range m.policies.SortedValues() { + if p.ARN == arn { + return true + } + } + + return false +} + +// policyInUse reports whether any firewall references the policy ARN. +func (m *Mock) policyInUse(arn string) bool { + return m.policyAssociationCount(arn) > 0 +} + +func (m *Mock) policyAssociationCount(arn string) int { + n := 0 + + for _, f := range m.firewalls.SortedValues() { + if f.PolicyARN == arn { + n++ + } + } + + return n +} + +// outPolicy returns a deep copy of the stored policy with the computed +// capacity, association count and status filled in. +func (m *Mock) outPolicy(p *nfdriver.FirewallPolicy) *nfdriver.FirewallPolicy { + out := *p + out.StatelessDefaultActions = cloneStrings(p.StatelessDefaultActions) + out.StatelessFragmentDefaultActions = cloneStrings(p.StatelessFragmentDefaultActions) + out.StatefulDefaultActions = cloneStrings(p.StatefulDefaultActions) + out.StatefulRuleGroupReferences = cloneRuleGroupRefs(p.StatefulRuleGroupReferences) + out.StatelessRuleGroupReferences = cloneRuleGroupRefs(p.StatelessRuleGroupReferences) + out.Extra = clonePolicyExtra(&p.Extra) + out.Tags = copyTags(p.Tags) + out.NumberOfAssociations = m.policyAssociationCount(p.ARN) + out.ConsumedStatelessRuleCapacity = m.referencedCapacity(p.StatelessRuleGroupReferences) + + stateful, domain := 0, 0 + + for _, r := range p.StatefulRuleGroupReferences { + rg, ok := m.ruleGroupByARN(r.ResourceARN) + if !ok { + continue + } + + if rg.Type == ruleTypeStatefulDomain { + domain += rg.Capacity + } else { + stateful += rg.Capacity + } + } + + out.ConsumedStatefulRuleCapacity = stateful + out.ConsumedStatefulDomainCapacity = domain + + return &out +} + +// referencedCapacity sums the capacity AWS reserves for referenced rule groups. +func (m *Mock) referencedCapacity(refs []nfdriver.RuleGroupReference) int { + total := 0 + + for _, r := range refs { + if rg, ok := m.ruleGroupByARN(r.ResourceARN); ok { + total += rg.Capacity + } + } + + return total +} + +func cloneRuleGroupRefs(refs []nfdriver.RuleGroupReference) []nfdriver.RuleGroupReference { + if len(refs) == 0 { + return nil + } + + out := make([]nfdriver.RuleGroupReference, len(refs)) + for i, r := range refs { + out[i] = nfdriver.RuleGroupReference{ + ResourceARN: r.ResourceARN, Priority: r.Priority, + Override: cloneRawJSON(r.Override), DeepThreatInspection: cloneBool(r.DeepThreatInspection), + } + } + + return out +} + +func clonePolicyExtra(e *nfdriver.PolicyExtra) nfdriver.PolicyExtra { + return nfdriver.PolicyExtra{ + StatelessCustomActions: cloneRawJSON(e.StatelessCustomActions), + PolicyVariables: cloneRawJSON(e.PolicyVariables), + StatefulEngineOptions: cloneRawJSON(e.StatefulEngineOptions), + EnableTLSSessionHolding: cloneBool(e.EnableTLSSessionHolding), + } +} diff --git a/providers/aws/networkfirewall/policy_actions.go b/providers/aws/networkfirewall/policy_actions.go new file mode 100644 index 000000000..147757fa2 --- /dev/null +++ b/providers/aws/networkfirewall/policy_actions.go @@ -0,0 +1,246 @@ +package networkfirewall + +import ( + "encoding/json" + + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +const ( + ruleOrderStrict = "STRICT_ORDER" + + minPriority = 1 + maxPriority = 65535 +) + +// Standard stateless default actions and the documented stateful default +// actions (AWS FirewallPolicy reference). +// +//nolint:gochecknoglobals // immutable enum value sets. +var ( + statelessStandardActions = []string{"aws:pass", "aws:drop", "aws:forward_to_sfe"} + statefulDefaultActions = []string{ + "aws:drop_strict", "aws:drop_established", "aws:alert_strict", "aws:alert_established", + "aws:drop_established_app_layer", "aws:alert_established_app_layer", + "aws:drop_established_app_layer_to_server", "aws:alert_established_app_layer_to_server", + } +) + +// policySpec is the validated shape shared by create and update. +type policySpec struct { + description string + statelessDefault []string + statelessFragmentDefault []string + statefulDefault []string + statefulRefs []nfdriver.RuleGroupReference + statelessRefs []nfdriver.RuleGroupReference + tlsARN string + extra nfdriver.PolicyExtra +} + +// validatePolicy applies the AWS rules for a firewall policy body. current is +// the stored policy on update (nil on create). +func (m *Mock) validatePolicy(s *policySpec, current *nfdriver.FirewallPolicy) error { + if err := validateDescription(s.description); err != nil { + return err + } + + strict, err := validatePolicyActions(s) + if err != nil { + return err + } + + return m.validatePolicyReferences(s, strict, current) +} + +// validatePolicyReferences checks the rule group references and the TLS +// inspection configuration the policy names. +func (m *Mock) validatePolicyReferences(s *policySpec, strict bool, current *nfdriver.FirewallPolicy) error { + if err := m.validateRefs("StatelessRuleGroupReferences", s.statelessRefs, true, []string{ruleTypeStateless}); err != nil { + return err + } + + if err := m.validateRefs("StatefulRuleGroupReferences", s.statefulRefs, strict, + []string{ruleTypeStateful, ruleTypeStatefulDomain}); err != nil { + return err + } + + return m.validatePolicyTLS(s, current) +} + +// validatePolicyActions checks the stateless and stateful default actions and +// reports whether the policy uses strict stateful rule ordering. +func validatePolicyActions(s *policySpec) (bool, error) { + custom, err := customActionNames(s.extra.StatelessCustomActions) + if err != nil { + return false, err + } + + strict, err := isStrictOrder(s.extra.StatefulEngineOptions) + if err != nil { + return false, err + } + + return strict, checkDefaultActions(s, custom, strict) +} + +func checkDefaultActions(s *policySpec, custom map[string]bool, strict bool) error { + if err := validateStatelessActions("StatelessDefaultActions", s.statelessDefault, custom); err != nil { + return err + } + + if err := validateStatelessActions("StatelessFragmentDefaultActions", s.statelessFragmentDefault, custom); err != nil { + return err + } + + return validateStatefulDefaults(s.statefulDefault, strict) +} + +// validateStatelessActions requires exactly one standard action; any other entry +// must name a custom action defined in the same policy. +func validateStatelessActions(field string, actions []string, custom map[string]bool) error { + if len(actions) == 0 { + return invalid("%s is required", field) + } + + standard := 0 + + for _, a := range actions { + switch { + case oneOf(a, statelessStandardActions...): + standard++ + case custom[a]: + default: + return invalid("%s entry %q is neither a standard action nor a defined custom action", field, a) + } + } + + if standard != 1 { + return invalid("%s must contain exactly one of %v", field, statelessStandardActions) + } + + return nil +} + +func validateStatefulDefaults(actions []string, strict bool) error { + if len(actions) == 0 { + return nil + } + + if !strict { + return invalid("StatefulDefaultActions is only valid with StatefulEngineOptions.RuleOrder %s", ruleOrderStrict) + } + + for _, a := range actions { + if !oneOf(a, statefulDefaultActions...) { + return invalid("StatefulDefaultActions entry %q is not valid", a) + } + } + + return nil +} + +// validateRefs checks rule group references: the group must exist with an +// allowed type, a priority is required where order matters, and priorities are +// unique within the list. +func (m *Mock) validateRefs(field string, refs []nfdriver.RuleGroupReference, needPriority bool, types []string) error { + seen := make(map[int]bool, len(refs)) + + for _, r := range refs { + if err := validateARN(field+" ResourceArn", r.ResourceARN); err != nil { + return err + } + + rg, ok := m.ruleGroupByARN(r.ResourceARN) + if !ok { + return invalid("%s: rule group %q not found", field, r.ResourceARN) + } + + if !oneOf(rg.Type, types...) { + return invalid("%s: rule group %q has type %s", field, r.ResourceARN, rg.Type) + } + + if !needPriority { + continue + } + + if r.Priority < minPriority || r.Priority > maxPriority { + return invalid("%s: Priority must be between %d and %d", field, minPriority, maxPriority) + } + + if seen[r.Priority] { + return invalid("%s: duplicate Priority %d", field, r.Priority) + } + + seen[r.Priority] = true + } + + return nil +} + +// validatePolicyTLS checks the TLS inspection configuration reference: it must +// exist, can only be replaced (never added or removed after create), and TLS +// session holding needs one. +func (m *Mock) validatePolicyTLS(s *policySpec, current *nfdriver.FirewallPolicy) error { + if s.tlsARN != "" { + if err := validateARN("TLSInspectionConfigurationArn", s.tlsARN); err != nil { + return err + } + + if _, ok := m.tlsByARN(s.tlsARN); !ok { + return invalid("TLS inspection configuration %q not found", s.tlsARN) + } + } + + if current != nil && (current.TLSInspectionConfigurationARN == "") != (s.tlsARN == "") { + return invalid("a TLS inspection configuration can only be replaced, not added or removed, after the policy is created") + } + + if s.extra.EnableTLSSessionHolding != nil && *s.extra.EnableTLSSessionHolding && s.tlsARN == "" { + return invalid("EnableTLSSessionHolding requires a TLS inspection configuration") + } + + return nil +} + +func customActionNames(raw json.RawMessage) (map[string]bool, error) { + names := map[string]bool{} + + if len(raw) == 0 { + return names, nil + } + + var actions []struct { + ActionName string `json:"ActionName"` + } + + if err := json.Unmarshal(raw, &actions); err != nil { + return nil, invalid("StatelessCustomActions is not valid: %v", err) + } + + for _, a := range actions { + names[a.ActionName] = true + } + + return names, nil +} + +func isStrictOrder(raw json.RawMessage) (bool, error) { + if len(raw) == 0 { + return false, nil + } + + var opts struct { + RuleOrder string `json:"RuleOrder"` + } + + if err := json.Unmarshal(raw, &opts); err != nil { + return false, invalid("StatefulEngineOptions is not valid: %v", err) + } + + if opts.RuleOrder != "" && !oneOf(opts.RuleOrder, "DEFAULT_ACTION_ORDER", ruleOrderStrict) { + return false, invalid("StatefulEngineOptions.RuleOrder %q is not valid", opts.RuleOrder) + } + + return opts.RuleOrder == ruleOrderStrict, nil +} diff --git a/providers/aws/networkfirewall/reference_test.go b/providers/aws/networkfirewall/reference_test.go new file mode 100644 index 000000000..cd62a108d --- /dev/null +++ b/providers/aws/networkfirewall/reference_test.go @@ -0,0 +1,395 @@ +package networkfirewall + +import ( + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + cerrors "github.com/stackshy/cloudemu/v2/errors" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +func refPolicy(name string, stateless, stateful []nfdriver.RuleGroupReference) nfdriver.CreateFirewallPolicyConfig { + return nfdriver.CreateFirewallPolicyConfig{ + Name: name, StatelessDefaultActions: standardActions, StatelessFragmentDefaultActions: standardActions, + StatelessRuleGroupReferences: stateless, StatefulRuleGroupReferences: stateful, + } +} + +func TestDeleteGuards_InvalidOperation(t *testing.T) { + m := newMock() + pol, fw := seedStack(t, m) + + _, err := m.UpdateFirewallDeleteProtection(bg, "fw-1", true, "") + require.NoError(t, err) + + _, err = m.DeleteFirewall(bg, "fw-1", "") + requireException(t, err, nfdriver.ExInvalidOperation) + + _, err = m.DeleteFirewallPolicy(bg, "pol-1", "") + requireException(t, err, nfdriver.ExInvalidOperation) + + rg := seedRuleGroup(t, m, "rg-1", "STATEFUL", 5) + _, err = m.CreateFirewallPolicy(bg, refPolicy("p2", nil, []nfdriver.RuleGroupReference{{ResourceARN: rg.ARN}})) + require.NoError(t, err) + + _, err = m.DeleteRuleGroup(bg, "rg-1", "", "STATEFUL") + requireException(t, err, nfdriver.ExInvalidOperation) + + _ = pol + _ = fw +} + +func TestDeleteRuleGroup_InUseByPolicy_Stateful_Stateless(t *testing.T) { + m := newMock() + sl := seedRuleGroup(t, m, "rg-sl", "STATELESS", 5) + sf := seedRuleGroup(t, m, "rg-sf", "STATEFUL", 5) + + p, err := m.CreateFirewallPolicy(bg, refPolicy("p", + []nfdriver.RuleGroupReference{{ResourceARN: sl.ARN, Priority: 10}}, + []nfdriver.RuleGroupReference{{ResourceARN: sf.ARN}})) + require.NoError(t, err) + + _, err = m.DeleteRuleGroup(bg, "rg-sl", "", "STATELESS") + requireException(t, err, nfdriver.ExInvalidOperation) + + _, err = m.DeleteRuleGroup(bg, "", sf.ARN, "") + requireException(t, err, nfdriver.ExInvalidOperation) + + // Dropping the references frees the rule groups. + _, err = m.UpdateFirewallPolicy(bg, "p", "", nfdriver.UpdateFirewallPolicyConfig{ + UpdateToken: p.UpdateToken, StatelessDefaultActions: standardActions, StatelessFragmentDefaultActions: standardActions, + }) + require.NoError(t, err) + + _, err = m.DeleteRuleGroup(bg, "rg-sl", "", "STATELESS") + require.NoError(t, err) + + _, err = m.DeleteRuleGroup(bg, "rg-sf", "", "STATEFUL") + require.NoError(t, err) +} + +func TestComputed_RuleGroupFields(t *testing.T) { + m, clock := newClockMock(t) + + stateless := []byte(`{"RulesSource":{"StatelessRulesAndCustomActions":{"StatelessRules":[` + + `{"Priority":1,"RuleDefinition":{"Actions":["aws:pass"],"MatchAttributes":{"Protocols":[6,17],` + + `"Sources":[{"AddressDefinition":"10.0.0.0/24"},{"AddressDefinition":"10.0.1.0/24"},{"AddressDefinition":"10.0.2.0/24"}]}}},` + + `{"Priority":2,"RuleDefinition":{"Actions":["aws:drop"],"MatchAttributes":{}}}]}}}`) + + sl, err := m.CreateRuleGroup(bg, nfdriver.CreateRuleGroupConfig{Name: "sl", Type: "STATELESS", Capacity: 10, Rules: stateless}) + require.NoError(t, err) + assert.Equal(t, 7, sl.ConsumedCapacity, "2 protocols x 3 sources = 6, plus 1 for the unconstrained rule") + assert.Equal(t, "ACTIVE", sl.Status) + assert.Equal(t, clock.Now(), sl.LastModified) + + sf, err := m.CreateRuleGroup(bg, nfdriver.CreateRuleGroupConfig{ + Name: "sf", Type: "STATEFUL", Capacity: 10, Rules: rulesString("r1", "# note", "", "r2"), + }) + require.NoError(t, err) + assert.Equal(t, 2, sf.ConsumedCapacity, "one unit per rule, comments and blanks excluded") + + structured, err := m.CreateRuleGroup(bg, nfdriver.CreateRuleGroupConfig{ + Name: "sf2", Type: "STATEFUL", Capacity: 10, Rules: []byte(`{"RulesSource":{"StatefulRules":[{"Action":"PASS"},{"Action":"DROP"},{"Action":"ALERT"}]}}`), + }) + require.NoError(t, err) + assert.Equal(t, 3, structured.ConsumedCapacity) + + _, err = m.CreateFirewallPolicy(bg, refPolicy("p", []nfdriver.RuleGroupReference{{ResourceARN: sl.ARN, Priority: 1}}, nil)) + require.NoError(t, err) + + got, _ := m.DescribeRuleGroup(bg, "sl", "", "STATELESS") + assert.Equal(t, 1, got.NumberOfAssociations) + + clock.Advance(time.Hour) + + later, _ := m.DescribeRuleGroup(bg, "sl", "", "STATELESS") + assert.Equal(t, got.LastModified, later.LastModified, "reads never move the timestamp") + + updated, err := m.UpdateRuleGroup(bg, "sl", "", "STATELESS", nfdriver.UpdateRuleGroupConfig{UpdateToken: got.UpdateToken, Description: "x"}) + require.NoError(t, err) + assert.True(t, updated.LastModified.After(got.LastModified), "a mutation does") +} + +func TestComputed_PolicyFields(t *testing.T) { + m := newMock() + sl := seedRuleGroup(t, m, "rg-sl", "STATELESS", 20) + sf := seedRuleGroup(t, m, "rg-sf", "STATEFUL", 30) + + domain, err := m.CreateRuleGroup(bg, nfdriver.CreateRuleGroupConfig{Name: "rg-d", Type: "STATEFUL_DOMAIN", Capacity: 40}) + require.NoError(t, err) + + p, err := m.CreateFirewallPolicy(bg, refPolicy("p", + []nfdriver.RuleGroupReference{{ResourceARN: sl.ARN, Priority: 1}}, + []nfdriver.RuleGroupReference{{ResourceARN: sf.ARN}, {ResourceARN: domain.ARN}})) + require.NoError(t, err) + + assert.Equal(t, "ACTIVE", p.Status) + assert.Equal(t, 20, p.ConsumedStatelessRuleCapacity) + assert.Equal(t, 30, p.ConsumedStatefulRuleCapacity) + assert.Equal(t, 40, p.ConsumedStatefulDomainCapacity) + assert.Equal(t, 0, p.NumberOfAssociations) + + seedFirewall(t, m, "fw-a", p.ARN) + seedFirewall(t, m, "fw-b", p.ARN) + + got, _ := m.DescribeFirewallPolicy(bg, "p", "") + assert.Equal(t, 2, got.NumberOfAssociations) +} + +func TestComputed_FirewallFields(t *testing.T) { + m := newMock() + _, fw := seedStack(t, m) + + assert.Equal(t, "READY", fw.Status) + assert.Equal(t, 0, fw.NumberOfAssociations) + + vpcAssociation(t, m, fw.ARN, "subnet-a") + vpcAssociation(t, m, fw.ARN, "subnet-b") + + got, _ := m.DescribeFirewall(bg, "fw-1", "") + assert.Equal(t, 2, got.NumberOfAssociations) +} + +func TestListFirewalls_VpcIdsFilter(t *testing.T) { + m := newMock() + pol := seedPolicy(t, m, "pol-1") + + for name, vpc := range map[string]string{"fw-a": "vpc-aa", "fw-b": "vpc-bb", "fw-c": "vpc-aa"} { + _, err := m.CreateFirewall(bg, nfdriver.CreateFirewallConfig{Name: name, PolicyARN: pol.ARN, VPCID: vpc}) + require.NoError(t, err) + } + + names := func(vpcs ...string) []string { + items, _, err := m.ListFirewalls(bg, vpcs, nfdriver.ListOptions{}) + require.NoError(t, err) + + out := make([]string, 0, len(items)) + for _, f := range items { + out = append(out, f.Name) + } + + return out + } + + assert.Equal(t, []string{"fw-a", "fw-b", "fw-c"}, names()) + assert.Equal(t, []string{"fw-a", "fw-c"}, names("vpc-aa")) + assert.Equal(t, []string{"fw-a", "fw-b", "fw-c"}, names("vpc-aa", "vpc-bb")) + assert.Empty(t, names("vpc-ff")) + + _, _, err := m.ListFirewalls(bg, []string{"not-a-vpc"}, nfdriver.ListOptions{}) + assert.True(t, cerrors.IsInvalidArgument(err), "%v", err) +} + +func TestListRuleGroups_TypeScopeFilters(t *testing.T) { + m := newMock() + seedRuleGroup(t, m, "a-sl", "STATELESS", 1) + seedRuleGroup(t, m, "b-sf", "STATEFUL", 1) + + count := func(f nfdriver.RuleGroupFilter) int { + items, _, err := m.ListRuleGroups(bg, f, nfdriver.ListOptions{}) + require.NoError(t, err) + + return len(items) + } + + assert.Equal(t, 2, count(nfdriver.RuleGroupFilter{})) + assert.Equal(t, 1, count(nfdriver.RuleGroupFilter{Type: "STATELESS"})) + assert.Equal(t, 2, count(nfdriver.RuleGroupFilter{Scope: "ACCOUNT"})) + assert.Equal(t, 0, count(nfdriver.RuleGroupFilter{Scope: "MANAGED"}), "the emulator has no AWS-managed rule groups") + assert.Equal(t, 0, count(nfdriver.RuleGroupFilter{ManagedType: "AWS_MANAGED_DOMAIN_LISTS"})) + + for _, bad := range []nfdriver.RuleGroupFilter{{Type: "X"}, {Scope: "X"}, {ManagedType: "X"}} { + _, _, err := m.ListRuleGroups(bg, bad, nfdriver.ListOptions{}) + assert.True(t, cerrors.IsInvalidArgument(err), "%+v: %v", bad, err) + } +} + +func TestARNFormats(t *testing.T) { + m := newMock() + pol, fw := seedStack(t, m) + sl := seedRuleGroup(t, m, "rg-sl", "STATELESS", 1) + sf := seedRuleGroup(t, m, "rg-sf", "STATEFUL", 1) + + prefix := "arn:aws:network-firewall:us-east-1:123456789012:" + assert.Equal(t, prefix+"firewall/fw-1", fw.ARN) + assert.Equal(t, prefix+"firewall-policy/pol-1", pol.ARN) + assert.Equal(t, prefix+"stateless-rulegroup/rg-sl", sl.ARN) + assert.Equal(t, prefix+"stateful-rulegroup/rg-sf", sf.ARN) + + assoc := vpcAssociation(t, m, fw.ARN, "subnet-a") + assert.Contains(t, assoc.ARN, prefix+"vpc-endpoint-association/") + + for arn, kind := range map[string]string{fw.ARN: "firewall", pol.ARN: "firewall-policy", sl.ARN: "stateless-rulegroup", "x": ""} { + assert.Equal(t, kind, arnKind(arn)) + } +} + +func TestMalformedARN_BeforeLookup(t *testing.T) { + m := newMock() + seedStack(t, m) + + for name, call := range map[string]func() error{ + "describe firewall": func() error { _, err := m.DescribeFirewall(bg, "", "bogus"); return err }, + "delete firewall": func() error { _, err := m.DeleteFirewall(bg, "", "bogus"); return err }, + "describe policy": func() error { _, err := m.DescribeFirewallPolicy(bg, "", "bogus"); return err }, + "delete policy": func() error { _, err := m.DeleteFirewallPolicy(bg, "", "bogus"); return err }, + "describe rule group": func() error { _, err := m.DescribeRuleGroup(bg, "", "bogus", ""); return err }, + "delete rule group": func() error { _, err := m.DeleteRuleGroup(bg, "", "bogus", ""); return err }, + "describe tls": func() error { _, err := m.DescribeTLSInspectionConfiguration(bg, "", "bogus"); return err }, + "describe assoc": func() error { _, err := m.DescribeVpcEndpointAssociation(bg, "bogus"); return err }, + "tag": func() error { return m.TagResource(bg, "bogus", map[string]string{"a": "b"}) }, + "untag": func() error { return m.UntagResource(bg, "bogus", nil) }, + "list tags": func() error { _, err := m.ListTagsForResource(bg, "bogus"); return err }, + "no identifier": func() error { _, err := m.DescribeFirewall(bg, "", ""); return err }, + "metadata": func() error { _, err := m.DescribeFirewallMetadata(bg, "bogus"); return err }, + } { + t.Run(name, func(t *testing.T) { + assert.True(t, cerrors.IsInvalidArgument(call()), "a malformed ARN is a request error, not NotFound") + }) + } + + _, err := m.DescribeFirewall(bg, "", "arn:aws:network-firewall:us-east-1:000000000000:firewall/ghost") + assert.True(t, cerrors.IsNotFound(err), "a well-formed unknown ARN is NotFound: %v", err) +} + +func TestNameAndARNDisagree(t *testing.T) { + m := newMock() + pol := seedPolicy(t, m, "pol-1") + seedFirewall(t, m, "fw-a", pol.ARN) + other := seedFirewall(t, m, "fw-b", pol.ARN) + + // When both are supplied the name selects the resource, as before this change. + got, err := m.DescribeFirewall(bg, "fw-a", other.ARN) + require.NoError(t, err) + assert.Equal(t, "fw-a", got.Name) +} + +func TestPagination_AllLists_PageSize1_Walk(t *testing.T) { + m := newMock() + pol := seedPolicy(t, m, "pol-b") + seedPolicy(t, m, "pol-c") + + for i := 0; i < 3; i++ { + seedFirewall(t, m, fmt.Sprintf("fw-%d", 3-i), pol.ARN) + seedRuleGroup(t, m, fmt.Sprintf("rg-%d", 3-i), "STATEFUL", 1) + + _, err := m.CreateTLSInspectionConfiguration(bg, nfdriver.CreateTLSInspectionConfig{ + Name: fmt.Sprintf("tls-%d", 3-i), Configuration: tlsConfigJSON("c"), + }) + require.NoError(t, err) + } + + // A policy created last sorts first, proving order is by name, not insertion. + seedPolicy(t, m, "pol-a") + + fw, _ := m.DescribeFirewall(bg, "fw-1", "") + for i := 0; i < 3; i++ { + vpcAssociation(t, m, fw.ARN, fmt.Sprintf("subnet-%d", i)) + } + + _, err := m.UpdateFirewallAnalysisSettings(bg, "fw-1", []string{"TLS_SNI"}, "") + require.NoError(t, err) + + for i := 0; i < 3; i++ { + _, err := m.StartAnalysisReport(bg, "fw-1", "", "TLS_SNI") + require.NoError(t, err) + } + + scope := nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"} + for i := 0; i < 3; i++ { + _, err := m.StartFlowFlush(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}) + require.NoError(t, err) + } + + lists := map[string]struct { + want int + page func(opts nfdriver.ListOptions) (int, string, error) + }{ + "firewalls": {3, func(o nfdriver.ListOptions) (int, string, error) { + v, n, err := m.ListFirewalls(bg, nil, o) + return len(v), n, err + }}, + "policies": {3, func(o nfdriver.ListOptions) (int, string, error) { + v, n, err := m.ListFirewallPolicies(bg, o) + return len(v), n, err + }}, + "rule groups": {3, func(o nfdriver.ListOptions) (int, string, error) { + v, n, err := m.ListRuleGroups(bg, nfdriver.RuleGroupFilter{}, o) + return len(v), n, err + }}, + "tls": {3, func(o nfdriver.ListOptions) (int, string, error) { + v, n, err := m.ListTLSInspectionConfigurations(bg, o) + return len(v), n, err + }}, + "associations": {3, func(o nfdriver.ListOptions) (int, string, error) { + v, n, err := m.ListVpcEndpointAssociations(bg, fw.ARN, o) + return len(v), n, err + }}, + "analysis reports": {3, func(o nfdriver.ListOptions) (int, string, error) { + v, n, err := m.ListAnalysisReports(bg, "fw-1", "", o) + return len(v), n, err + }}, + "flow operations": {3, func(o nfdriver.ListOptions) (int, string, error) { + v, n, err := m.ListFlowOperations(bg, scope, "", o) + return len(v), n, err + }}, + } + + for name, l := range lists { + t.Run(name, func(t *testing.T) { + seen, token := 0, "" + + for pages := 0; pages < 10; pages++ { + n, next, err := l.page(nfdriver.ListOptions{MaxResults: 1, NextToken: token}) + require.NoError(t, err) + assert.Equal(t, 1, n) + + seen += n + + if next == "" { + break + } + + token = next + } + + assert.Equal(t, l.want, seen, "every item exactly once") + }) + } + + // Firewalls come back sorted by name regardless of creation order. + items, _, err := m.ListFirewalls(bg, nil, nfdriver.ListOptions{}) + require.NoError(t, err) + assert.Equal(t, "fw-1", items[0].Name) + + pols, _, err := m.ListFirewallPolicies(bg, nfdriver.ListOptions{}) + require.NoError(t, err) + assert.Equal(t, "pol-a", pols[0].Name) +} + +func TestPagination_InvalidTokenAndRange(t *testing.T) { + m := newMock() + seedPolicy(t, m, "pol-1") + + for _, opts := range []nfdriver.ListOptions{{MaxResults: -1}, {MaxResults: 101}, {NextToken: "!!!not-a-token"}} { + _, _, err := m.ListFirewallPolicies(bg, opts) + assert.True(t, cerrors.IsInvalidArgument(err), "%+v: %v", opts, err) + } + + items, next, err := m.ListFirewallPolicies(bg, nfdriver.ListOptions{MaxResults: 100}) + require.NoError(t, err) + assert.Len(t, items, 1) + assert.Empty(t, next, "the last page has no token") +} + +func TestPagination_HugeMaxResults_Bounded(t *testing.T) { + m := newMock() + seedPolicy(t, m, "pol-1") + + _, _, err := m.ListFirewallPolicies(bg, nfdriver.ListOptions{MaxResults: 1 << 30}) + assert.True(t, cerrors.IsInvalidArgument(err), "MaxResults above 100 is rejected, never used to size an allocation: %v", err) +} diff --git a/providers/aws/networkfirewall/resource_policy.go b/providers/aws/networkfirewall/resource_policy.go new file mode 100644 index 000000000..5a4582766 --- /dev/null +++ b/providers/aws/networkfirewall/resource_policy.go @@ -0,0 +1,194 @@ +package networkfirewall + +import ( + "context" + "encoding/json" + + cerrors "github.com/stackshy/cloudemu/v2/errors" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +const maxResourcePolicyLen = 395000 + +// allowedPolicyActions are the actions a resource-sharing policy may grant, per +// shareable resource kind (AWS PutResourcePolicy reference). +// +//nolint:gochecknoglobals // immutable lookup table. +var allowedPolicyActions = map[string][]string{ + "stateful-rulegroup": ruleGroupPolicyActions, + "stateless-rulegroup": ruleGroupPolicyActions, + "firewall-policy": {"network-firewall:AssociateFirewallPolicy", "network-firewall:ListFirewallPolicies"}, + "firewall": { + "network-firewall:CreateVpcEndpointAssociation", "network-firewall:DescribeFirewallMetadata", "network-firewall:ListFirewalls", + }, +} + +//nolint:gochecknoglobals // immutable lookup table. +var ruleGroupPolicyActions = []string{ + "network-firewall:CreateFirewallPolicy", "network-firewall:UpdateFirewallPolicy", "network-firewall:ListRuleGroups", +} + +// PutResourcePolicy creates or replaces the resource-sharing policy of a rule +// group, firewall policy or firewall. +func (m *Mock) PutResourcePolicy(_ context.Context, resourceARN, policy string) error { + m.mu.Lock() + defer m.mu.Unlock() + + kind, err := m.shareableKind(resourceARN) + if err != nil { + return err + } + + if policy == "" || len(policy) > maxResourcePolicyLen { + return invalid("Policy must be 1 to %d characters", maxResourcePolicyLen) + } + + if err := validatePolicyDocument(policy, allowedPolicyActions[kind]); err != nil { + return err + } + + m.resourcePolicies[resourceARN] = policy + + return nil +} + +// DescribeResourcePolicy returns the resource-sharing policy of a resource. +func (m *Mock) DescribeResourcePolicy(_ context.Context, resourceARN string) (string, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + if _, err := m.shareableKind(resourceARN); err != nil { + return "", err + } + + p, ok := m.resourcePolicies[resourceARN] + if !ok { + return "", cerrors.Newf(cerrors.NotFound, "no resource policy is attached to %q", resourceARN) + } + + return p, nil +} + +// DeleteResourcePolicy removes the resource-sharing policy of a resource. +func (m *Mock) DeleteResourcePolicy(_ context.Context, resourceARN string) error { + m.mu.Lock() + defer m.mu.Unlock() + + if _, err := m.shareableKind(resourceARN); err != nil { + return err + } + + if _, ok := m.resourcePolicies[resourceARN]; !ok { + return cerrors.Newf(cerrors.NotFound, "no resource policy is attached to %q", resourceARN) + } + + delete(m.resourcePolicies, resourceARN) + + return nil +} + +// shareableKind validates the ARN and returns its resource kind when it names an +// existing rule group, firewall policy or firewall. +func (m *Mock) shareableKind(arn string) (string, error) { + if err := validateARN("ResourceArn", arn); err != nil { + return "", err + } + + kind := arnKind(arn) + if _, ok := allowedPolicyActions[kind]; !ok { + return "", invalid("ResourceArn %q is not a rule group, firewall policy or firewall", arn) + } + + exists := false + + switch kind { + case "firewall": + _, exists = m.firewallByARN(arn) + case "firewall-policy": + exists = m.policyExists(arn) + default: + _, exists = m.ruleGroupByARN(arn) + } + + if !exists { + return "", cerrors.Newf(cerrors.NotFound, "resource %q not found", arn) + } + + return kind, nil +} + +func (m *Mock) firewallByARN(arn string) (*nfdriver.Firewall, bool) { + return m.lookupFirewall("", arn) +} + +// validatePolicyDocument parses an IAM policy document and checks that every +// statement grants only the allowed actions. +func validatePolicyDocument(doc string, allowed []string) error { + var p struct { + Statement json.RawMessage `json:"Statement"` + } + + if err := json.Unmarshal([]byte(doc), &p); err != nil { + return nfdriver.InvalidResourcePolicy("the policy is not valid JSON: %v", err) + } + + stmts, err := policyStatements(p.Statement) + if err != nil { + return err + } + + if len(stmts) == 0 { + return nfdriver.InvalidResourcePolicy("the policy has no statements") + } + + for _, s := range stmts { + actions, err := stringOrList(s.Action) + if err != nil || len(actions) == 0 { + return nfdriver.InvalidResourcePolicy("every statement needs an Action") + } + + for _, a := range actions { + if !oneOf(a, allowed...) { + return nfdriver.InvalidResourcePolicy("action %q cannot be granted on this resource (allowed: %v)", a, allowed) + } + } + } + + return nil +} + +type policyStatement struct { + Action json.RawMessage `json:"Action"` +} + +func policyStatements(raw json.RawMessage) ([]policyStatement, error) { + if len(raw) == 0 { + return nil, nil + } + + var many []policyStatement + if err := json.Unmarshal(raw, &many); err == nil { + return many, nil + } + + var one policyStatement + if err := json.Unmarshal(raw, &one); err != nil { + return nil, nfdriver.InvalidResourcePolicy("the policy Statement is not valid") + } + + return []policyStatement{one}, nil +} + +func stringOrList(raw json.RawMessage) ([]string, error) { + var many []string + if err := json.Unmarshal(raw, &many); err == nil { + return many, nil + } + + var one string + if err := json.Unmarshal(raw, &one); err != nil { + return nil, err //nolint:wrapcheck // caller only tests for failure + } + + return []string{one}, nil +} diff --git a/providers/aws/networkfirewall/rule_group.go b/providers/aws/networkfirewall/rule_group.go new file mode 100644 index 000000000..f44d9f119 --- /dev/null +++ b/providers/aws/networkfirewall/rule_group.go @@ -0,0 +1,318 @@ +package networkfirewall + +import ( + "context" + "fmt" + + cerrors "github.com/stackshy/cloudemu/v2/errors" + "github.com/stackshy/cloudemu/v2/internal/idgen" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +// summaryRuleOptions are the SDK SummaryRuleOption values. +// +//nolint:gochecknoglobals // immutable enum value sets. +var ( + summaryRuleOptions = []string{"SID", "MSG", "METADATA"} + managedTypes = []string{"AWS_MANAGED_THREAT_SIGNATURES", "AWS_MANAGED_DOMAIN_LISTS", "ACTIVE_THREAT_DEFENSE", "PARTNER_MANAGED"} +) + +//nolint:gocritic // cfg matches the driver signature. +func (m *Mock) CreateRuleGroup(_ context.Context, cfg nfdriver.CreateRuleGroupConfig) (*nfdriver.RuleGroup, error) { + m.mu.Lock() + defer m.mu.Unlock() + + if err := validateName("RuleGroupName", cfg.Name); err != nil { + return nil, err + } + + if err := validateRuleGroupBody(cfg.Description, cfg.Tags, cfg.SummaryRuleOptions); err != nil { + return nil, err + } + + if !oneOf(cfg.Type, ruleTypeStateful, ruleTypeStateless, ruleTypeStatefulDomain) { + return nil, invalid("Type must be one of STATELESS, STATEFUL, STATEFUL_DOMAIN") + } + + if cfg.Capacity < 1 { + return nil, invalid("Capacity must be at least 1, got %d", cfg.Capacity) + } + + consumed, err := consumedCapacity(cfg.Rules) + if err != nil { + return nil, err + } + + if consumed > cfg.Capacity { + return nil, invalid("the rules need %d capacity units but Capacity is %d", consumed, cfg.Capacity) + } + + rgKind := "stateful-rulegroup" + if cfg.Type == ruleTypeStateless { + rgKind = "stateless-rulegroup" + } + + rg := &nfdriver.RuleGroup{ + Name: cfg.Name, + ARN: m.arn(rgKind, cfg.Name), + ID: idgen.GenerateID(""), + Type: cfg.Type, + Capacity: cfg.Capacity, + Description: cfg.Description, + Rules: cloneRawJSON(cfg.Rules), + SummaryRuleOptions: cloneStrings(cfg.SummaryRuleOptions), + Status: statusActive, + LastModified: m.now(), + UpdateToken: newToken(), + Tags: copyTags(cfg.Tags), + } + if !m.ruleGroups.SetIfAbsent(ruleGroupKey(cfg.Name, cfg.Type), rg) { + return nil, cerrors.Newf(cerrors.AlreadyExists, "rule group %q already exists", cfg.Name) + } + + return m.outRuleGroup(rg), nil +} + +func validateRuleGroupBody(description string, tags map[string]string, summaryOpts []string) error { + if err := validateDescription(description); err != nil { + return err + } + + if err := validateTags(tags); err != nil { + return err + } + + for _, o := range summaryOpts { + if !oneOf(o, summaryRuleOptions...) { + return invalid("SummaryConfiguration.RuleOptions value %q is not valid", o) + } + } + + return nil +} + +func (m *Mock) DescribeRuleGroup(_ context.Context, name, arn, ruleType string) (*nfdriver.RuleGroup, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + rg, err := m.findRuleGroup(name, arn, ruleType) + if err != nil { + return nil, err + } + + return m.outRuleGroup(rg), nil +} + +//nolint:gocritic // cfg matches the driver signature. +func (m *Mock) UpdateRuleGroup( + _ context.Context, name, arn, ruleType string, cfg nfdriver.UpdateRuleGroupConfig, +) (*nfdriver.RuleGroup, error) { + m.mu.Lock() + defer m.mu.Unlock() + + if err := requireToken(cfg.UpdateToken); err != nil { + return nil, err + } + + rg, err := m.findRuleGroup(name, arn, ruleType) + if err != nil { + return nil, err + } + + if err = checkToken(rg.UpdateToken, cfg.UpdateToken); err != nil { + return nil, err + } + + if err = validateRuleGroupBody(cfg.Description, nil, cfg.SummaryRuleOptions); err != nil { + return nil, err + } + + rules := rg.Rules + if len(cfg.Rules) > 0 { + rules = cfg.Rules + } + + consumed, err := consumedCapacity(rules) + if err != nil { + return nil, err + } + + if consumed > rg.Capacity { + return nil, invalid("the rules need %d capacity units but the rule group capacity is %d", consumed, rg.Capacity) + } + + rg.Description = cfg.Description + rg.Rules = cloneRawJSON(rules) + + if cfg.SummaryRuleOptions != nil { + rg.SummaryRuleOptions = cloneStrings(cfg.SummaryRuleOptions) + } + + rg.LastModified = m.now() + rg.UpdateToken = newToken() + + return m.outRuleGroup(rg), nil +} + +func (m *Mock) DeleteRuleGroup(_ context.Context, name, arn, ruleType string) (*nfdriver.RuleGroup, error) { + m.mu.Lock() + defer m.mu.Unlock() + + rg, err := m.findRuleGroup(name, arn, ruleType) + if err != nil { + return nil, err + } + + if n := m.ruleGroupRefCount(rg.ARN); n > 0 { + return nil, nfdriver.InvalidOperation("rule group %q is referenced by %d firewall policy(ies)", rg.Name, n) + } + + out := m.outRuleGroup(rg) + out.Status = statusDeleting + + m.ruleGroups.Delete(ruleGroupKey(rg.Name, rg.Type)) + delete(m.resourcePolicies, rg.ARN) + + return out, nil +} + +func (m *Mock) ListRuleGroups( + _ context.Context, filter nfdriver.RuleGroupFilter, opts nfdriver.ListOptions, +) ([]nfdriver.RuleGroup, string, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + if err := validateRuleGroupFilter(filter); err != nil { + return nil, "", err + } + + items, next, err := paginate(m.matchRuleGroups(filter), opts) + if err != nil { + return nil, "", err + } + + out := make([]nfdriver.RuleGroup, 0, len(items)) + for _, rg := range items { + out = append(out, *m.outRuleGroup(rg)) + } + + return out, next, nil +} + +func validateRuleGroupFilter(f nfdriver.RuleGroupFilter) error { + if f.Type != "" && !oneOf(f.Type, ruleTypeStateful, ruleTypeStateless, ruleTypeStatefulDomain) { + return invalid("Type %q is not valid", f.Type) + } + + if f.Scope != "" && !oneOf(f.Scope, "MANAGED", "ACCOUNT") { + return invalid("Scope %q is not valid", f.Scope) + } + + if f.ManagedType != "" && !oneOf(f.ManagedType, managedTypes...) { + return invalid("ManagedType %q is not valid", f.ManagedType) + } + + return nil +} + +// matchRuleGroups returns the rule groups a filter selects, in name order. +// Every rule group the emulator holds is account-owned, so a MANAGED scope or a +// ManagedType selects none. +func (m *Mock) matchRuleGroups(f nfdriver.RuleGroupFilter) []*nfdriver.RuleGroup { + if f.Scope == "MANAGED" || f.ManagedType != "" { + return nil + } + + var matched []*nfdriver.RuleGroup + + for _, rg := range m.ruleGroups.SortedValues() { + if f.Type == "" || rg.Type == f.Type { + matched = append(matched, rg) + } + } + + return matched +} + +// findRuleGroup resolves a rule group by name+type or by ARN, validating the +// identifier first. +func (m *Mock) findRuleGroup(name, arn, ruleType string) (*nfdriver.RuleGroup, error) { + if err := requireIdentifier("RuleGroup", name, arn); err != nil { + return nil, err + } + + if name != "" && ruleType != "" && !oneOf(ruleType, ruleTypeStateful, ruleTypeStateless, ruleTypeStatefulDomain) { + return nil, invalid("Type %q is not valid", ruleType) + } + + rg, ok := m.lookupRuleGroup(name, arn, ruleType) + if !ok { + return nil, cerrors.Newf(cerrors.NotFound, "rule group %q not found", nonEmpty(name, arn)) + } + + return rg, nil +} + +func (m *Mock) lookupRuleGroup(name, arn, ruleType string) (*nfdriver.RuleGroup, bool) { + if name != "" && ruleType != "" { + return m.ruleGroups.Get(ruleGroupKey(name, ruleType)) + } + + for _, rg := range m.ruleGroups.SortedValues() { + if (name != "" && rg.Name == name) || (arn != "" && rg.ARN == arn) { + return rg, true + } + } + + return nil, false +} + +func (m *Mock) ruleGroupByARN(arn string) (*nfdriver.RuleGroup, bool) { + for _, rg := range m.ruleGroups.SortedValues() { + if rg.ARN == arn { + return rg, true + } + } + + return nil, false +} + +// ruleGroupRefCount counts the firewall policies that reference the rule group. +func (m *Mock) ruleGroupRefCount(arn string) int { + n := 0 + + for _, p := range m.policies.SortedValues() { + if refsContain(p.StatefulRuleGroupReferences, arn) || refsContain(p.StatelessRuleGroupReferences, arn) { + n++ + } + } + + return n +} + +func refsContain(refs []nfdriver.RuleGroupReference, arn string) bool { + for _, r := range refs { + if r.ResourceARN == arn { + return true + } + } + + return false +} + +func ruleGroupKey(name, ruleType string) string { + return fmt.Sprintf("%s/%s", ruleType, name) +} + +// outRuleGroup returns a deep copy of the stored rule group with the computed +// consumed capacity and association count filled in. +func (m *Mock) outRuleGroup(rg *nfdriver.RuleGroup) *nfdriver.RuleGroup { + out := *rg + out.Rules = cloneRawJSON(rg.Rules) + out.SummaryRuleOptions = cloneStrings(rg.SummaryRuleOptions) + out.Tags = copyTags(rg.Tags) + out.NumberOfAssociations = m.ruleGroupRefCount(rg.ARN) + out.ConsumedCapacity, _ = consumedCapacity(rg.Rules) + + return &out +} diff --git a/providers/aws/networkfirewall/snapshot.go b/providers/aws/networkfirewall/snapshot.go index 684d66868..0a355e5b1 100644 --- a/providers/aws/networkfirewall/snapshot.go +++ b/providers/aws/networkfirewall/snapshot.go @@ -13,38 +13,57 @@ var _ snapshot.Snapshottable = (*Mock)(nil) // networkfirewallSnapshot is the full serialized state of the AWS Network // Firewall mock. Every memstore store holds a fully-exported *nfdriver pointer -// type (Firewall, FirewallPolicy, RuleGroup), so each round-trips through the -// generic memstore helper under its exact key: firewalls/policies by name, rule -// groups by the "TYPE/name" composite key, so DescribeRuleGroup's type-qualified -// lookup keeps working after a restore. The mu-guarded logging map (firewall -// name -> log types) is captured beside the stores. The wired opts is -// intentionally not serialized. +// type, so each round-trips through the generic memstore helper under its exact +// key: firewalls/policies/TLS configs by name, rule groups by the "TYPE/name" +// composite key (so DescribeRuleGroup's type-qualified lookup keeps working +// after a restore), VPC endpoint associations by ARN, flow operations and +// analysis reports by id. The mu-guarded logging and resource-policy maps are +// captured beside the stores. The wired opts is intentionally not serialized. +// Fields added after the first release are additive, so older snapshots load. type networkfirewallSnapshot struct { - Firewalls json.RawMessage `json:"firewalls,omitempty"` - Policies json.RawMessage `json:"policies,omitempty"` - RuleGroups json.RawMessage `json:"ruleGroups,omitempty"` - Logging map[string][]nfdriver.LogDestinationConfig `json:"logging,omitempty"` + Firewalls json.RawMessage `json:"firewalls,omitempty"` + Policies json.RawMessage `json:"policies,omitempty"` + RuleGroups json.RawMessage `json:"ruleGroups,omitempty"` + TLSConfigs json.RawMessage `json:"tlsConfigs,omitempty"` + Associations json.RawMessage `json:"associations,omitempty"` + FlowOperations json.RawMessage `json:"flowOperations,omitempty"` + AnalysisReports json.RawMessage `json:"analysisReports,omitempty"` + // Logging maps a firewall name to its logging configuration. Snapshots + // written before the monitoring-dashboard switch stored a bare destination + // array per firewall; Restore accepts both shapes. + Logging map[string]json.RawMessage `json:"logging,omitempty"` + ResourcePolicies map[string]string `json:"resourcePolicies,omitempty"` } // Snapshot captures the mock's entire state as JSON. includeAssets is unused. Network Firewall is // control-plane only and holds no bulk object bodies. func (m *Mock) Snapshot(_ context.Context, _ bool) (json.RawMessage, error) { + m.mu.RLock() + defer m.mu.RUnlock() + var snap networkfirewallSnapshot if err := m.snapshotStores(&snap); err != nil { return nil, err } - m.mu.RLock() - logging := make(map[string][]nfdriver.LogDestinationConfig, len(m.logging)) + if len(m.logging) > 0 { + snap.Logging = make(map[string]json.RawMessage, len(m.logging)) - for name, configs := range m.logging { - logging[name] = cloneLogConfigs(configs) - } + for name, cfg := range m.logging { + b, err := json.Marshal(cfg) + if err != nil { + return nil, fmt.Errorf("networkfirewall: snapshot logging: %w", err) + } - m.mu.RUnlock() + snap.Logging[name] = b + } + } - if len(logging) > 0 { - snap.Logging = logging + if len(m.resourcePolicies) > 0 { + snap.ResourcePolicies = make(map[string]string, len(m.resourcePolicies)) + for arn, p := range m.resourcePolicies { + snap.ResourcePolicies[arn] = p + } } return json.Marshal(snap) @@ -58,6 +77,10 @@ func (m *Mock) snapshotStores(snap *networkfirewallSnapshot) error { {&snap.Firewalls, m.firewalls.Snapshot}, {&snap.Policies, m.policies.Snapshot}, {&snap.RuleGroups, m.ruleGroups.Snapshot}, + {&snap.TLSConfigs, m.tlsConfigs.Snapshot}, + {&snap.Associations, m.associations.Snapshot}, + {&snap.FlowOperations, m.flowOperations.Snapshot}, + {&snap.AnalysisReports, m.analysisReports.Snapshot}, } for _, d := range dumps { @@ -73,27 +96,66 @@ func (m *Mock) snapshotStores(snap *networkfirewallSnapshot) error { } // Restore rebuilds the mock's state under the original identities: every -// firewall/policy/rule-group name and ARN (and the ARN cross-references records -// hold) is preserved, so a restore is transparent to clients. +// resource name and ARN (and the ARN cross-references records hold) is +// preserved, so a restore is transparent to clients. State written before update +// tokens existed gets a freshly minted token per resource. func (m *Mock) Restore(_ context.Context, data json.RawMessage) error { var snap networkfirewallSnapshot if err := json.Unmarshal(data, &snap); err != nil { return fmt.Errorf("networkfirewall: parse snapshot: %w", err) } + m.mu.Lock() + defer m.mu.Unlock() + if err := m.restoreStores(&snap); err != nil { return err } - m.mu.Lock() - if snap.Logging != nil { - m.logging = snap.Logging + logging, err := decodeLogging(snap.Logging) + if err != nil { + return err } - m.mu.Unlock() + + if logging != nil { + m.logging = logging + } + + if snap.ResourcePolicies != nil { + m.resourcePolicies = snap.ResourcePolicies + } + + m.backfillRestoredState() return nil } +// decodeLogging parses the snapshot's logging map, accepting the current object +// shape and the older bare destination array. +func decodeLogging(raw map[string]json.RawMessage) (map[string]*nfdriver.LoggingConfiguration, error) { + if raw == nil { + return nil, nil //nolint:nilnil // nil means "no logging in the snapshot" + } + + out := make(map[string]*nfdriver.LoggingConfiguration, len(raw)) + + for name, b := range raw { + var cfg nfdriver.LoggingConfiguration + + if len(b) > 0 && b[0] == '[' { + if err := json.Unmarshal(b, &cfg.Destinations); err != nil { + return nil, fmt.Errorf("networkfirewall: restore logging: %w", err) + } + } else if err := json.Unmarshal(b, &cfg); err != nil { + return nil, fmt.Errorf("networkfirewall: restore logging: %w", err) + } + + out[name] = &cfg + } + + return out, nil +} + func (m *Mock) restoreStores(snap *networkfirewallSnapshot) error { loads := []struct { src json.RawMessage @@ -102,6 +164,10 @@ func (m *Mock) restoreStores(snap *networkfirewallSnapshot) error { {snap.Firewalls, m.firewalls.LoadSnapshot}, {snap.Policies, m.policies.LoadSnapshot}, {snap.RuleGroups, m.ruleGroups.LoadSnapshot}, + {snap.TLSConfigs, m.tlsConfigs.LoadSnapshot}, + {snap.Associations, m.associations.LoadSnapshot}, + {snap.FlowOperations, m.flowOperations.LoadSnapshot}, + {snap.AnalysisReports, m.analysisReports.LoadSnapshot}, } for _, l := range loads { @@ -116,3 +182,38 @@ func (m *Mock) restoreStores(snap *networkfirewallSnapshot) error { return nil } + +// backfillRestoredState gives state saved before this release what it lacks: an +// update token and an ACTIVE status on every resource that has them. +func (m *Mock) backfillRestoredState() { + for _, f := range m.firewalls.SortedValues() { + ensureToken(&f.UpdateToken) + } + + for _, p := range m.policies.SortedValues() { + ensureToken(&p.UpdateToken) + ensureActive(&p.Status) + } + + for _, rg := range m.ruleGroups.SortedValues() { + ensureToken(&rg.UpdateToken) + ensureActive(&rg.Status) + } + + for _, t := range m.tlsConfigs.SortedValues() { + ensureToken(&t.UpdateToken) + ensureActive(&t.Status) + } +} + +func ensureToken(token *string) { + if *token == "" { + *token = newToken() + } +} + +func ensureActive(status *string) { + if *status == "" { + *status = statusActive + } +} diff --git a/providers/aws/networkfirewall/snapshot_test.go b/providers/aws/networkfirewall/snapshot_test.go index 109a50fb7..fcefe29de 100644 --- a/providers/aws/networkfirewall/snapshot_test.go +++ b/providers/aws/networkfirewall/snapshot_test.go @@ -1,72 +1,115 @@ package networkfirewall import ( - "context" + "encoding/json" "testing" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" ) // TestSnapshotRoundTripNetworkFirewall proves a snapshot/restore round-trip -// preserves the firewall/policy/rule-group stores and the mu-guarded logging map -// under their original identities. +// preserves every store, the logging and resource-policy maps and the update +// tokens under their original identities. func TestSnapshotRoundTripNetworkFirewall(t *testing.T) { - ctx := context.Background() src := newMock() + pol, fw := seedStack(t, src) + + _, err := src.CreateRuleGroup(bg, nfdriver.CreateRuleGroupConfig{Name: "rg-1", Type: "STATEFUL", Capacity: 100}) + require.NoError(t, err) - pol, err := src.CreateFirewallPolicy(ctx, nfdriver.CreateFirewallPolicyConfig{ - Name: "pol-1", Description: "policy one", + _, err = src.CreateTLSInspectionConfiguration(bg, nfdriver.CreateTLSInspectionConfig{ + Name: "tls-1", Configuration: tlsConfigJSON("arn:aws:acm:us-east-1:000000000000:certificate/c1"), }) - if err != nil { - t.Fatalf("create policy: %v", err) - } + require.NoError(t, err) - fw, err := src.CreateFirewall(ctx, nfdriver.CreateFirewallConfig{ - Name: "fw-1", VPCID: "vpc-1", SubnetIDs: []string{"subnet-1"}, PolicyARN: pol.ARN, + assoc, err := src.CreateVpcEndpointAssociation(bg, nfdriver.CreateVPCEndpointAssociationConfig{ + FirewallARN: fw.ARN, VPCID: "vpc-2b", SubnetID: "subnet-9", }) - if err != nil { - t.Fatalf("create firewall: %v", err) - } + require.NoError(t, err) - if _, err := src.CreateRuleGroup(ctx, nfdriver.CreateRuleGroupConfig{ - Name: "rg-1", Type: "STATEFUL", Capacity: 100, - }); err != nil { - t.Fatalf("create rule group: %v", err) - } + require.NoError(t, src.UpdateLoggingConfiguration(bg, "fw-1", &nfdriver.LoggingConfiguration{ + Destinations: []nfdriver.LogDestinationConfig{s3Dest("FLOW", "b")}, + })) + require.NoError(t, src.PutResourcePolicy(bg, pol.ARN, policyDoc("network-firewall:AssociateFirewallPolicy"))) - if err := src.UpdateLoggingConfiguration(ctx, "fw-1", logConfigs("FLOW", "ALERT")); err != nil { - t.Fatalf("update logging: %v", err) - } + flow, err := src.StartFlowFlush(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}) + require.NoError(t, err) - raw, err := src.Snapshot(ctx, true) - if err != nil { - t.Fatalf("snapshot: %v", err) - } + _, err = src.UpdateFirewallAnalysisSettings(bg, "fw-1", []string{"TLS_SNI"}, "") + require.NoError(t, err) + + rep, err := src.StartAnalysisReport(bg, "fw-1", "", "TLS_SNI") + require.NoError(t, err) + + raw, err := src.Snapshot(bg, true) + require.NoError(t, err) dst := newMock() - if err := dst.Restore(ctx, raw); err != nil { - t.Fatalf("restore: %v", err) - } + require.NoError(t, dst.Restore(bg, raw)) - gotFw, err := dst.DescribeFirewall(ctx, "fw-1", "") - if err != nil || gotFw.ARN != fw.ARN || gotFw.PolicyARN != pol.ARN { - t.Fatalf("restored firewall = %+v, err %v", gotFw, err) - } + gotFw, err := dst.DescribeFirewall(bg, "fw-1", "") + require.NoError(t, err) + assert.Equal(t, pol.ARN, gotFw.PolicyARN) + assert.Equal(t, 1, gotFw.NumberOfAssociations) - gotPol, err := dst.DescribeFirewallPolicy(ctx, "pol-1", "") - if err != nil || gotPol.Description != "policy one" { - t.Fatalf("restored policy = %+v, err %v", gotPol, err) - } + srcFw, _ := src.DescribeFirewall(bg, "fw-1", "") + assert.Equal(t, srcFw.UpdateToken, gotFw.UpdateToken, "tokens survive a restore") - // Rule group keyed by "TYPE/name" resolves through the type-qualified lookup. - gotRg, err := dst.DescribeRuleGroup(ctx, "rg-1", "", "STATEFUL") - if err != nil || gotRg.Capacity != 100 { - t.Fatalf("restored rule group = %+v, err %v", gotRg, err) - } + gotRg, err := dst.DescribeRuleGroup(bg, "rg-1", "", "STATEFUL") + require.NoError(t, err) + assert.Equal(t, 100, gotRg.Capacity) + + _, err = dst.DescribeTLSInspectionConfiguration(bg, "tls-1", "") + require.NoError(t, err) + + _, err = dst.DescribeVpcEndpointAssociation(bg, assoc.ARN) + require.NoError(t, err) + + logs, err := dst.DescribeLoggingConfiguration(bg, "fw-1") + require.NoError(t, err) + require.Len(t, logs.Destinations, 1) + assert.Equal(t, "FLOW", logs.Destinations[0].LogType) + + policy, err := dst.DescribeResourcePolicy(bg, pol.ARN) + require.NoError(t, err) + assert.Contains(t, policy, "AssociateFirewallPolicy") + + _, err = dst.DescribeFlowOperation(bg, nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}, flow.ID) + require.NoError(t, err) - // Logging (mu-guarded) survived. - logs, err := dst.DescribeLoggingConfiguration(ctx, "fw-1") - if err != nil || len(logs) != 2 || logs[0].LogType != "FLOW" || logs[1].LogType != "ALERT" { - t.Fatalf("restored logging = %+v, err %v", logs, err) + _, err = dst.GetAnalysisReport(bg, "fw-1", "", rep.ID) + require.NoError(t, err) +} + +// TestRestoreLegacySnapshot loads state written before update tokens, status +// fields and the logging-configuration object existed. +func TestRestoreLegacySnapshot(t *testing.T) { + legacy := map[string]any{ + "firewalls": json.RawMessage(`{"fw-old":{"Name":"fw-old","ARN":"arn:aws:network-firewall:us-east-1:000000000000:firewall/fw-old","VPCID":"vpc-1","Status":"READY"}}`), + "policies": json.RawMessage(`{"pol-old":{"Name":"pol-old","ARN":"arn:aws:network-firewall:us-east-1:000000000000:firewall-policy/pol-old"}}`), + "logging": json.RawMessage(`{"fw-old":[{"LogType":"FLOW","LogDestinationType":"S3","LogDestination":{"bucketName":"b"}}]}`), } + raw, err := json.Marshal(legacy) + require.NoError(t, err) + + m := newMock() + require.NoError(t, m.Restore(bg, raw)) + + fw, err := m.DescribeFirewall(bg, "fw-old", "") + require.NoError(t, err) + assert.Regexp(t, `^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$`, fw.UpdateToken) + assert.False(t, fw.SubnetChangeProtection) + + pol, err := m.DescribeFirewallPolicy(bg, "pol-old", "") + require.NoError(t, err) + assert.NotEmpty(t, pol.UpdateToken) + assert.Equal(t, "ACTIVE", pol.Status) + + logs, err := m.DescribeLoggingConfiguration(bg, "fw-old") + require.NoError(t, err) + require.Len(t, logs.Destinations, 1) + assert.Equal(t, "S3", logs.Destinations[0].LogDestinationType) } diff --git a/providers/aws/networkfirewall/tags.go b/providers/aws/networkfirewall/tags.go new file mode 100644 index 000000000..1ddf8d1e5 --- /dev/null +++ b/providers/aws/networkfirewall/tags.go @@ -0,0 +1,131 @@ +package networkfirewall + +import ( + "context" + + cerrors "github.com/stackshy/cloudemu/v2/errors" +) + +// TagResource adds tags to any taggable resource (firewall, policy, rule group, +// TLS inspection configuration, VPC endpoint association) by ARN. Tagging does +// not rotate the resource's update token. +func (m *Mock) TagResource(_ context.Context, arn string, tags map[string]string) error { + m.mu.Lock() + defer m.mu.Unlock() + + if err := validateARN("ResourceArn", arn); err != nil { + return err + } + + t := m.taggableByARN(arn) + if t == nil { + return cerrors.Newf(cerrors.NotFound, "resource %q not found", arn) + } + + if len(t)+len(tags) > maxTags { + return invalid("at most %d tags are allowed", maxTags) + } + + for k, v := range tags { + t[k] = v + } + + return nil +} + +// UntagResource removes tags from a resource by ARN. +func (m *Mock) UntagResource(_ context.Context, arn string, keys []string) error { + m.mu.Lock() + defer m.mu.Unlock() + + if err := validateARN("ResourceArn", arn); err != nil { + return err + } + + t := m.taggableByARN(arn) + if t == nil { + return cerrors.Newf(cerrors.NotFound, "resource %q not found", arn) + } + + for _, k := range keys { + delete(t, k) + } + + return nil +} + +// ListTagsForResource returns a copy of the tags on the resource with the given ARN. +func (m *Mock) ListTagsForResource(_ context.Context, arn string) (map[string]string, error) { + m.mu.Lock() + defer m.mu.Unlock() + + if err := validateARN("ResourceArn", arn); err != nil { + return nil, err + } + + t := m.taggableByARN(arn) + if t == nil { + return nil, cerrors.Newf(cerrors.NotFound, "resource %q not found", arn) + } + + return copyTags(t), nil +} + +// taggableByARN returns the mutable Tags map of the resource with the given ARN, +// creating it if nil, or nil when no resource matches. +func (m *Mock) taggableByARN(arn string) map[string]string { + for _, f := range m.firewalls.SortedValues() { + if f.ARN == arn { + if f.Tags == nil { + f.Tags = map[string]string{} + } + + return f.Tags + } + } + + for _, p := range m.policies.SortedValues() { + if p.ARN == arn { + if p.Tags == nil { + p.Tags = map[string]string{} + } + + return p.Tags + } + } + + for _, rg := range m.ruleGroups.SortedValues() { + if rg.ARN == arn { + if rg.Tags == nil { + rg.Tags = map[string]string{} + } + + return rg.Tags + } + } + + return m.taggableExtra(arn) +} + +// taggableExtra covers the resource families added after the original three. +func (m *Mock) taggableExtra(arn string) map[string]string { + for _, t := range m.tlsConfigs.SortedValues() { + if t.ARN == arn { + if t.Tags == nil { + t.Tags = map[string]string{} + } + + return t.Tags + } + } + + if a, ok := m.associations.Get(arn); ok { + if a.Tags == nil { + a.Tags = map[string]string{} + } + + return a.Tags + } + + return nil +} diff --git a/providers/aws/networkfirewall/tls_inspection.go b/providers/aws/networkfirewall/tls_inspection.go new file mode 100644 index 000000000..e0c78629d --- /dev/null +++ b/providers/aws/networkfirewall/tls_inspection.go @@ -0,0 +1,226 @@ +package networkfirewall + +import ( + "context" + "encoding/json" + + cerrors "github.com/stackshy/cloudemu/v2/errors" + "github.com/stackshy/cloudemu/v2/internal/idgen" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +// tlsPayload is the part of a TLSInspectionConfiguration the emulator reads: the +// server certificate ARNs it reports back as Certificates. The payload itself +// is stored untouched. +type tlsPayload struct { + ServerCertificateConfigurations []struct { + ServerCertificates []struct { + ResourceArn string `json:"ResourceArn"` + } `json:"ServerCertificates"` + } `json:"ServerCertificateConfigurations"` +} + +func (m *Mock) CreateTLSInspectionConfiguration( + _ context.Context, cfg nfdriver.CreateTLSInspectionConfig, +) (*nfdriver.TLSInspectionConfig, error) { + m.mu.Lock() + defer m.mu.Unlock() + + if err := validateName("TLSInspectionConfigurationName", cfg.Name); err != nil { + return nil, err + } + + if err := validateDescription(cfg.Description); err != nil { + return nil, err + } + + if err := validateTags(cfg.Tags); err != nil { + return nil, err + } + + if _, err := tlsCertificates(cfg.Configuration); err != nil { + return nil, err + } + + t := &nfdriver.TLSInspectionConfig{ + Name: cfg.Name, + ARN: m.arn("tls-configuration", cfg.Name), + ID: idgen.GenerateID(""), + Description: cfg.Description, + Configuration: cloneRawJSON(cfg.Configuration), + Status: statusActive, + LastModified: m.now(), + UpdateToken: newToken(), + Tags: copyTags(cfg.Tags), + } + if !m.tlsConfigs.SetIfAbsent(cfg.Name, t) { + return nil, cerrors.Newf(cerrors.AlreadyExists, "TLS inspection configuration %q already exists", cfg.Name) + } + + return m.outTLS(t), nil +} + +func (m *Mock) DescribeTLSInspectionConfiguration(_ context.Context, name, arn string) (*nfdriver.TLSInspectionConfig, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + t, err := m.findTLS(name, arn) + if err != nil { + return nil, err + } + + return m.outTLS(t), nil +} + +func (m *Mock) UpdateTLSInspectionConfiguration( + _ context.Context, name, arn string, cfg nfdriver.UpdateTLSInspectionConfig, +) (*nfdriver.TLSInspectionConfig, error) { + m.mu.Lock() + defer m.mu.Unlock() + + if err := requireToken(cfg.UpdateToken); err != nil { + return nil, err + } + + t, err := m.findTLS(name, arn) + if err != nil { + return nil, err + } + + if err := checkToken(t.UpdateToken, cfg.UpdateToken); err != nil { + return nil, err + } + + if err := validateDescription(cfg.Description); err != nil { + return nil, err + } + + if _, err := tlsCertificates(cfg.Configuration); err != nil { + return nil, err + } + + t.Description = cfg.Description + t.Configuration = cloneRawJSON(cfg.Configuration) + t.LastModified = m.now() + t.UpdateToken = newToken() + + return m.outTLS(t), nil +} + +func (m *Mock) DeleteTLSInspectionConfiguration(_ context.Context, name, arn string) (*nfdriver.TLSInspectionConfig, error) { + m.mu.Lock() + defer m.mu.Unlock() + + t, err := m.findTLS(name, arn) + if err != nil { + return nil, err + } + + if n := m.tlsRefCount(t.ARN); n > 0 { + return nil, nfdriver.InvalidOperation("TLS inspection configuration %q is used by %d firewall policy(ies)", t.Name, n) + } + + out := m.outTLS(t) + out.Status = statusDeleting + + m.tlsConfigs.Delete(t.Name) + + return out, nil +} + +func (m *Mock) ListTLSInspectionConfigurations( + _ context.Context, opts nfdriver.ListOptions, +) ([]nfdriver.TLSInspectionConfig, string, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + items, next, err := paginate(m.tlsConfigs.SortedValues(), opts) + if err != nil { + return nil, "", err + } + + out := make([]nfdriver.TLSInspectionConfig, 0, len(items)) + for _, t := range items { + out = append(out, *m.outTLS(t)) + } + + return out, next, nil +} + +func (m *Mock) findTLS(name, arn string) (*nfdriver.TLSInspectionConfig, error) { + if err := requireIdentifier("TLSInspectionConfiguration", name, arn); err != nil { + return nil, err + } + + if name != "" { + if t, ok := m.tlsConfigs.Get(name); ok { + return t, nil + } + } else if t, ok := m.tlsByARN(arn); ok { + return t, nil + } + + return nil, cerrors.Newf(cerrors.NotFound, "TLS inspection configuration %q not found", nonEmpty(name, arn)) +} + +func (m *Mock) tlsByARN(arn string) (*nfdriver.TLSInspectionConfig, bool) { + for _, t := range m.tlsConfigs.SortedValues() { + if t.ARN == arn { + return t, true + } + } + + return nil, false +} + +// tlsRefCount counts the firewall policies that use the TLS inspection configuration. +func (m *Mock) tlsRefCount(arn string) int { + n := 0 + + for _, p := range m.policies.SortedValues() { + if p.TLSInspectionConfigurationARN == arn { + n++ + } + } + + return n +} + +func (m *Mock) outTLS(t *nfdriver.TLSInspectionConfig) *nfdriver.TLSInspectionConfig { + out := *t + out.Configuration = cloneRawJSON(t.Configuration) + out.Tags = copyTags(t.Tags) + out.NumberOfAssociations = m.tlsRefCount(t.ARN) + out.CertificateARNs, _ = tlsCertificates(t.Configuration) + + return &out +} + +// tlsCertificates validates a TLSInspectionConfiguration payload (at least one +// server certificate configuration) and returns the server certificate ARNs. +func tlsCertificates(raw json.RawMessage) ([]string, error) { + if len(raw) == 0 { + return nil, invalid("TLSInspectionConfiguration is required") + } + + var p tlsPayload + if err := json.Unmarshal(raw, &p); err != nil { + return nil, invalid("TLSInspectionConfiguration is not valid: %v", err) + } + + if len(p.ServerCertificateConfigurations) == 0 { + return nil, invalid("TLSInspectionConfiguration needs at least one ServerCertificateConfiguration") + } + + var arns []string + + for _, c := range p.ServerCertificateConfigurations { + for _, s := range c.ServerCertificates { + if s.ResourceArn != "" { + arns = append(arns, s.ResourceArn) + } + } + } + + return arns, nil +} diff --git a/providers/aws/networkfirewall/token.go b/providers/aws/networkfirewall/token.go new file mode 100644 index 000000000..10ee49ad0 --- /dev/null +++ b/providers/aws/networkfirewall/token.go @@ -0,0 +1,25 @@ +package networkfirewall + +import nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" + +// checkToken compares the update token a caller sent with the resource's +// current one. An empty token is an unconditional update (allowed only where +// AWS marks the token optional; use requireToken where it is required). A stale +// token fails with InvalidTokenException, as in real Network Firewall. +func checkToken(current, supplied string) error { + if supplied != "" && supplied != current { + return nfdriver.InvalidToken("the update token is stale; describe the resource again to get a current token") + } + + return nil +} + +// requireToken fails with a request error when a token AWS marks required is +// missing (UpdateFirewallPolicy, UpdateRuleGroup, UpdateTLSInspectionConfiguration). +func requireToken(supplied string) error { + if supplied == "" { + return invalid("UpdateToken is required") + } + + return nil +} diff --git a/providers/aws/networkfirewall/token_test.go b/providers/aws/networkfirewall/token_test.go new file mode 100644 index 000000000..afd49a156 --- /dev/null +++ b/providers/aws/networkfirewall/token_test.go @@ -0,0 +1,324 @@ +package networkfirewall + +import ( + "sync" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + cerrors "github.com/stackshy/cloudemu/v2/errors" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +const uuidPattern = `^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$` + +func TestToken_MintedAtCreate_UUID_StableAcrossReads(t *testing.T) { + m := newMock() + pol, fw := seedStack(t, m) + rg := seedRuleGroup(t, m, "rg-1", "STATEFUL", 10) + + assert.Regexp(t, uuidPattern, fw.UpdateToken) + assert.Regexp(t, uuidPattern, pol.UpdateToken) + assert.Regexp(t, uuidPattern, rg.UpdateToken) + + for i := 0; i < 3; i++ { + got, err := m.DescribeFirewall(bg, "fw-1", "") + require.NoError(t, err) + assert.Equal(t, fw.UpdateToken, got.UpdateToken) + } + + assert.NotEqual(t, pol.UpdateToken, rg.UpdateToken) +} + +func TestToken_RotatesOnEveryMutation(t *testing.T) { + m := newMock() + pol, fw := seedStack(t, m) + + other := seedPolicy(t, m, "pol-2") + before := fw.UpdateToken + + updated, err := m.UpdateFirewallDeleteProtection(bg, "fw-1", true, "") + require.NoError(t, err) + assert.NotEqual(t, before, updated.UpdateToken) + + again, err := m.UpdateFirewallDeleteProtection(bg, "fw-1", false, updated.UpdateToken) + require.NoError(t, err) + assert.NotEqual(t, updated.UpdateToken, again.UpdateToken) + + // Other resources are untouched by a firewall mutation. + gotPol, _ := m.DescribeFirewallPolicy(bg, "pol-1", "") + assert.Equal(t, pol.UpdateToken, gotPol.UpdateToken) + + gotOther, _ := m.DescribeFirewallPolicy(bg, "pol-2", "") + assert.Equal(t, other.UpdateToken, gotOther.UpdateToken) +} + +func TestToken_StaleRejected_InvalidTokenException(t *testing.T) { + m := newMock() + pol, fw := seedStack(t, m) + + _, err := m.UpdateFirewallDeleteProtection(bg, "fw-1", true, "") + require.NoError(t, err) + + // The token read at create time is now stale. + _, err = m.UpdateFirewallDeleteProtection(bg, "fw-1", false, fw.UpdateToken) + requireException(t, err, nfdriver.ExInvalidToken) + + got, _ := m.DescribeFirewall(bg, "fw-1", "") + assert.True(t, got.DeleteProtection, "a rejected update changes nothing") + + _, err = m.UpdateFirewallPolicy(bg, "pol-1", "", nfdriver.UpdateFirewallPolicyConfig{ + UpdateToken: "00000000-0000-0000-0000-000000000000", StatelessDefaultActions: standardActions, + StatelessFragmentDefaultActions: standardActions, + }) + requireException(t, err, nfdriver.ExInvalidToken) + + gotPol, _ := m.DescribeFirewallPolicy(bg, "pol-1", "") + assert.Equal(t, pol.UpdateToken, gotPol.UpdateToken) +} + +func TestToken_RequiredOnPolicyAndRuleGroupUpdate(t *testing.T) { + m := newMock() + seedPolicy(t, m, "pol-1") + seedRuleGroup(t, m, "rg-1", "STATEFUL", 10) + + _, err := m.UpdateFirewallPolicy(bg, "pol-1", "", nfdriver.UpdateFirewallPolicyConfig{ + StatelessDefaultActions: standardActions, StatelessFragmentDefaultActions: standardActions, + }) + assert.True(t, cerrors.IsInvalidArgument(err), "policy update without token: %v", err) + + _, err = m.UpdateRuleGroup(bg, "rg-1", "", "STATEFUL", nfdriver.UpdateRuleGroupConfig{Description: "d"}) + assert.True(t, cerrors.IsInvalidArgument(err), "rule group update without token: %v", err) +} + +func TestToken_OptionalOnFirewallUpdates(t *testing.T) { + m := newMock() + _, fw := seedStack(t, m) + + _, err := m.UpdateFirewallDeleteProtection(bg, "fw-1", true, "") + require.NoError(t, err, "omitted token = unconditional") + + cur, _ := m.DescribeFirewall(bg, "fw-1", "") + + _, err = m.UpdateFirewallDeleteProtection(bg, "fw-1", false, cur.UpdateToken) + require.NoError(t, err, "matching token succeeds") + + _ = fw +} + +func TestToken_TagOpsDoNotRotate(t *testing.T) { + m := newMock() + _, fw := seedStack(t, m) + + require.NoError(t, m.TagResource(bg, fw.ARN, map[string]string{"a": "b"})) + + got, _ := m.DescribeFirewall(bg, "fw-1", "") + assert.Equal(t, fw.UpdateToken, got.UpdateToken) +} + +func TestToken_Race_50Writers_ExactlyOneWins(t *testing.T) { + m := newMock() + _, fw := seedStack(t, m) + + var ( + wg sync.WaitGroup + wins atomic.Int32 + invalid atomic.Int32 + ) + + for i := 0; i < 50; i++ { + wg.Add(1) + + go func() { + defer wg.Done() + + _, err := m.UpdateFirewallDeleteProtection(bg, "fw-1", true, fw.UpdateToken) + + switch ex, _ := nfdriver.ExceptionOf(err); { + case err == nil: + wins.Add(1) + case ex == nfdriver.ExInvalidToken: + invalid.Add(1) + } + }() + } + + wg.Wait() + + assert.EqualValues(t, 1, wins.Load()) + assert.EqualValues(t, 49, invalid.Load()) +} + +func TestChangeProtection_DefaultsFalse_EchoedOnDescribe(t *testing.T) { + m := newMock() + pol := seedPolicy(t, m, "pol-1") + + plain := seedFirewall(t, m, "fw-plain", pol.ARN) + assert.False(t, plain.SubnetChangeProtection || plain.FirewallPolicyChangeProtection || plain.AvailabilityZoneChangeProtection) + + _, err := m.CreateFirewall(bg, nfdriver.CreateFirewallConfig{ + Name: "fw-prot", PolicyARN: pol.ARN, VPCID: "vpc-1a", SubnetChangeProtection: true, + FirewallPolicyChangeProtection: true, AvailabilityZoneChangeProtection: true, + }) + require.NoError(t, err) + + got, _ := m.DescribeFirewall(bg, "fw-prot", "") + assert.True(t, got.SubnetChangeProtection && got.FirewallPolicyChangeProtection && got.AvailabilityZoneChangeProtection) +} + +func TestChangeProtection_Update_Toggles(t *testing.T) { + m := newMock() + seedStack(t, m) + + fw, err := m.UpdateSubnetChangeProtection(bg, "fw-1", true, "") + require.NoError(t, err) + assert.True(t, fw.SubnetChangeProtection) + assert.False(t, fw.FirewallPolicyChangeProtection) + assert.False(t, fw.AvailabilityZoneChangeProtection) + + fw, err = m.UpdateFirewallPolicyChangeProtection(bg, "fw-1", true, fw.UpdateToken) + require.NoError(t, err) + assert.True(t, fw.SubnetChangeProtection && fw.FirewallPolicyChangeProtection) + + fw, err = m.UpdateAvailabilityZoneChangeProtection(bg, "fw-1", true, "") + require.NoError(t, err) + assert.True(t, fw.AvailabilityZoneChangeProtection) + + fw, err = m.UpdateSubnetChangeProtection(bg, "fw-1", false, "") + require.NoError(t, err) + assert.False(t, fw.SubnetChangeProtection) +} + +func TestChangeProtection_BlocksSubnetAssociateDisassociate(t *testing.T) { + m := newMock() + seedStack(t, m) + + _, err := m.UpdateSubnetChangeProtection(bg, "fw-1", true, "") + require.NoError(t, err) + + _, err = m.AssociateSubnets(bg, "fw-1", []string{"subnet-2"}, "") + requireException(t, err, nfdriver.ExInvalidOperation) + + _, err = m.DisassociateSubnets(bg, "fw-1", []string{"subnet-1"}, "") + requireException(t, err, nfdriver.ExInvalidOperation) + + _, err = m.UpdateSubnetChangeProtection(bg, "fw-1", false, "") + require.NoError(t, err) + + _, err = m.AssociateSubnets(bg, "fw-1", []string{"subnet-2"}, "") + require.NoError(t, err) +} + +func TestChangeProtection_BlocksPolicyAssociate(t *testing.T) { + m := newMock() + seedStack(t, m) + other := seedPolicy(t, m, "pol-2") + + _, err := m.UpdateFirewallPolicyChangeProtection(bg, "fw-1", true, "") + require.NoError(t, err) + + _, err = m.AssociateFirewallPolicy(bg, "fw-1", other.ARN, "") + requireException(t, err, nfdriver.ExInvalidOperation) + + _, err = m.UpdateFirewallPolicyChangeProtection(bg, "fw-1", false, "") + require.NoError(t, err) + + _, err = m.AssociateFirewallPolicy(bg, "fw-1", other.ARN, "") + require.NoError(t, err) +} + +func tgwFirewall(t *testing.T, m *Mock, name string, protect bool) *nfdriver.Firewall { + t.Helper() + + pol := seedPolicy(t, m, name+"-pol") + + fw, err := m.CreateFirewall(bg, nfdriver.CreateFirewallConfig{ + Name: name, PolicyARN: pol.ARN, TransitGatewayID: "tgw-0abc", AvailabilityZones: []string{"us-east-1a"}, + AvailabilityZoneChangeProtection: protect, + }) + require.NoError(t, err) + + return fw +} + +func TestChangeProtection_BlocksAZAssociateDisassociate(t *testing.T) { + m := newMock() + tgwFirewall(t, m, "fw-tgw", true) + + _, err := m.AssociateAvailabilityZones(bg, "fw-tgw", []string{"us-east-1b"}, "") + requireException(t, err, nfdriver.ExInvalidOperation) + + _, err = m.DisassociateAvailabilityZones(bg, "fw-tgw", []string{"us-east-1a"}, "") + requireException(t, err, nfdriver.ExInvalidOperation) + + _, err = m.UpdateAvailabilityZoneChangeProtection(bg, "fw-tgw", false, "") + require.NoError(t, err) + + _, err = m.AssociateAvailabilityZones(bg, "fw-tgw", []string{"us-east-1b"}, "") + require.NoError(t, err) +} + +func TestAvailabilityZones_AssociateDisassociate_TGWFirewall(t *testing.T) { + m := newMock() + fw := tgwFirewall(t, m, "fw-tgw", false) + + got, err := m.AssociateAvailabilityZones(bg, "fw-tgw", []string{"us-east-1b", "us-east-1a"}, "") + require.NoError(t, err) + assert.Equal(t, []string{"us-east-1a", "us-east-1b"}, got.AvailabilityZones, "deduplicated") + assert.NotEqual(t, fw.UpdateToken, got.UpdateToken) + + got, err = m.DisassociateAvailabilityZones(bg, "fw-tgw", []string{"us-east-1a"}, "") + require.NoError(t, err) + assert.Equal(t, []string{"us-east-1b"}, got.AvailabilityZones) + + _, err = m.DisassociateAvailabilityZones(bg, "fw-tgw", []string{"us-east-1z"}, "") + assert.True(t, cerrors.IsInvalidArgument(err), "unknown zone: %v", err) +} + +func TestAvailabilityZones_OnVPCFirewall_Unsupported(t *testing.T) { + m := newMock() + tgw := tgwFirewall(t, m, "fw-tgw", false) + _, vpc := seedStack(t, m) + + _, err := m.AssociateAvailabilityZones(bg, vpc.Name, []string{"us-east-1b"}, "") + requireException(t, err, nfdriver.ExInvalidOperation) + + _, err = m.AssociateSubnets(bg, tgw.Name, []string{"subnet-1"}, "") + requireException(t, err, nfdriver.ExInvalidOperation) +} + +func TestChangeProtection_NotFoundFirewall(t *testing.T) { + m := newMock() + + _, err := m.UpdateSubnetChangeProtection(bg, "ghost", true, "") + assert.True(t, cerrors.IsNotFound(err), "%v", err) +} + +func TestUpdateFirewallDescription_SetAndClear(t *testing.T) { + m := newMock() + _, fw := seedStack(t, m) + + got, err := m.UpdateFirewallDescription(bg, "fw-1", "edge firewall", "") + require.NoError(t, err) + assert.Equal(t, "edge firewall", got.Description) + assert.NotEqual(t, fw.UpdateToken, got.UpdateToken) + + got, err = m.UpdateFirewallDescription(bg, "fw-1", "", got.UpdateToken) + require.NoError(t, err) + assert.Empty(t, got.Description, "an omitted description clears it") +} + +func TestUpdateFirewallDescription_TooLong(t *testing.T) { + m := newMock() + seedStack(t, m) + + long := make([]byte, 513) + for i := range long { + long[i] = 'x' + } + + _, err := m.UpdateFirewallDescription(bg, "fw-1", string(long), "") + assert.True(t, cerrors.IsInvalidArgument(err), "%v", err) +} diff --git a/providers/aws/networkfirewall/validation.go b/providers/aws/networkfirewall/validation.go new file mode 100644 index 000000000..8778d2b62 --- /dev/null +++ b/providers/aws/networkfirewall/validation.go @@ -0,0 +1,115 @@ +package networkfirewall + +import ( + "strings" + + cerrors "github.com/stackshy/cloudemu/v2/errors" +) + +// Limits from the AWS Network Firewall API reference. +const ( + maxNameLen = 128 + maxDescriptionLen = 512 + maxTags = 200 + maxARNLen = 256 + arnPrefix = "arn:aws" + vpcIDPrefix = "vpc-" +) + +func invalid(format string, args ...any) error { + return cerrors.Newf(cerrors.InvalidArgument, format, args...) +} + +// validateName checks a resource name: 1-128 characters of [a-zA-Z0-9-]. +func validateName(what, name string) error { + if name == "" { + return invalid("%s is required", what) + } + + if len(name) > maxNameLen { + return invalid("%s %q exceeds %d characters", what, name, maxNameLen) + } + + for _, r := range name { + if !isNameRune(r) { + return invalid("%s %q must match ^[a-zA-Z0-9-]+$", what, name) + } + } + + return nil +} + +func isNameRune(r rune) bool { + return r == '-' || (r >= '0' && r <= '9') || (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') +} + +func validateDescription(d string) error { + if len(d) > maxDescriptionLen { + return invalid("Description exceeds %d characters", maxDescriptionLen) + } + + return nil +} + +func validateTags(tags map[string]string) error { + if len(tags) > maxTags { + return invalid("at most %d tags are allowed, got %d", maxTags, len(tags)) + } + + return nil +} + +// validateARN rejects an ARN that is empty, too long or not an AWS ARN, before +// any store lookup (a malformed ARN is a request error, not "not found"). +func validateARN(what, arn string) error { + if arn == "" { + return invalid("%s is required", what) + } + + if len(arn) > maxARNLen || !strings.HasPrefix(arn, arnPrefix) { + return invalid("%s %q is not a valid ARN", what, arn) + } + + return nil +} + +// validateVPCID checks a VPC id against ^vpc-[0-9a-f]+$ (max 128 characters). +func validateVPCID(id string) error { + hex, ok := strings.CutPrefix(id, vpcIDPrefix) + if !ok || hex == "" || len(id) > maxNameLen { + return invalid("VpcId %q must match ^vpc-[0-9a-f]+$", id) + } + + for _, r := range hex { + if (r < '0' || r > '9') && (r < 'a' || r > 'f') { + return invalid("VpcId %q must match ^vpc-[0-9a-f]+$", id) + } + } + + return nil +} + +// requireIdentifier checks that a name-or-ARN lookup carries one of them and +// that a supplied ARN is well formed. +func requireIdentifier(what, name, arn string) error { + if name == "" && arn == "" { + return invalid("either %sName or %sArn is required", what, what) + } + + if name == "" { + return validateARN(what+"Arn", arn) + } + + return nil +} + +// oneOf reports whether v is one of allowed (SDK enum values, copied verbatim). +func oneOf(v string, allowed ...string) bool { + for _, a := range allowed { + if v == a { + return true + } + } + + return false +} diff --git a/providers/aws/networkfirewall/validation_test.go b/providers/aws/networkfirewall/validation_test.go new file mode 100644 index 000000000..c1062a03a --- /dev/null +++ b/providers/aws/networkfirewall/validation_test.go @@ -0,0 +1,324 @@ +package networkfirewall + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + cerrors "github.com/stackshy/cloudemu/v2/errors" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +func TestCreateFirewall_Validation(t *testing.T) { + m := newMock() + pol := seedPolicy(t, m, "pol-1") + + base := func() nfdriver.CreateFirewallConfig { + return nfdriver.CreateFirewallConfig{Name: "fw", PolicyARN: pol.ARN, VPCID: "vpc-1a"} + } + + tags := map[string]string{} + for i := 0; i < 201; i++ { + tags[strings.Repeat("k", i+1)] = "v" + } + + cases := map[string]func(*nfdriver.CreateFirewallConfig){ + "no vpc id": func(c *nfdriver.CreateFirewallConfig) { c.VPCID = "" }, + "bad vpc id": func(c *nfdriver.CreateFirewallConfig) { c.VPCID = "vpc-XYZ" }, + "bad name": func(c *nfdriver.CreateFirewallConfig) { c.Name = "fw_1" }, + "long name": func(c *nfdriver.CreateFirewallConfig) { c.Name = strings.Repeat("a", 129) }, + "long description": func(c *nfdriver.CreateFirewallConfig) { c.Description = strings.Repeat("d", 513) }, + "too many tags": func(c *nfdriver.CreateFirewallConfig) { c.Tags = tags }, + "no policy": func(c *nfdriver.CreateFirewallConfig) { c.PolicyARN = "" }, + "unknown policy": func(c *nfdriver.CreateFirewallConfig) { + c.PolicyARN = "arn:aws:network-firewall:us-east-1:000000000000:firewall-policy/x" + }, + "malformed policy": func(c *nfdriver.CreateFirewallConfig) { c.PolicyARN = "not-an-arn" }, + "bad analysis type": func(c *nfdriver.CreateFirewallConfig) { c.EnabledAnalysisTypes = []string{"BOGUS"} }, + "vpc with az": func(c *nfdriver.CreateFirewallConfig) { c.AvailabilityZones = []string{"us-east-1a"} }, + "tgw with vpc": func(c *nfdriver.CreateFirewallConfig) { + c.TransitGatewayID = "tgw-1" + c.AvailabilityZones = []string{"a"} + }, + "tgw without azs": func(c *nfdriver.CreateFirewallConfig) { c.TransitGatewayID = "tgw-1"; c.VPCID = "" }, + } + + for name, mutate := range cases { + t.Run(name, func(t *testing.T) { + cfg := base() + mutate(&cfg) + + _, err := m.CreateFirewall(bg, cfg) + assert.True(t, cerrors.IsInvalidArgument(err), "want InvalidArgument, got %v", err) + }) + } + + _, err := m.CreateFirewall(bg, base()) + require.NoError(t, err) +} + +func TestCreateFirewall_TGWWithoutVPC_OK(t *testing.T) { + m := newMock() + + fw := tgwFirewall(t, m, "fw-tgw", false) + assert.Empty(t, fw.VPCID) + assert.Equal(t, "tgw-0abc", fw.TransitGatewayID) +} + +func TestLogging_Validation(t *testing.T) { + m := newMock() + seedStack(t, m) + + bad := map[string][]nfdriver.LogDestinationConfig{ + "bogus log type": {s3Dest("BOGUS", "b")}, + "bogus dest type": {logDest("FLOW", "Kafka", map[string]string{"x": "y"})}, + "missing bucket": {logDest("FLOW", "S3", map[string]string{"prefix": "p"})}, + "missing log group": {logDest("FLOW", "CloudWatchLogs", map[string]string{})}, + "missing stream": {logDest("FLOW", "KinesisDataFirehose", nil)}, + "unknown key": {logDest("FLOW", "S3", map[string]string{"bucketName": "b", "oops": "1"})}, + "duplicate log type": {s3Dest("FLOW", "a"), s3Dest("FLOW", "b")}, + "more than three": {s3Dest("FLOW", "b"), s3Dest("ALERT", "b"), s3Dest("TLS", "b"), s3Dest("TLS", "c")}, + "prefix on cloudwatch": {logDest("FLOW", "CloudWatchLogs", map[string]string{"logGroup": "g", "prefix": "p"})}, + } + + for name, dests := range bad { + t.Run(name, func(t *testing.T) { + err := m.UpdateLoggingConfiguration(bg, "fw-1", &nfdriver.LoggingConfiguration{Destinations: dests}) + assert.True(t, cerrors.IsInvalidArgument(err), "want InvalidArgument, got %v", err) + }) + } + + logs, err := m.DescribeLoggingConfiguration(bg, "fw-1") + require.NoError(t, err) + assert.Empty(t, logs.Destinations, "rejected updates store nothing") +} + +func TestLogging_OneChangePerCall(t *testing.T) { + m := newMock() + seedStack(t, m) + + two := &nfdriver.LoggingConfiguration{Destinations: []nfdriver.LogDestinationConfig{s3Dest("FLOW", "b"), s3Dest("ALERT", "b")}} + err := m.UpdateLoggingConfiguration(bg, "fw-1", two) + assert.True(t, cerrors.IsInvalidArgument(err), "adding two destinations at once: %v", err) + + one := &nfdriver.LoggingConfiguration{Destinations: []nfdriver.LogDestinationConfig{s3Dest("FLOW", "b")}} + require.NoError(t, m.UpdateLoggingConfiguration(bg, "fw-1", one)) + + // Changing the destination TYPE of an existing entry is a remove plus an add. + typeChange := &nfdriver.LoggingConfiguration{Destinations: []nfdriver.LogDestinationConfig{ + logDest("FLOW", "CloudWatchLogs", map[string]string{"logGroup": "g"}), + }} + err = m.UpdateLoggingConfiguration(bg, "fw-1", typeChange) + assert.True(t, cerrors.IsInvalidArgument(err), "type change: %v", err) + + // Replacing one entry with another log type is also two changes. + swap := &nfdriver.LoggingConfiguration{Destinations: []nfdriver.LogDestinationConfig{s3Dest("ALERT", "b")}} + err = m.UpdateLoggingConfiguration(bg, "fw-1", swap) + assert.True(t, cerrors.IsInvalidArgument(err), "swap: %v", err) +} + +func TestLogging_Add_Remove_ChangeDestination_OmitDisables(t *testing.T) { + m := newMock() + seedStack(t, m) + + update := func(dests ...nfdriver.LogDestinationConfig) error { + return m.UpdateLoggingConfiguration(bg, "fw-1", &nfdriver.LoggingConfiguration{Destinations: dests}) + } + + require.NoError(t, update(s3Dest("FLOW", "b1"))) + require.NoError(t, update(s3Dest("FLOW", "b1"), s3Dest("ALERT", "b1"))) + require.NoError(t, update(s3Dest("FLOW", "b2"), s3Dest("ALERT", "b1")), "change one destination") + require.NoError(t, update(s3Dest("FLOW", "b2")), "remove one") + + logs, _ := m.DescribeLoggingConfiguration(bg, "fw-1") + require.Len(t, logs.Destinations, 1) + assert.Equal(t, "b2", logs.Destinations[0].LogDestination["bucketName"]) + + dash := true + require.NoError(t, m.UpdateLoggingConfiguration(bg, "fw-1", &nfdriver.LoggingConfiguration{ + Destinations: []nfdriver.LogDestinationConfig{s3Dest("FLOW", "b2")}, EnableMonitoringDashboard: &dash, + })) + + logs, _ = m.DescribeLoggingConfiguration(bg, "fw-1") + require.NotNil(t, logs.EnableMonitoringDashboard) + assert.True(t, *logs.EnableMonitoringDashboard) + + // An omitted configuration disables logging (the dashboard flag is kept). + require.NoError(t, m.UpdateLoggingConfiguration(bg, "fw-1", nil)) + + logs, _ = m.DescribeLoggingConfiguration(bg, "fw-1") + assert.Empty(t, logs.Destinations) + + err := m.UpdateLoggingConfiguration(bg, "ghost", nil) + assert.True(t, cerrors.IsNotFound(err)) +} + +func TestCreateRuleGroup_Validation(t *testing.T) { + m := newMock() + + rules := rulesString(`alert tcp any any -> any any (msg:"x"; sid:1;)`) + both := map[string]nfdriver.CreateRuleGroupConfig{ + "capacity 0": {Name: "rg", Type: "STATEFUL", Capacity: 0}, + "capacity negative": {Name: "rg", Type: "STATEFUL", Capacity: -3}, + "bad type": {Name: "rg", Type: "NOPE", Capacity: 5}, + "bad name": {Name: "rg 1", Type: "STATEFUL", Capacity: 5}, + "no name": {Type: "STATEFUL", Capacity: 5}, + "long description": {Name: "rg", Type: "STATEFUL", Capacity: 5, Description: strings.Repeat("d", 513)}, + "bad summary opt": {Name: "rg", Type: "STATEFUL", Capacity: 5, SummaryRuleOptions: []string{"BOGUS"}}, + "malformed rules": {Name: "rg", Type: "STATEFUL", Capacity: 5, Rules: []byte(`{not json`)}, + "over capacity": {Name: "rg", Type: "STATEFUL", Capacity: 1, Rules: rulesString("a", "b")}, + } + + for name, cfg := range both { + t.Run(name, func(t *testing.T) { + _, err := m.CreateRuleGroup(bg, cfg) + assert.True(t, cerrors.IsInvalidArgument(err), "want InvalidArgument, got %v", err) + }) + } + + _, err := m.CreateRuleGroup(bg, nfdriver.CreateRuleGroupConfig{Name: "rg", Type: "STATEFUL", Capacity: 1, Rules: rules}) + require.NoError(t, err) +} + +func TestCreateRuleGroup_StatefulDomainType(t *testing.T) { + m := newMock() + + rg, err := m.CreateRuleGroup(bg, nfdriver.CreateRuleGroupConfig{Name: "domains", Type: "STATEFUL_DOMAIN", Capacity: 5}) + require.NoError(t, err) + assert.Equal(t, "STATEFUL_DOMAIN", rg.Type) +} + +func TestRuleGroup_ConsumedExceedsCapacity(t *testing.T) { + m := newMock() + + rg, err := m.CreateRuleGroup(bg, nfdriver.CreateRuleGroupConfig{ + Name: "rg", Type: "STATEFUL", Capacity: 2, Rules: rulesString("r1", "r2"), + }) + require.NoError(t, err) + assert.Equal(t, 2, rg.ConsumedCapacity) + + _, err = m.UpdateRuleGroup(bg, "rg", "", "STATEFUL", nfdriver.UpdateRuleGroupConfig{ + UpdateToken: rg.UpdateToken, Rules: rulesString("r1", "r2", "r3"), + }) + assert.True(t, cerrors.IsInvalidArgument(err), "update past capacity: %v", err) + + got, _ := m.DescribeRuleGroup(bg, "rg", "", "STATEFUL") + assert.Equal(t, 2, got.Capacity, "capacity is fixed at creation") + assert.Equal(t, rg.UpdateToken, got.UpdateToken, "a rejected update changes nothing") +} + +func TestPolicy_DefaultActionValidation(t *testing.T) { + m := newMock() + + strict := []byte(`{"RuleOrder":"STRICT_ORDER"}`) + custom := []byte(`[{"ActionName":"mine","ActionDefinition":{}}]`) + + cases := map[string]nfdriver.CreateFirewallPolicyConfig{ + "no actions": {Name: "p"}, + "no fragment actions": {Name: "p", StatelessDefaultActions: standardActions}, + "unknown action": {Name: "p", StatelessDefaultActions: []string{"aws:nope"}, StatelessFragmentDefaultActions: standardActions}, + "two standard actions": {Name: "p", StatelessDefaultActions: []string{"aws:pass", "aws:drop"}, StatelessFragmentDefaultActions: standardActions}, + "only a custom action": {Name: "p", StatelessDefaultActions: []string{"mine"}, StatelessFragmentDefaultActions: standardActions, Extra: nfdriver.PolicyExtra{StatelessCustomActions: custom}}, + "undefined custom action": {Name: "p", StatelessDefaultActions: []string{"aws:pass", "ghost"}, StatelessFragmentDefaultActions: standardActions}, + "stateful default no strict": {Name: "p", StatelessDefaultActions: standardActions, StatelessFragmentDefaultActions: standardActions, StatefulDefaultActions: []string{"aws:drop_strict"}}, + "bad stateful default": {Name: "p", StatelessDefaultActions: standardActions, StatelessFragmentDefaultActions: standardActions, StatefulDefaultActions: []string{"aws:what"}, Extra: nfdriver.PolicyExtra{StatefulEngineOptions: strict}}, + "bad rule order": {Name: "p", StatelessDefaultActions: standardActions, StatelessFragmentDefaultActions: standardActions, Extra: nfdriver.PolicyExtra{StatefulEngineOptions: []byte(`{"RuleOrder":"RANDOM"}`)}}, + "tls holding without tls": {Name: "p", StatelessDefaultActions: standardActions, StatelessFragmentDefaultActions: standardActions, Extra: nfdriver.PolicyExtra{EnableTLSSessionHolding: ptr(true)}}, + "bad name": {Name: "p_1", StatelessDefaultActions: standardActions, StatelessFragmentDefaultActions: standardActions}, + } + + for name, cfg := range cases { + t.Run(name, func(t *testing.T) { + _, err := m.CreateFirewallPolicy(bg, cfg) + assert.True(t, cerrors.IsInvalidArgument(err), "want InvalidArgument, got %v", err) + }) + } + + ok := nfdriver.CreateFirewallPolicyConfig{ + Name: "good", StatelessDefaultActions: []string{"aws:pass", "mine"}, StatelessFragmentDefaultActions: standardActions, + StatefulDefaultActions: []string{"aws:drop_strict"}, + Extra: nfdriver.PolicyExtra{StatelessCustomActions: custom, StatefulEngineOptions: strict}, + } + _, err := m.CreateFirewallPolicy(bg, ok) + require.NoError(t, err) +} + +func ptr[T any](v T) *T { return &v } + +func TestPolicy_ReferenceValidation(t *testing.T) { + m := newMock() + stateless := seedRuleGroup(t, m, "rg-sl", "STATELESS", 5) + stateful := seedRuleGroup(t, m, "rg-sf", "STATEFUL", 5) + + policy := func(sl, sf []nfdriver.RuleGroupReference, extra nfdriver.PolicyExtra) nfdriver.CreateFirewallPolicyConfig { + return nfdriver.CreateFirewallPolicyConfig{ + Name: "p", StatelessDefaultActions: standardActions, StatelessFragmentDefaultActions: standardActions, + StatelessRuleGroupReferences: sl, StatefulRuleGroupReferences: sf, Extra: extra, + } + } + ref := func(arn string, prio int) nfdriver.RuleGroupReference { + return nfdriver.RuleGroupReference{ResourceARN: arn, Priority: prio} + } + strict := nfdriver.PolicyExtra{StatefulEngineOptions: []byte(`{"RuleOrder":"STRICT_ORDER"}`)} + ghost := "arn:aws:network-firewall:us-east-1:000000000000:stateless-rulegroup/ghost" + + cases := map[string]nfdriver.CreateFirewallPolicyConfig{ + "stateless without priority": policy([]nfdriver.RuleGroupReference{ref(stateless.ARN, 0)}, nil, nfdriver.PolicyExtra{}), + "duplicate priority": policy([]nfdriver.RuleGroupReference{ref(stateless.ARN, 1), ref(stateless.ARN, 1)}, nil, nfdriver.PolicyExtra{}), + "missing rule group": policy([]nfdriver.RuleGroupReference{ref(ghost, 1)}, nil, nfdriver.PolicyExtra{}), + "stateful in stateless list": policy([]nfdriver.RuleGroupReference{ref(stateful.ARN, 1)}, nil, nfdriver.PolicyExtra{}), + "stateless in stateful list": policy(nil, []nfdriver.RuleGroupReference{ref(stateless.ARN, 1)}, nfdriver.PolicyExtra{}), + "strict stateful no priority": policy(nil, []nfdriver.RuleGroupReference{ref(stateful.ARN, 0)}, strict), + "malformed arn": policy([]nfdriver.RuleGroupReference{ref("nope", 1)}, nil, nfdriver.PolicyExtra{}), + } + + for name, cfg := range cases { + t.Run(name, func(t *testing.T) { + _, err := m.CreateFirewallPolicy(bg, cfg) + assert.True(t, cerrors.IsInvalidArgument(err), "want InvalidArgument, got %v", err) + }) + } + + _, err := m.CreateFirewallPolicy(bg, policy( + []nfdriver.RuleGroupReference{ref(stateless.ARN, 1)}, []nfdriver.RuleGroupReference{ref(stateful.ARN, 0)}, nfdriver.PolicyExtra{})) + require.NoError(t, err, "default-order stateful references need no priority") +} + +func TestPolicy_ExtrasRoundTrip(t *testing.T) { + m := newMock() + + tlsCfg, err := m.CreateTLSInspectionConfiguration(bg, nfdriver.CreateTLSInspectionConfig{ + Name: "tls-1", Configuration: tlsConfigJSON("arn:aws:acm:us-east-1:000000000000:certificate/c1"), + }) + require.NoError(t, err) + + extra := nfdriver.PolicyExtra{ + StatelessCustomActions: []byte(`[{"ActionName":"mine","ActionDefinition":{"PublishMetricAction":{"Dimensions":[{"Value":"v"}]}}}]`), + PolicyVariables: []byte(`{"RuleVariables":{"HOME_NET":{"Definition":["10.0.0.0/8"]}}}`), + StatefulEngineOptions: []byte(`{"RuleOrder":"STRICT_ORDER","StreamExceptionPolicy":"DROP"}`), + EnableTLSSessionHolding: ptr(true), + } + + created, err := m.CreateFirewallPolicy(bg, nfdriver.CreateFirewallPolicyConfig{ + Name: "full", StatelessDefaultActions: []string{"aws:pass", "mine"}, StatelessFragmentDefaultActions: standardActions, + StatefulDefaultActions: []string{"aws:alert_established"}, TLSInspectionConfigurationARN: tlsCfg.ARN, Extra: extra, + }) + require.NoError(t, err) + + got, err := m.DescribeFirewallPolicy(bg, "full", "") + require.NoError(t, err) + assert.JSONEq(t, string(extra.StatelessCustomActions), string(got.Extra.StatelessCustomActions)) + assert.JSONEq(t, string(extra.PolicyVariables), string(got.Extra.PolicyVariables)) + assert.JSONEq(t, string(extra.StatefulEngineOptions), string(got.Extra.StatefulEngineOptions)) + assert.True(t, *got.Extra.EnableTLSSessionHolding) + assert.Equal(t, tlsCfg.ARN, got.TLSInspectionConfigurationARN) + assert.Equal(t, []string{"aws:alert_established"}, got.StatefulDefaultActions) + + // A TLS configuration can be replaced but not removed after create. + _, err = m.UpdateFirewallPolicy(bg, "full", "", nfdriver.UpdateFirewallPolicyConfig{ + UpdateToken: created.UpdateToken, StatelessDefaultActions: standardActions, StatelessFragmentDefaultActions: standardActions, + }) + assert.True(t, cerrors.IsInvalidArgument(err), "removing the TLS configuration: %v", err) +} diff --git a/providers/aws/networkfirewall/vpc_endpoint_association.go b/providers/aws/networkfirewall/vpc_endpoint_association.go new file mode 100644 index 000000000..f7e2582b5 --- /dev/null +++ b/providers/aws/networkfirewall/vpc_endpoint_association.go @@ -0,0 +1,157 @@ +package networkfirewall + +import ( + "context" + + cerrors "github.com/stackshy/cloudemu/v2/errors" + "github.com/stackshy/cloudemu/v2/internal/idgen" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +//nolint:gocritic // cfg matches the driver signature. +func (m *Mock) CreateVpcEndpointAssociation( + _ context.Context, cfg nfdriver.CreateVPCEndpointAssociationConfig, +) (*nfdriver.VPCEndpointAssociation, error) { + m.mu.Lock() + defer m.mu.Unlock() + + if err := validateARN("FirewallArn", cfg.FirewallARN); err != nil { + return nil, err + } + + if err := validateVPCID(cfg.VPCID); err != nil { + return nil, err + } + + if cfg.SubnetID == "" { + return nil, invalid("SubnetMapping.SubnetId is required") + } + + if cfg.IPAddressType != "" && !oneOf(cfg.IPAddressType, ipAddressType...) { + return nil, invalid("SubnetMapping.IPAddressType %q is not valid", cfg.IPAddressType) + } + + if err := validateDescription(cfg.Description); err != nil { + return nil, err + } + + if err := validateTags(cfg.Tags); err != nil { + return nil, err + } + + if _, ok := m.firewallByARN(cfg.FirewallARN); !ok { + return nil, cerrors.Newf(cerrors.NotFound, "firewall %q not found", cfg.FirewallARN) + } + + id := idgen.GenerateID("") + a := &nfdriver.VPCEndpointAssociation{ + ARN: m.arn("vpc-endpoint-association", id), + ID: id, + FirewallARN: cfg.FirewallARN, + VPCID: cfg.VPCID, + SubnetID: cfg.SubnetID, + IPAddressType: cfg.IPAddressType, + AvailabilityZone: nfdriver.ZoneForKey(m.opts.Region, cfg.SubnetID), + Description: cfg.Description, + Status: statusReady, + Tags: copyTags(cfg.Tags), + } + m.associations.Set(a.ARN, a) + + return cloneAssociation(a), nil +} + +func (m *Mock) DescribeVpcEndpointAssociation(_ context.Context, arn string) (*nfdriver.VPCEndpointAssociation, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + a, err := m.findAssociation(arn) + if err != nil { + return nil, err + } + + return cloneAssociation(a), nil +} + +func (m *Mock) DeleteVpcEndpointAssociation(_ context.Context, arn string) (*nfdriver.VPCEndpointAssociation, error) { + m.mu.Lock() + defer m.mu.Unlock() + + a, err := m.findAssociation(arn) + if err != nil { + return nil, err + } + + out := cloneAssociation(a) + out.Status = statusDeleting + + m.associations.Delete(a.ARN) + + return out, nil +} + +func (m *Mock) ListVpcEndpointAssociations( + _ context.Context, firewallARN string, opts nfdriver.ListOptions, +) ([]nfdriver.VPCEndpointAssociation, string, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + if firewallARN != "" { + if err := validateARN("FirewallArn", firewallARN); err != nil { + return nil, "", err + } + } + + var matched []*nfdriver.VPCEndpointAssociation + + for _, a := range m.associations.SortedValues() { + if firewallARN == "" || a.FirewallARN == firewallARN { + matched = append(matched, a) + } + } + + items, next, err := paginate(matched, opts) + if err != nil { + return nil, "", err + } + + out := make([]nfdriver.VPCEndpointAssociation, 0, len(items)) + for _, a := range items { + out = append(out, *cloneAssociation(a)) + } + + return out, next, nil +} + +func (m *Mock) findAssociation(arn string) (*nfdriver.VPCEndpointAssociation, error) { + if err := validateARN("VpcEndpointAssociationArn", arn); err != nil { + return nil, err + } + + a, ok := m.associations.Get(arn) + if !ok { + return nil, cerrors.Newf(cerrors.NotFound, "VPC endpoint association %q not found", arn) + } + + return a, nil +} + +// associationCount counts the VPC endpoint associations of a firewall. +func (m *Mock) associationCount(firewallARN string) int { + n := 0 + + for _, a := range m.associations.SortedValues() { + if a.FirewallARN == firewallARN { + n++ + } + } + + return n +} + +func cloneAssociation(a *nfdriver.VPCEndpointAssociation) *nfdriver.VPCEndpointAssociation { + out := *a + out.Tags = copyTags(a.Tags) + + return &out +} diff --git a/providers/aws/networkfirewall_discovery_test.go b/providers/aws/networkfirewall_discovery_test.go new file mode 100644 index 000000000..8f20441db --- /dev/null +++ b/providers/aws/networkfirewall_discovery_test.go @@ -0,0 +1,67 @@ +package aws + +import ( + "context" + "testing" + + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" + "github.com/stackshy/cloudemu/v2/services/resourcediscovery" +) + +// Every Network Firewall resource family the emulator holds must surface in the +// cross-service inventory with its live tags: firewalls and policies, rule +// groups, TLS inspection configurations and VPC endpoint associations. +func TestResourceDiscoverySurfacesNetworkFirewall(t *testing.T) { + ctx := context.Background() + p := New() + nf := p.NetworkFirewall + + pol, err := nf.CreateFirewallPolicy(ctx, nfdriver.CreateFirewallPolicyConfig{ + Name: "pol", StatelessDefaultActions: []string{"aws:pass"}, StatelessFragmentDefaultActions: []string{"aws:pass"}, + Tags: map[string]string{"env": "prod"}, + }) + if err != nil { + t.Fatalf("CreateFirewallPolicy: %v", err) + } + + fw, err := nf.CreateFirewall(ctx, nfdriver.CreateFirewallConfig{Name: "fw", PolicyARN: pol.ARN, VPCID: "vpc-1a"}) + if err != nil { + t.Fatalf("CreateFirewall: %v", err) + } + + if _, err := nf.CreateRuleGroup(ctx, nfdriver.CreateRuleGroupConfig{Name: "rg", Type: "STATEFUL", Capacity: 5}); err != nil { + t.Fatalf("CreateRuleGroup: %v", err) + } + + if _, err := nf.CreateTLSInspectionConfiguration(ctx, nfdriver.CreateTLSInspectionConfig{ + Name: "tls", Configuration: []byte(`{"ServerCertificateConfigurations":[{}]}`), + }); err != nil { + t.Fatalf("CreateTLSInspectionConfiguration: %v", err) + } + + if _, err := nf.CreateVpcEndpointAssociation(ctx, nfdriver.CreateVPCEndpointAssociationConfig{ + FirewallARN: fw.ARN, VPCID: "vpc-2b", SubnetID: "subnet-1", + }); err != nil { + t.Fatalf("CreateVpcEndpointAssociation: %v", err) + } + + res, err := p.ResourceDiscovery.List(ctx, resourcediscovery.Query{Services: []string{"network-firewall"}}) + if err != nil { + t.Fatalf("discovery List: %v", err) + } + + types := map[string]resourcediscovery.Resource{} + for _, r := range res { + types[r.Type] = r + } + + for _, want := range []string{"firewall", "firewall-policy", "rule-group", "tls-configuration", "vpc-endpoint-association"} { + if _, ok := types[want]; !ok { + t.Errorf("%s missing from discovery output (%d resources)", want, len(res)) + } + } + + if got := types["firewall-policy"].Tags["env"]; got != "prod" { + t.Errorf("firewall policy tags not surfaced: %+v", types["firewall-policy"].Tags) + } +} diff --git a/providers/aws/rgt_discovery.go b/providers/aws/rgt_discovery.go index 2c263bba6..d54b786d6 100644 --- a/providers/aws/rgt_discovery.go +++ b/providers/aws/rgt_discovery.go @@ -141,14 +141,97 @@ func (d taggedDiscovery) discoverKMS(ctx context.Context) ([]resourcediscovery.D } func (d taggedDiscovery) discoverNetworkFirewall(ctx context.Context) ([]resourcediscovery.DiscoveredResource, error) { - firewalls, err := d.p.NetworkFirewall.ListFirewalls(ctx) + nf := d.p.NetworkFirewall + + collectors := []func() ([]resourcediscovery.DiscoveredResource, error){ + func() ([]resourcediscovery.DiscoveredResource, error) { + return pageRows(func(token string) ([]nfdriver.Firewall, string, error) { + return nf.ListFirewalls(ctx, nil, nfdriver.ListOptions{NextToken: token}) + }, func(f *nfdriver.Firewall) resourcediscovery.DiscoveredResource { + return row("network-firewall", "firewall", f.Name, f.ARN, f.Tags) + }) + }, + func() ([]resourcediscovery.DiscoveredResource, error) { + return pageRows(func(token string) ([]nfdriver.FirewallPolicy, string, error) { + return nf.ListFirewallPolicies(ctx, nfdriver.ListOptions{NextToken: token}) + }, func(p *nfdriver.FirewallPolicy) resourcediscovery.DiscoveredResource { + return row("network-firewall", "firewall-policy", p.Name, p.ARN, p.Tags) + }) + }, + func() ([]resourcediscovery.DiscoveredResource, error) { + return pageRows(func(token string) ([]nfdriver.RuleGroup, string, error) { + return nf.ListRuleGroups(ctx, nfdriver.RuleGroupFilter{}, nfdriver.ListOptions{NextToken: token}) + }, func(g *nfdriver.RuleGroup) resourcediscovery.DiscoveredResource { + return row("network-firewall", "rule-group", g.Name, g.ARN, g.Tags) + }) + }, + func() ([]resourcediscovery.DiscoveredResource, error) { + return pageRows(func(token string) ([]nfdriver.TLSInspectionConfig, string, error) { + return nf.ListTLSInspectionConfigurations(ctx, nfdriver.ListOptions{NextToken: token}) + }, func(c *nfdriver.TLSInspectionConfig) resourcediscovery.DiscoveredResource { + return row("network-firewall", "tls-configuration", c.Name, c.ARN, c.Tags) + }) + }, + func() ([]resourcediscovery.DiscoveredResource, error) { + return pageRows(func(token string) ([]nfdriver.VPCEndpointAssociation, string, error) { + return nf.ListVpcEndpointAssociations(ctx, "", nfdriver.ListOptions{NextToken: token}) + }, func(a *nfdriver.VPCEndpointAssociation) resourcediscovery.DiscoveredResource { + return row("network-firewall", "vpc-endpoint-association", a.ID, a.ARN, a.Tags) + }) + }, + } + + var out []resourcediscovery.DiscoveredResource + + for _, collect := range collectors { + rows, err := collect() + if err != nil { + return nil, err + } + + out = append(out, rows...) + } + + return out, nil +} + +// pageRows drains a NextToken-paginated list call and maps every item to a row. +func pageRows[T any]( + list func(token string) ([]T, string, error), toRow func(*T) resourcediscovery.DiscoveredResource, +) ([]resourcediscovery.DiscoveredResource, error) { + items, err := allPages(list) if err != nil { return nil, err } - return project(ctx, firewalls, func(_ context.Context, f nfdriver.Firewall) (resourcediscovery.DiscoveredResource, error) { - return row("network-firewall", "firewall", f.Name, f.ARN, f.Tags), nil - }) + rows := make([]resourcediscovery.DiscoveredResource, 0, len(items)) + for i := range items { + rows = append(rows, toRow(&items[i])) + } + + return rows, nil +} + +// allPages drains a NextToken-paginated list call. +func allPages[T any](list func(token string) ([]T, string, error)) ([]T, error) { + var all []T + + token := "" + + for { + items, next, err := list(token) + if err != nil { + return nil, err + } + + all = append(all, items...) + + if next == "" { + return all, nil + } + + token = next + } } func (d taggedDiscovery) discoverSESv2(ctx context.Context) ([]resourcediscovery.DiscoveredResource, error) { diff --git a/server/aws/networkfirewall/analysis_report.go b/server/aws/networkfirewall/analysis_report.go new file mode 100644 index 000000000..b4e737461 --- /dev/null +++ b/server/aws/networkfirewall/analysis_report.go @@ -0,0 +1,96 @@ +package networkfirewall + +import ( + "net/http" + + "github.com/stackshy/cloudemu/v2/server/wire" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +type startReportRequest struct { + nameArnRequest + AnalysisType string `json:"AnalysisType"` +} + +func (h *Handler) startAnalysisReport(w http.ResponseWriter, r *http.Request) { + var req startReportRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + reports, ok := capability[nfdriver.AnalysisReports](h, w) + if !ok { + return + } + + rep, err := reports.StartAnalysisReport(r.Context(), req.FirewallName, req.FirewallArn, req.AnalysisType) + if err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{"AnalysisReportId": rep.ID}) +} + +type listReportsRequest struct { + nameArnRequest + listRequest +} + +func (h *Handler) listAnalysisReports(w http.ResponseWriter, r *http.Request) { + var req listReportsRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + reports, ok := capability[nfdriver.AnalysisReports](h, w) + if !ok { + return + } + + items, next, err := reports.ListAnalysisReports(r.Context(), req.FirewallName, req.FirewallArn, req.options()) + if err != nil { + writeErr(w, err) + return + } + + out := make([]map[string]any, 0, len(items)) + for i := range items { + out = append(out, map[string]any{ + "AnalysisReportId": items[i].ID, "AnalysisType": items[i].AnalysisType, + "ReportTime": epochSeconds(items[i].ReportTime), "Status": items[i].Status, + }) + } + + wire.WriteJSON(w, withNextToken(map[string]any{"AnalysisReports": out}, next)) +} + +type getReportRequest struct { + nameArnRequest + listRequest + AnalysisReportID string `json:"AnalysisReportId"` +} + +func (h *Handler) getAnalysisReportResults(w http.ResponseWriter, r *http.Request) { + var req getReportRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + reports, ok := capability[nfdriver.AnalysisReports](h, w) + if !ok { + return + } + + rep, err := reports.GetAnalysisReport(r.Context(), req.FirewallName, req.FirewallArn, req.AnalysisReportID) + if err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{ + "AnalysisType": rep.AnalysisType, "Status": rep.Status, "ReportTime": epochSeconds(rep.ReportTime), + "StartTime": epochSeconds(rep.ReportTime), "EndTime": epochSeconds(rep.ReportTime), + "AnalysisReportResults": []map[string]any{}, + }) +} diff --git a/server/aws/networkfirewall/availability_zones.go b/server/aws/networkfirewall/availability_zones.go new file mode 100644 index 000000000..e031fb9ee --- /dev/null +++ b/server/aws/networkfirewall/availability_zones.go @@ -0,0 +1,48 @@ +package networkfirewall + +import ( + "net/http" + + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +type zonesRequest struct { + firewallUpdateRequest + AvailabilityZoneMappings []zoneMapping `json:"AvailabilityZoneMappings"` +} + +func zoneMappingsOf(fw *nfdriver.Firewall) []zoneMapping { + out := make([]zoneMapping, 0, len(fw.AvailabilityZones)) + for _, z := range fw.AvailabilityZones { + out = append(out, zoneMapping{AvailabilityZone: z}) + } + + return out +} + +// zoneChange is the Associate/DisassociateAvailabilityZones driver call. +type zoneChange func(z nfdriver.AvailabilityZones, name string, zones []string, token string) (*nfdriver.Firewall, error) + +func (h *Handler) changeZones(w http.ResponseWriter, r *http.Request, change zoneChange) { + serveFirewallOp[zonesRequest](h, w, r, + func(z nfdriver.AvailabilityZones, name string, req *zonesRequest) (*nfdriver.Firewall, map[string]any, error) { + fw, err := change(z, name, zoneNames(req.AvailabilityZoneMappings), req.UpdateToken) + if err != nil { + return nil, nil, err + } + + return fw, map[string]any{"AvailabilityZoneMappings": zoneMappingsOf(fw)}, nil + }) +} + +func (h *Handler) associateAvailabilityZones(w http.ResponseWriter, r *http.Request) { + h.changeZones(w, r, func(z nfdriver.AvailabilityZones, name string, zones []string, token string) (*nfdriver.Firewall, error) { + return z.AssociateAvailabilityZones(r.Context(), name, zones, token) + }) +} + +func (h *Handler) disassociateAvailabilityZones(w http.ResponseWriter, r *http.Request) { + h.changeZones(w, r, func(z nfdriver.AvailabilityZones, name string, zones []string, token string) (*nfdriver.Firewall, error) { + return z.DisassociateAvailabilityZones(r.Context(), name, zones, token) + }) +} diff --git a/server/aws/networkfirewall/change_protection.go b/server/aws/networkfirewall/change_protection.go new file mode 100644 index 000000000..237edc2e5 --- /dev/null +++ b/server/aws/networkfirewall/change_protection.go @@ -0,0 +1,121 @@ +package networkfirewall + +import ( + "net/http" + + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +// firewallSettingCall is a FirewallSettings operation: it returns the updated +// firewall and the response member that echoes the changed setting (a nil value +// is left out, as AWS omits an absent member). +type firewallSettingCall[R any] func(s nfdriver.FirewallSettings, name string, req *R) (*nfdriver.Firewall, string, any, error) + +// serveFirewallSetting adapts a FirewallSettings operation to serveFirewallOp. +func serveFirewallSetting[R any, P firewallRequest[R]](h *Handler, w http.ResponseWriter, r *http.Request, call firewallSettingCall[R]) { + serveFirewallOp[R, P](h, w, r, func(s nfdriver.FirewallSettings, name string, req *R) (*nfdriver.Firewall, map[string]any, error) { + fw, member, value, err := call(s, name, req) + if err != nil { + return nil, nil, err + } + + extra := map[string]any{} + if value != nil { + extra[member] = value + } + + return fw, extra, nil + }) +} + +// memberDescription is the response member UpdateFirewallDescription echoes. +const memberDescription = "Description" + +type descriptionRequest struct { + firewallUpdateRequest + Description string `json:"Description"` +} + +func (h *Handler) updateFirewallDescription(w http.ResponseWriter, r *http.Request) { + serveFirewallSetting[descriptionRequest](h, w, r, + func(s nfdriver.FirewallSettings, name string, req *descriptionRequest) (*nfdriver.Firewall, string, any, error) { + fw, err := s.UpdateFirewallDescription(r.Context(), name, req.Description, req.UpdateToken) + if err != nil { + return nil, "", nil, err + } + + if fw.Description == "" { + return fw, memberDescription, nil, nil + } + + return fw, memberDescription, fw.Description, nil + }) +} + +type subnetProtectionRequest struct { + firewallUpdateRequest + SubnetChangeProtection bool `json:"SubnetChangeProtection"` +} + +func (h *Handler) updateSubnetChangeProtection(w http.ResponseWriter, r *http.Request) { + serveFirewallSetting[subnetProtectionRequest](h, w, r, + func(s nfdriver.FirewallSettings, name string, req *subnetProtectionRequest) (*nfdriver.Firewall, string, any, error) { + fw, err := s.UpdateSubnetChangeProtection(r.Context(), name, req.SubnetChangeProtection, req.UpdateToken) + if err != nil { + return nil, "", nil, err + } + + return fw, "SubnetChangeProtection", fw.SubnetChangeProtection, nil + }) +} + +type policyProtectionRequest struct { + firewallUpdateRequest + FirewallPolicyChangeProtection bool `json:"FirewallPolicyChangeProtection"` +} + +func (h *Handler) updateFirewallPolicyChangeProtection(w http.ResponseWriter, r *http.Request) { + serveFirewallSetting[policyProtectionRequest](h, w, r, + func(s nfdriver.FirewallSettings, name string, req *policyProtectionRequest) (*nfdriver.Firewall, string, any, error) { + fw, err := s.UpdateFirewallPolicyChangeProtection(r.Context(), name, req.FirewallPolicyChangeProtection, req.UpdateToken) + if err != nil { + return nil, "", nil, err + } + + return fw, "FirewallPolicyChangeProtection", fw.FirewallPolicyChangeProtection, nil + }) +} + +type zoneProtectionRequest struct { + firewallUpdateRequest + AvailabilityZoneChangeProtection bool `json:"AvailabilityZoneChangeProtection"` +} + +func (h *Handler) updateAvailabilityZoneChangeProtection(w http.ResponseWriter, r *http.Request) { + serveFirewallSetting[zoneProtectionRequest](h, w, r, + func(s nfdriver.FirewallSettings, name string, req *zoneProtectionRequest) (*nfdriver.Firewall, string, any, error) { + fw, err := s.UpdateAvailabilityZoneChangeProtection(r.Context(), name, req.AvailabilityZoneChangeProtection, req.UpdateToken) + if err != nil { + return nil, "", nil, err + } + + return fw, "AvailabilityZoneChangeProtection", fw.AvailabilityZoneChangeProtection, nil + }) +} + +type analysisSettingsRequest struct { + firewallUpdateRequest + EnabledAnalysisTypes []string `json:"EnabledAnalysisTypes"` +} + +func (h *Handler) updateFirewallAnalysisSettings(w http.ResponseWriter, r *http.Request) { + serveFirewallSetting[analysisSettingsRequest](h, w, r, + func(s nfdriver.FirewallSettings, name string, req *analysisSettingsRequest) (*nfdriver.Firewall, string, any, error) { + fw, err := s.UpdateFirewallAnalysisSettings(r.Context(), name, req.EnabledAnalysisTypes, req.UpdateToken) + if err != nil { + return nil, "", nil, err + } + + return fw, "EnabledAnalysisTypes", fw.EnabledAnalysisTypes, nil + }) +} diff --git a/server/aws/networkfirewall/depth.go b/server/aws/networkfirewall/depth.go index 2fb072085..6ae06d546 100644 --- a/server/aws/networkfirewall/depth.go +++ b/server/aws/networkfirewall/depth.go @@ -7,197 +7,150 @@ import ( nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" ) -type associatePolicyRequest struct { - FirewallName string `json:"FirewallName"` - FirewallArn string `json:"FirewallArn"` - FirewallPolicyArn string `json:"FirewallPolicyArn"` -} - -func (h *Handler) associateFirewallPolicy(w http.ResponseWriter, r *http.Request) { - var req associatePolicyRequest - if !wire.DecodeJSON(w, r, &req) { - return +// resolveFirewall returns the firewall's name from a name-or-ARN request (the +// driver mutators are keyed by name), writing the error response on failure. +func (h *Handler) resolveFirewall(w http.ResponseWriter, r *http.Request, name, arn string) (string, bool) { + if name != "" { + return name, true } - fw, err := h.db.AssociateFirewallPolicy(r.Context(), firewallName(req.FirewallName, req.FirewallArn), req.FirewallPolicyArn) + fw, err := h.db.DescribeFirewall(r.Context(), "", arn) if err != nil { writeErr(w, err) - return + return "", false } - wire.WriteJSON(w, map[string]any{ - "FirewallArn": fw.ARN, "FirewallName": fw.Name, - "FirewallPolicyArn": fw.PolicyARN, "UpdateToken": updateToken, - }) + return fw.Name, true } -type subnetsRequest struct { - FirewallName string `json:"FirewallName"` - FirewallArn string `json:"FirewallArn"` - SubnetMappings []subnetMapping `json:"SubnetMappings"` - SubnetIDs []string `json:"SubnetIds"` +type firewallUpdateRequest struct { + FirewallName string `json:"FirewallName"` + FirewallArn string `json:"FirewallArn"` + UpdateToken string `json:"UpdateToken"` } -func (h *Handler) associateSubnets(w http.ResponseWriter, r *http.Request) { - var req subnetsRequest - if !wire.DecodeJSON(w, r, &req) { - return - } - - fw, err := h.db.AssociateSubnets(r.Context(), firewallName(req.FirewallName, req.FirewallArn), subnetIDs(req.SubnetMappings)) - if err != nil { - writeErr(w, err) - return - } +// base lets the generic firewall-operation helper reach the shared members of +// any request that embeds firewallUpdateRequest. +func (f *firewallUpdateRequest) base() *firewallUpdateRequest { return f } - writeSubnetsResult(w, fw) +// firewallRequest is a request body that embeds firewallUpdateRequest. +type firewallRequest[R any] interface { + *R + base() *firewallUpdateRequest } -func (h *Handler) disassociateSubnets(w http.ResponseWriter, r *http.Request) { - var req subnetsRequest +// firewallCall performs one firewall mutation on a driver capability C for the +// resolved firewall name and returns the updated firewall plus the response +// members specific to the operation. +type firewallCall[C, R any] func(c C, name string, req *R) (*nfdriver.Firewall, map[string]any, error) + +// serveFirewallOp decodes the request body into R, resolves the driver +// capability C (UnsupportedOperationException when the driver lacks it) and the +// firewall name, runs call and writes the common response members +// (FirewallArn, FirewallName, UpdateToken) plus the operation-specific ones. +func serveFirewallOp[R any, P firewallRequest[R], C any](h *Handler, w http.ResponseWriter, r *http.Request, call firewallCall[C, R]) { + var req R if !wire.DecodeJSON(w, r, &req) { return } - fw, err := h.db.DisassociateSubnets(r.Context(), firewallName(req.FirewallName, req.FirewallArn), req.SubnetIDs) - if err != nil { - writeErr(w, err) + c, ok := capability[C](h, w) + if !ok { return } - writeSubnetsResult(w, fw) -} - -func writeSubnetsResult(w http.ResponseWriter, fw *nfdriver.Firewall) { - mappings := make([]subnetMapping, 0, len(fw.SubnetIDs)) - for _, s := range fw.SubnetIDs { - mappings = append(mappings, subnetMapping{SubnetID: s}) - } + base := P(&req).base() - wire.WriteJSON(w, map[string]any{ - "FirewallArn": fw.ARN, "FirewallName": fw.Name, - "SubnetMappings": mappings, "UpdateToken": updateToken, - }) -} - -type deleteProtectionRequest struct { - FirewallName string `json:"FirewallName"` - FirewallArn string `json:"FirewallArn"` - DeleteProtection bool `json:"DeleteProtection"` -} - -func (h *Handler) updateFirewallDeleteProtection(w http.ResponseWriter, r *http.Request) { - var req deleteProtectionRequest - if !wire.DecodeJSON(w, r, &req) { + name, ok := h.resolveFirewall(w, r, base.FirewallName, base.FirewallArn) + if !ok { return } - fw, err := h.db.UpdateFirewallDeleteProtection(r.Context(), firewallName(req.FirewallName, req.FirewallArn), req.DeleteProtection) + fw, extra, err := call(c, name, &req) if err != nil { writeErr(w, err) return } - wire.WriteJSON(w, map[string]any{ - "FirewallArn": fw.ARN, "FirewallName": fw.Name, - "DeleteProtection": fw.DeleteProtection, "UpdateToken": updateToken, - }) -} + resp := map[string]any{"FirewallArn": fw.ARN, "FirewallName": fw.Name, "UpdateToken": fw.UpdateToken} + for k, v := range extra { + resp[k] = v + } -type logDestinationConfig struct { - LogType string `json:"LogType"` - LogDestinationType string `json:"LogDestinationType,omitempty"` - LogDestination map[string]string `json:"LogDestination,omitempty"` + wire.WriteJSON(w, resp) } -type loggingConfiguration struct { - LogDestinationConfigs []logDestinationConfig `json:"LogDestinationConfigs"` +type associatePolicyRequest struct { + firewallUpdateRequest + FirewallPolicyArn string `json:"FirewallPolicyArn"` } -type loggingRequest struct { - FirewallName string `json:"FirewallName"` - FirewallArn string `json:"FirewallArn"` - LoggingConfiguration loggingConfiguration `json:"LoggingConfiguration"` +func (h *Handler) associateFirewallPolicy(w http.ResponseWriter, r *http.Request) { + serveFirewallOp[associatePolicyRequest](h, w, r, + func(c nfdriver.NetworkFirewall, name string, req *associatePolicyRequest) (*nfdriver.Firewall, map[string]any, error) { + fw, err := c.AssociateFirewallPolicy(r.Context(), name, req.FirewallPolicyArn, req.UpdateToken) + if err != nil { + return nil, nil, err + } + + return fw, map[string]any{"FirewallPolicyArn": fw.PolicyARN}, nil + }) } -func (h *Handler) updateLoggingConfiguration(w http.ResponseWriter, r *http.Request) { - var req loggingRequest - if !wire.DecodeJSON(w, r, &req) { - return - } - - name := firewallName(req.FirewallName, req.FirewallArn) - if err := h.db.UpdateLoggingConfiguration(r.Context(), name, toLogConfigs(req.LoggingConfiguration.LogDestinationConfigs)); err != nil { - writeErr(w, err) - return - } - - fw, err := h.db.DescribeFirewall(r.Context(), name, "") - if err != nil { - writeErr(w, err) - return - } - - wire.WriteJSON(w, map[string]any{ - "FirewallArn": fw.ARN, "FirewallName": name, - "LoggingConfiguration": req.LoggingConfiguration, - }) +type subnetsRequest struct { + firewallUpdateRequest + SubnetMappings []subnetMapping `json:"SubnetMappings"` + SubnetIDs []string `json:"SubnetIds"` } -func (h *Handler) describeLoggingConfiguration(w http.ResponseWriter, r *http.Request) { - var req nameArnRequest - if !wire.DecodeJSON(w, r, &req) { - return - } - - name := firewallName(req.FirewallName, req.FirewallArn) - - configs, err := h.db.DescribeLoggingConfiguration(r.Context(), name) - if err != nil { - writeErr(w, err) - return - } - - fw, err := h.db.DescribeFirewall(r.Context(), name, "") - if err != nil { - writeErr(w, err) - return - } - - wire.WriteJSON(w, map[string]any{ - "FirewallArn": fw.ARN, - "LoggingConfiguration": loggingConfiguration{LogDestinationConfigs: fromLogConfigs(configs)}, - }) +func (h *Handler) associateSubnets(w http.ResponseWriter, r *http.Request) { + serveFirewallOp[subnetsRequest](h, w, r, + func(c nfdriver.NetworkFirewall, name string, req *subnetsRequest) (*nfdriver.Firewall, map[string]any, error) { + fw, err := c.AssociateSubnets(r.Context(), name, subnetIDs(req.SubnetMappings), req.UpdateToken) + if err != nil { + return nil, nil, err + } + + return fw, map[string]any{"SubnetMappings": subnetMappingsOf(fw)}, nil + }) } -func toLogConfigs(cs []logDestinationConfig) []nfdriver.LogDestinationConfig { - if len(cs) == 0 { - return nil - } - - out := make([]nfdriver.LogDestinationConfig, 0, len(cs)) - for _, c := range cs { - out = append(out, nfdriver.LogDestinationConfig{ - LogType: c.LogType, LogDestinationType: c.LogDestinationType, LogDestination: c.LogDestination, +func (h *Handler) disassociateSubnets(w http.ResponseWriter, r *http.Request) { + serveFirewallOp[subnetsRequest](h, w, r, + func(c nfdriver.NetworkFirewall, name string, req *subnetsRequest) (*nfdriver.Firewall, map[string]any, error) { + fw, err := c.DisassociateSubnets(r.Context(), name, req.SubnetIDs, req.UpdateToken) + if err != nil { + return nil, nil, err + } + + return fw, map[string]any{"SubnetMappings": subnetMappingsOf(fw)}, nil }) +} + +func subnetMappingsOf(fw *nfdriver.Firewall) []subnetMapping { + mappings := make([]subnetMapping, 0, len(fw.SubnetIDs)) + for _, s := range fw.SubnetIDs { + mappings = append(mappings, subnetMapping{SubnetID: s}) } - return out + return mappings } -func fromLogConfigs(cs []nfdriver.LogDestinationConfig) []logDestinationConfig { - if len(cs) == 0 { - return nil - } +type deleteProtectionRequest struct { + firewallUpdateRequest + DeleteProtection bool `json:"DeleteProtection"` +} - out := make([]logDestinationConfig, 0, len(cs)) - for _, c := range cs { - out = append(out, logDestinationConfig{ - LogType: c.LogType, LogDestinationType: c.LogDestinationType, LogDestination: c.LogDestination, +func (h *Handler) updateFirewallDeleteProtection(w http.ResponseWriter, r *http.Request) { + serveFirewallOp[deleteProtectionRequest](h, w, r, + func(c nfdriver.NetworkFirewall, name string, req *deleteProtectionRequest) (*nfdriver.Firewall, map[string]any, error) { + fw, err := c.UpdateFirewallDeleteProtection(r.Context(), name, req.DeleteProtection, req.UpdateToken) + if err != nil { + return nil, nil, err + } + + return fw, map[string]any{"DeleteProtection": fw.DeleteProtection}, nil }) - } - - return out } type tagResourceRequest struct { @@ -256,20 +209,3 @@ func (h *Handler) listTagsForResource(w http.ResponseWriter, r *http.Request) { wire.WriteJSON(w, map[string]any{"Tags": mapToTags(tags)}) } - -// firewallName resolves the firewall's store key (its name) from either the -// name or the ARN provided by the caller. Firewalls are keyed by name. -func firewallName(name, arn string) string { - if name != "" { - return name - } - - // ARN tail after "firewall/" is the name. - for i := len(arn) - 1; i >= 0; i-- { - if arn[i] == '/' { - return arn[i+1:] - } - } - - return arn -} diff --git a/server/aws/networkfirewall/dispatch_test.go b/server/aws/networkfirewall/dispatch_test.go new file mode 100644 index 000000000..ea8984409 --- /dev/null +++ b/server/aws/networkfirewall/dispatch_test.go @@ -0,0 +1,210 @@ +package networkfirewall + +import ( + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stackshy/cloudemu/v2/config" + cerrors "github.com/stackshy/cloudemu/v2/errors" + nfmock "github.com/stackshy/cloudemu/v2/providers/aws/networkfirewall" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +// supportedOps is every Network Firewall operation the emulator implements +// (issue #1455 scope); the proxy, container-association, transit-gateway +// attachment and encryption families are documented non-goals. +// +//nolint:gochecknoglobals // immutable test fixture. +var supportedOps = []string{ + "CreateFirewall", "DescribeFirewall", "DeleteFirewall", "ListFirewalls", + "CreateFirewallPolicy", "DescribeFirewallPolicy", "UpdateFirewallPolicy", "DeleteFirewallPolicy", "ListFirewallPolicies", + "CreateRuleGroup", "DescribeRuleGroup", "UpdateRuleGroup", "DeleteRuleGroup", "ListRuleGroups", + "AssociateFirewallPolicy", "AssociateSubnets", "DisassociateSubnets", "UpdateFirewallDeleteProtection", + "UpdateLoggingConfiguration", "DescribeLoggingConfiguration", "TagResource", "UntagResource", "ListTagsForResource", + "UpdateFirewallDescription", "UpdateSubnetChangeProtection", "UpdateFirewallPolicyChangeProtection", + "UpdateAvailabilityZoneChangeProtection", "UpdateFirewallAnalysisSettings", + "AssociateAvailabilityZones", "DisassociateAvailabilityZones", + "PutResourcePolicy", "DescribeResourcePolicy", "DeleteResourcePolicy", + "CreateTLSInspectionConfiguration", "DescribeTLSInspectionConfiguration", "UpdateTLSInspectionConfiguration", + "DeleteTLSInspectionConfiguration", "ListTLSInspectionConfigurations", + "CreateVpcEndpointAssociation", "DescribeVpcEndpointAssociation", "DeleteVpcEndpointAssociation", "ListVpcEndpointAssociations", + "DescribeFirewallMetadata", "DescribeRuleGroupMetadata", "DescribeRuleGroupSummary", + "StartFlowCapture", "StartFlowFlush", "DescribeFlowOperation", "ListFlowOperations", "ListFlowOperationResults", + "StartAnalysisReport", "ListAnalysisReports", "GetAnalysisReportResults", +} + +func newHandler() *Handler { return New(nfmock.New(config.NewOptions())) } + +func call(h http.Handler, target, body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body)) + if target != "" { + req.Header.Set("X-Amz-Target", target) + } + + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + + return rec +} + +func TestMatches_TargetPrefix_And_RoutesTable(t *testing.T) { + h := newHandler() + + for _, tc := range []struct { + target string + want bool + }{ + {"NetworkFirewall_20201112.CreateFirewall", true}, + {"NetworkFirewall_20201112.", true}, + {"NetworkFirewall_2020.CreateFirewall", false}, + {"AWSKinesisService.ListStreams", false}, + {"", false}, + } { + req := httptest.NewRequest(http.MethodPost, "/", nil) + if tc.target != "" { + req.Header.Set("X-Amz-Target", tc.target) + } + + assert.Equal(t, tc.want, h.Matches(req), tc.target) + } + + // A plain S3-style request is never claimed (the handler cannot shadow S3). + assert.False(t, h.Matches(httptest.NewRequest(http.MethodGet, "/bucket/key", nil))) + + assert.Len(t, h.routes, len(supportedOps), "route table and supported-operation list agree") + + for _, op := range supportedOps { + assert.Contains(t, h.routes, op) + } + + rec := call(h, targetPrefix+"CreateProxy", "{}") + assert.Equal(t, http.StatusBadRequest, rec.Code) + assert.Contains(t, rec.Body.String(), "InvalidRequestException") + assert.Contains(t, rec.Body.String(), "unknown operation") + + assert.Equal(t, "network-firewall", h.IAMService()) +} + +func TestWriteErr_Mapping(t *testing.T) { + typed := nfdriver.InvalidToken("stale") + wrapped := errors.Join(errors.New("context"), typed) //nolint:err113 // test fixture + + for name, tc := range map[string]struct { + err error + status int + kind string + }{ + "typed": {typed, http.StatusBadRequest, "InvalidTokenException"}, + "typed through a wrap": {wrapped, http.StatusBadRequest, "InvalidTokenException"}, + "invalid operation": {nfdriver.InvalidOperation("x"), http.StatusBadRequest, "InvalidOperationException"}, + "resource policy": {nfdriver.InvalidResourcePolicy("x"), http.StatusBadRequest, "InvalidResourcePolicyException"}, + "not found": {cerrors.New(cerrors.NotFound, "x"), http.StatusBadRequest, "ResourceNotFoundException"}, + "already exists": {cerrors.New(cerrors.AlreadyExists, "x"), http.StatusBadRequest, "InvalidRequestException"}, + "invalid argument": {cerrors.New(cerrors.InvalidArgument, "x"), http.StatusBadRequest, "InvalidRequestException"}, + "failed precondition": {cerrors.New(cerrors.FailedPrecondition, "x"), http.StatusBadRequest, "InvalidOperationException"}, + "unexpected": {errors.New("boom"), http.StatusInternalServerError, "InternalServerError"}, //nolint:err113 // test fixture + } { + t.Run(name, func(t *testing.T) { + rec := httptest.NewRecorder() + writeErr(rec, tc.err) + + assert.Equal(t, tc.status, rec.Code) + assert.Contains(t, rec.Body.String(), tc.kind) + }) + } +} + +// baseOnly hides every optional capability of the wrapped driver: embedding the +// interface promotes only the base NetworkFirewall methods. +type baseOnly struct{ nfdriver.NetworkFirewall } + +func TestOptionalCapabilities_UnsupportedWhenAbsent(t *testing.T) { + h := New(baseOnly{nfmock.New(config.NewOptions())}) + + for _, op := range []string{ + "UpdateFirewallDescription", "UpdateSubnetChangeProtection", "AssociateAvailabilityZones", "PutResourcePolicy", + "CreateTLSInspectionConfiguration", "CreateVpcEndpointAssociation", "DescribeFirewallMetadata", "StartFlowCapture", "StartAnalysisReport", + } { + rec := call(h, targetPrefix+op, "{}") + + assert.Equal(t, http.StatusBadRequest, rec.Code, op) + assert.Contains(t, rec.Body.String(), "UnsupportedOperationException", op) + } + + // The base operations still work. + rec := call(h, targetPrefix+"ListFirewalls", "{}") + assert.Equal(t, http.StatusOK, rec.Code) +} + +func TestDecodeErrors_AreRequestErrors(t *testing.T) { + h := newHandler() + + rec := call(h, targetPrefix+"CreateFirewall", "{not json") + require.Equal(t, http.StatusBadRequest, rec.Code) +} + +func TestDuplicateCreate_IsInvalidRequest(t *testing.T) { + h := newHandler() + body := `{"FirewallPolicyName":"p","FirewallPolicy":{"StatelessDefaultActions":["aws:pass"],"StatelessFragmentDefaultActions":["aws:pass"]}}` + + require.Equal(t, http.StatusOK, call(h, targetPrefix+"CreateFirewallPolicy", body).Code) + + rec := call(h, targetPrefix+"CreateFirewallPolicy", body) + assert.Equal(t, http.StatusBadRequest, rec.Code) + assert.Contains(t, rec.Body.String(), "InvalidRequestException") +} + +func TestRuleGroupBody_Resolution(t *testing.T) { + for name, tc := range map[string]struct { + group string + rules string + wantErr bool + wantNil bool + }{ + "both": {`{"RulesSource":{}}`, "pass any", true, true}, + "neither": {"", "", false, true}, + "null": {"null", "", false, true}, + "group": {`{"RulesSource":{}}`, "", false, false}, + "rules": {"", "pass any", false, false}, + } { + t.Run(name, func(t *testing.T) { + got, err := ruleGroupBody([]byte(tc.group), tc.rules) + + assert.Equal(t, tc.wantErr, err != nil) + assert.Equal(t, tc.wantNil, got == nil) + }) + } +} + +// TestEveryOp_BadInput_IsRequestError sends every operation an empty body (no +// identifiers) and a malformed body: neither may succeed, panic or answer 5xx. +func TestEveryOp_BadInput_IsRequestError(t *testing.T) { + h := newHandler() + + // Operations with no required identifier answer an empty body successfully. + listOps := map[string]bool{ + "ListFirewalls": true, "ListFirewallPolicies": true, "ListRuleGroups": true, + "ListTLSInspectionConfigurations": true, "ListVpcEndpointAssociations": true, + } + + for _, op := range supportedOps { + t.Run(op, func(t *testing.T) { + rec := call(h, targetPrefix+op, "{}") + + if listOps[op] { + assert.Equal(t, http.StatusOK, rec.Code) + } else { + assert.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String()) + } + + bad := call(h, targetPrefix+op, "{not json") + assert.Equal(t, http.StatusBadRequest, bad.Code) + }) + } +} diff --git a/server/aws/networkfirewall/errors.go b/server/aws/networkfirewall/errors.go new file mode 100644 index 000000000..3c49558cc --- /dev/null +++ b/server/aws/networkfirewall/errors.go @@ -0,0 +1,45 @@ +package networkfirewall + +import ( + "net/http" + + cerrors "github.com/stackshy/cloudemu/v2/errors" + "github.com/stackshy/cloudemu/v2/server/wire" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +// writeErr renders err as the Network Firewall exception it represents: a typed +// driver error carries its exact exception name; everything else maps by code. +func writeErr(w http.ResponseWriter, err error) { + msg := cerrors.Message(err) + + if ex, ok := nfdriver.ExceptionOf(err); ok { + wire.WriteJSONError(w, http.StatusBadRequest, ex, msg) + return + } + + switch { + case cerrors.IsNotFound(err): + wire.WriteJSONError(w, http.StatusBadRequest, "ResourceNotFoundException", msg) + case cerrors.IsFailedPrecondition(err): + wire.WriteJSONError(w, http.StatusBadRequest, nfdriver.ExInvalidOperation, msg) + case cerrors.IsAlreadyExists(err), cerrors.IsInvalidArgument(err): + // A duplicate name is a request error: InvalidRequestException is the one + // exception every Create operation models. + wire.WriteJSONError(w, http.StatusBadRequest, "InvalidRequestException", msg) + default: + wire.WriteJSONError(w, http.StatusInternalServerError, "InternalServerError", msg) + } +} + +// capability returns the optional operation family T the driver implements, or +// writes UnsupportedOperationException and returns false. +func capability[T any](h *Handler, w http.ResponseWriter) (T, bool) { + c, ok := h.db.(T) + if !ok { + wire.WriteJSONError(w, http.StatusBadRequest, nfdriver.ExUnsupportedOperation, + "the operation is not supported by this Network Firewall implementation") + } + + return c, ok +} diff --git a/server/aws/networkfirewall/flow_operation.go b/server/aws/networkfirewall/flow_operation.go new file mode 100644 index 000000000..422cd74e7 --- /dev/null +++ b/server/aws/networkfirewall/flow_operation.go @@ -0,0 +1,194 @@ +package networkfirewall + +import ( + "encoding/json" + "net/http" + + "github.com/stackshy/cloudemu/v2/server/wire" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +type flowScopeRequest struct { + FirewallArn string `json:"FirewallArn"` + AvailabilityZone string `json:"AvailabilityZone"` + VpcEndpointID string `json:"VpcEndpointId"` + VpcEndpointAssociationArn string `json:"VpcEndpointAssociationArn"` +} + +func (s *flowScopeRequest) scope() nfdriver.FlowOperationScope { + return nfdriver.FlowOperationScope{ + FirewallARN: s.FirewallArn, AvailabilityZone: s.AvailabilityZone, + VPCEndpointID: s.VpcEndpointID, VPCEndpointAssociationARN: s.VpcEndpointAssociationArn, + } +} + +type startFlowRequest struct { + flowScopeRequest + FlowFilters json.RawMessage `json:"FlowFilters"` + MinimumFlowAgeInSeconds *int32 `json:"MinimumFlowAgeInSeconds"` +} + +func (s *startFlowRequest) request() nfdriver.FlowOperationRequest { + return nfdriver.FlowOperationRequest{ + FirewallARN: s.FirewallArn, AvailabilityZone: s.AvailabilityZone, VPCEndpointID: s.VpcEndpointID, + VPCEndpointAssociationARN: s.VpcEndpointAssociationArn, + MinimumFlowAgeSeconds: s.MinimumFlowAgeInSeconds, Filters: s.FlowFilters, + } +} + +func (h *Handler) startFlowCapture(w http.ResponseWriter, r *http.Request) { + h.startFlow(w, r, func(f nfdriver.FlowOperations, req nfdriver.FlowOperationRequest) (*nfdriver.FlowOperation, error) { + return f.StartFlowCapture(r.Context(), req) + }) +} + +func (h *Handler) startFlowFlush(w http.ResponseWriter, r *http.Request) { + h.startFlow(w, r, func(f nfdriver.FlowOperations, req nfdriver.FlowOperationRequest) (*nfdriver.FlowOperation, error) { + return f.StartFlowFlush(r.Context(), req) + }) +} + +func (h *Handler) startFlow( + w http.ResponseWriter, r *http.Request, + start func(nfdriver.FlowOperations, nfdriver.FlowOperationRequest) (*nfdriver.FlowOperation, error), +) { + var req startFlowRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + flows, ok := capability[nfdriver.FlowOperations](h, w) + if !ok { + return + } + + op, err := start(flows, req.request()) + if err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{ + "FirewallArn": op.FirewallARN, "FlowOperationId": op.ID, "FlowOperationStatus": op.Status, + }) +} + +type describeFlowRequest struct { + flowScopeRequest + FlowOperationID string `json:"FlowOperationId"` +} + +func (h *Handler) describeFlowOperation(w http.ResponseWriter, r *http.Request) { + var req describeFlowRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + flows, ok := capability[nfdriver.FlowOperations](h, w) + if !ok { + return + } + + op, err := flows.DescribeFlowOperation(r.Context(), req.scope(), req.FlowOperationID) + if err != nil { + writeErr(w, err) + return + } + + resp := flowOperationFields(op) + resp["FlowOperation"] = map[string]any{ + "FlowFilters": op.Filters, "MinimumFlowAgeInSeconds": op.MinimumFlowAgeSeconds, + } + resp["FlowOperationType"] = op.Type + + wire.WriteJSON(w, resp) +} + +// flowOperationFields are the response members DescribeFlowOperation and +// ListFlowOperationResults share. +func flowOperationFields(op *nfdriver.FlowOperation) map[string]any { + resp := map[string]any{ + "FirewallArn": op.FirewallARN, "FlowOperationId": op.ID, "FlowOperationStatus": op.Status, + "FlowRequestTimestamp": epochSeconds(op.RequestedAt), + } + if op.AvailabilityZone != "" { + resp["AvailabilityZone"] = op.AvailabilityZone + } + + if op.VPCEndpointID != "" { + resp["VpcEndpointId"] = op.VPCEndpointID + } + + if op.VPCEndpointAssociationARN != "" { + resp["VpcEndpointAssociationArn"] = op.VPCEndpointAssociationARN + } + + if op.StatusMessage != "" { + resp["StatusMessage"] = op.StatusMessage + } + + return resp +} + +type listFlowOperationsRequest struct { + flowScopeRequest + listRequest + FlowOperationType string `json:"FlowOperationType"` +} + +func (h *Handler) listFlowOperations(w http.ResponseWriter, r *http.Request) { + var req listFlowOperationsRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + flows, ok := capability[nfdriver.FlowOperations](h, w) + if !ok { + return + } + + items, next, err := flows.ListFlowOperations(r.Context(), req.scope(), req.FlowOperationType, req.options()) + if err != nil { + writeErr(w, err) + return + } + + metas := make([]map[string]any, 0, len(items)) + for i := range items { + metas = append(metas, map[string]any{ + "FlowOperationId": items[i].ID, "FlowOperationType": items[i].Type, + "FlowOperationStatus": items[i].Status, "FlowRequestTimestamp": epochSeconds(items[i].RequestedAt), + }) + } + + wire.WriteJSON(w, withNextToken(map[string]any{"FlowOperations": metas}, next)) +} + +type listFlowResultsRequest struct { + flowScopeRequest + listRequest + FlowOperationID string `json:"FlowOperationId"` +} + +func (h *Handler) listFlowOperationResults(w http.ResponseWriter, r *http.Request) { + var req listFlowResultsRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + flows, ok := capability[nfdriver.FlowOperations](h, w) + if !ok { + return + } + + op, next, err := flows.ListFlowOperationResults(r.Context(), req.scope(), req.FlowOperationID, req.options()) + if err != nil { + writeErr(w, err) + return + } + + resp := flowOperationFields(op) + resp["Flows"] = []map[string]any{} + + wire.WriteJSON(w, withNextToken(resp, next)) +} diff --git a/server/aws/networkfirewall/handler.go b/server/aws/networkfirewall/handler.go index 555c996f0..f580dec5c 100644 --- a/server/aws/networkfirewall/handler.go +++ b/server/aws/networkfirewall/handler.go @@ -8,7 +8,6 @@ import ( "net/http" "strings" - cerrors "github.com/stackshy/cloudemu/v2/errors" "github.com/stackshy/cloudemu/v2/server/wire" nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" ) @@ -16,13 +15,20 @@ import ( const targetPrefix = "NetworkFirewall_20201112." // Handler serves Network Firewall requests against a networkfirewall driver. +// Operation families beyond the base driver interface are optional capability +// interfaces; an operation whose family the driver lacks answers +// UnsupportedOperationException. type Handler struct { - db nfdriver.NetworkFirewall + db nfdriver.NetworkFirewall + routes map[string]http.HandlerFunc } // New returns a Network Firewall handler backed by db. func New(db nfdriver.NetworkFirewall) *Handler { - return &Handler{db: db} + h := &Handler{db: db} + h.routes = h.buildRoutes() + + return h } // Matches claims requests whose X-Amz-Target names a Network Firewall operation. @@ -31,77 +37,74 @@ func (*Handler) Matches(r *http.Request) bool { } // ServeHTTP dispatches on the operation named in X-Amz-Target. -// -//nolint:gocyclo // a flat operation switch is the clearest dispatch shape. func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { op := strings.TrimPrefix(r.Header.Get("X-Amz-Target"), targetPrefix) - switch op { - case "CreateFirewall": - h.createFirewall(w, r) - case "DescribeFirewall": - h.describeFirewall(w, r) - case "DeleteFirewall": - h.deleteFirewall(w, r) - case "ListFirewalls": - h.listFirewalls(w, r) - case "CreateFirewallPolicy": - h.createFirewallPolicy(w, r) - case "DescribeFirewallPolicy": - h.describeFirewallPolicy(w, r) - case "UpdateFirewallPolicy": - h.updateFirewallPolicy(w, r) - case "DeleteFirewallPolicy": - h.deleteFirewallPolicy(w, r) - case "ListFirewallPolicies": - h.listFirewallPolicies(w, r) - case "CreateRuleGroup": - h.createRuleGroup(w, r) - case "DescribeRuleGroup": - h.describeRuleGroup(w, r) - case "UpdateRuleGroup": - h.updateRuleGroup(w, r) - case "DeleteRuleGroup": - h.deleteRuleGroup(w, r) - case "ListRuleGroups": - h.listRuleGroups(w, r) - case "AssociateFirewallPolicy": - h.associateFirewallPolicy(w, r) - case "AssociateSubnets": - h.associateSubnets(w, r) - case "DisassociateSubnets": - h.disassociateSubnets(w, r) - case "UpdateFirewallDeleteProtection": - h.updateFirewallDeleteProtection(w, r) - case "UpdateLoggingConfiguration": - h.updateLoggingConfiguration(w, r) - case "DescribeLoggingConfiguration": - h.describeLoggingConfiguration(w, r) - case "TagResource": - h.tagResource(w, r) - case "UntagResource": - h.untagResource(w, r) - case "ListTagsForResource": - h.listTagsForResource(w, r) - default: + route, ok := h.routes[op] + if !ok { wire.WriteJSONError(w, http.StatusBadRequest, "InvalidRequestException", "unknown operation: "+op) + return } -} -const updateToken = "00000000-0000-0000-0000-000000000000" - -func writeErr(w http.ResponseWriter, err error) { - msg := cerrors.Message(err) + route(w, r) +} - switch { - case cerrors.IsNotFound(err): - wire.WriteJSONError(w, http.StatusBadRequest, "ResourceNotFoundException", msg) - case cerrors.IsAlreadyExists(err): - wire.WriteJSONError(w, http.StatusBadRequest, "InvalidOperationException", msg) - case cerrors.IsInvalidArgument(err), cerrors.IsFailedPrecondition(err): - wire.WriteJSONError(w, http.StatusBadRequest, "InvalidRequestException", msg) - default: - wire.WriteJSONError(w, http.StatusInternalServerError, "InternalServerError", msg) +// buildRoutes is the operation table: one entry per supported operation. +func (h *Handler) buildRoutes() map[string]http.HandlerFunc { + return map[string]http.HandlerFunc{ + "CreateFirewall": h.createFirewall, + "DescribeFirewall": h.describeFirewall, + "DeleteFirewall": h.deleteFirewall, + "ListFirewalls": h.listFirewalls, + "CreateFirewallPolicy": h.createFirewallPolicy, + "DescribeFirewallPolicy": h.describeFirewallPolicy, + "UpdateFirewallPolicy": h.updateFirewallPolicy, + "DeleteFirewallPolicy": h.deleteFirewallPolicy, + "ListFirewallPolicies": h.listFirewallPolicies, + "CreateRuleGroup": h.createRuleGroup, + "DescribeRuleGroup": h.describeRuleGroup, + "UpdateRuleGroup": h.updateRuleGroup, + "DeleteRuleGroup": h.deleteRuleGroup, + "ListRuleGroups": h.listRuleGroups, + "AssociateFirewallPolicy": h.associateFirewallPolicy, + "AssociateSubnets": h.associateSubnets, + "DisassociateSubnets": h.disassociateSubnets, + "UpdateFirewallDeleteProtection": h.updateFirewallDeleteProtection, + "UpdateLoggingConfiguration": h.updateLoggingConfiguration, + "DescribeLoggingConfiguration": h.describeLoggingConfiguration, + "TagResource": h.tagResource, + "UntagResource": h.untagResource, + "ListTagsForResource": h.listTagsForResource, + "UpdateFirewallDescription": h.updateFirewallDescription, + "UpdateSubnetChangeProtection": h.updateSubnetChangeProtection, + "UpdateFirewallPolicyChangeProtection": h.updateFirewallPolicyChangeProtection, + "UpdateAvailabilityZoneChangeProtection": h.updateAvailabilityZoneChangeProtection, + "UpdateFirewallAnalysisSettings": h.updateFirewallAnalysisSettings, + "AssociateAvailabilityZones": h.associateAvailabilityZones, + "DisassociateAvailabilityZones": h.disassociateAvailabilityZones, + "PutResourcePolicy": h.putResourcePolicy, + "DescribeResourcePolicy": h.describeResourcePolicy, + "DeleteResourcePolicy": h.deleteResourcePolicy, + "CreateTLSInspectionConfiguration": h.createTLSInspectionConfiguration, + "DescribeTLSInspectionConfiguration": h.describeTLSInspectionConfiguration, + "UpdateTLSInspectionConfiguration": h.updateTLSInspectionConfiguration, + "DeleteTLSInspectionConfiguration": h.deleteTLSInspectionConfiguration, + "ListTLSInspectionConfigurations": h.listTLSInspectionConfigurations, + "CreateVpcEndpointAssociation": h.createVpcEndpointAssociation, + "DescribeVpcEndpointAssociation": h.describeVpcEndpointAssociation, + "DeleteVpcEndpointAssociation": h.deleteVpcEndpointAssociation, + "ListVpcEndpointAssociations": h.listVpcEndpointAssociations, + "DescribeFirewallMetadata": h.describeFirewallMetadata, + "DescribeRuleGroupMetadata": h.describeRuleGroupMetadata, + "DescribeRuleGroupSummary": h.describeRuleGroupSummary, + "StartFlowCapture": h.startFlowCapture, + "StartFlowFlush": h.startFlowFlush, + "DescribeFlowOperation": h.describeFlowOperation, + "ListFlowOperations": h.listFlowOperations, + "ListFlowOperationResults": h.listFlowOperationResults, + "StartAnalysisReport": h.startAnalysisReport, + "ListAnalysisReports": h.listAnalysisReports, + "GetAnalysisReportResults": h.getAnalysisReportResults, } } diff --git a/server/aws/networkfirewall/logging.go b/server/aws/networkfirewall/logging.go new file mode 100644 index 000000000..2bec7cdb6 --- /dev/null +++ b/server/aws/networkfirewall/logging.go @@ -0,0 +1,120 @@ +package networkfirewall + +import ( + "net/http" + + "github.com/stackshy/cloudemu/v2/server/wire" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +type logDestinationConfig struct { + LogType string `json:"LogType"` + LogDestinationType string `json:"LogDestinationType,omitempty"` + LogDestination map[string]string `json:"LogDestination,omitempty"` +} + +type loggingConfiguration struct { + LogDestinationConfigs []logDestinationConfig `json:"LogDestinationConfigs"` +} + +type loggingRequest struct { + FirewallName string `json:"FirewallName"` + FirewallArn string `json:"FirewallArn"` + LoggingConfiguration *loggingConfiguration `json:"LoggingConfiguration"` + EnableMonitoringDashboard *bool `json:"EnableMonitoringDashboard"` +} + +func (h *Handler) updateLoggingConfiguration(w http.ResponseWriter, r *http.Request) { + var req loggingRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + name, ok := h.resolveFirewall(w, r, req.FirewallName, req.FirewallArn) + if !ok { + return + } + + cfg := &nfdriver.LoggingConfiguration{EnableMonitoringDashboard: req.EnableMonitoringDashboard} + if req.LoggingConfiguration != nil { + cfg.Destinations = toLogConfigs(req.LoggingConfiguration.LogDestinationConfigs) + } + + if err := h.db.UpdateLoggingConfiguration(r.Context(), name, cfg); err != nil { + writeErr(w, err) + return + } + + h.writeLoggingConfiguration(w, r, name, true) +} + +func (h *Handler) describeLoggingConfiguration(w http.ResponseWriter, r *http.Request) { + var req nameArnRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + name, ok := h.resolveFirewall(w, r, req.FirewallName, req.FirewallArn) + if !ok { + return + } + + h.writeLoggingConfiguration(w, r, name, false) +} + +// writeLoggingConfiguration reads the stored configuration back and renders it, +// so both the update and describe responses reflect what is stored (the update +// response also names the firewall). +func (h *Handler) writeLoggingConfiguration(w http.ResponseWriter, r *http.Request, name string, withName bool) { + cfg, err := h.db.DescribeLoggingConfiguration(r.Context(), name) + if err != nil { + writeErr(w, err) + return + } + + fw, err := h.db.DescribeFirewall(r.Context(), name, "") + if err != nil { + writeErr(w, err) + return + } + + resp := map[string]any{ + "FirewallArn": fw.ARN, + "LoggingConfiguration": loggingConfiguration{LogDestinationConfigs: fromLogConfigs(cfg.Destinations)}, + } + if cfg.EnableMonitoringDashboard != nil { + resp["EnableMonitoringDashboard"] = *cfg.EnableMonitoringDashboard + } + + if withName { + resp["FirewallName"] = name + } + + wire.WriteJSON(w, resp) +} + +func toLogConfigs(cs []logDestinationConfig) []nfdriver.LogDestinationConfig { + if len(cs) == 0 { + return nil + } + + out := make([]nfdriver.LogDestinationConfig, 0, len(cs)) + for _, c := range cs { + out = append(out, nfdriver.LogDestinationConfig{ + LogType: c.LogType, LogDestinationType: c.LogDestinationType, LogDestination: c.LogDestination, + }) + } + + return out +} + +func fromLogConfigs(cs []nfdriver.LogDestinationConfig) []logDestinationConfig { + out := make([]logDestinationConfig, 0, len(cs)) + for _, c := range cs { + out = append(out, logDestinationConfig{ + LogType: c.LogType, LogDestinationType: c.LogDestinationType, LogDestination: c.LogDestination, + }) + } + + return out +} diff --git a/server/aws/networkfirewall/metadata.go b/server/aws/networkfirewall/metadata.go new file mode 100644 index 000000000..7a1a7d0c1 --- /dev/null +++ b/server/aws/networkfirewall/metadata.go @@ -0,0 +1,111 @@ +package networkfirewall + +import ( + "net/http" + + "github.com/stackshy/cloudemu/v2/server/wire" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +type firewallArnRequest struct { + FirewallArn string `json:"FirewallArn"` +} + +func (h *Handler) describeFirewallMetadata(w http.ResponseWriter, r *http.Request) { + var req firewallArnRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + meta, ok := capability[nfdriver.Metadata](h, w) + if !ok { + return + } + + m, err := meta.DescribeFirewallMetadata(r.Context(), req.FirewallArn) + if err != nil { + writeErr(w, err) + return + } + + zones := make(map[string]map[string]string, len(m.AvailabilityZones)) + for _, z := range m.AvailabilityZones { + zones[z] = map[string]string{} + } + + resp := map[string]any{ + "FirewallArn": m.FirewallARN, "FirewallPolicyArn": m.PolicyARN, + "Status": m.Status, "SupportedAvailabilityZones": zones, + } + withDescription(resp, m.Description) + + wire.WriteJSON(w, resp) +} + +func (h *Handler) describeRuleGroupMetadata(w http.ResponseWriter, r *http.Request) { + var req ruleGroupNameArnRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + meta, ok := capability[nfdriver.Metadata](h, w) + if !ok { + return + } + + rg, err := meta.DescribeRuleGroupMetadata(r.Context(), req.RuleGroupName, req.RuleGroupArn, req.Type) + if err != nil { + writeErr(w, err) + return + } + + resp := map[string]any{ + "RuleGroupArn": rg.ARN, "RuleGroupName": rg.Name, "Capacity": rg.Capacity, + "LastModifiedTime": epochSeconds(rg.LastModified), "Type": rg.Type, + } + withDescription(resp, rg.Description) + + wire.WriteJSON(w, resp) +} + +type ruleSummaryJSON struct { + Msg string `json:"Msg,omitempty"` + SID string `json:"SID,omitempty"` + Metadata string `json:"Metadata,omitempty"` +} + +func (h *Handler) describeRuleGroupSummary(w http.ResponseWriter, r *http.Request) { + var req ruleGroupNameArnRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + meta, ok := capability[nfdriver.Metadata](h, w) + if !ok { + return + } + + rg, summaries, err := meta.DescribeRuleGroupSummary(r.Context(), req.RuleGroupName, req.RuleGroupArn, req.Type) + if err != nil { + writeErr(w, err) + return + } + + out := make([]ruleSummaryJSON, 0, len(summaries)) + for _, s := range summaries { + out = append(out, ruleSummaryJSON{Msg: s.Msg, SID: s.SID, Metadata: s.Metadata}) + } + + resp := map[string]any{"RuleGroupName": rg.Name, "Summary": map[string]any{"RuleSummaries": out}} + withDescription(resp, rg.Description) + + wire.WriteJSON(w, resp) +} + +// withDescription adds Description to a response only when one is set, as AWS +// omits an absent description rather than returning an empty string. +func withDescription(resp map[string]any, description string) { + if description != "" { + resp["Description"] = description + } +} diff --git a/server/aws/networkfirewall/operations.go b/server/aws/networkfirewall/operations.go index 086fe8579..8b4791f49 100644 --- a/server/aws/networkfirewall/operations.go +++ b/server/aws/networkfirewall/operations.go @@ -4,32 +4,53 @@ import ( "encoding/json" "net/http" "strings" + "time" "github.com/stackshy/cloudemu/v2/server/wire" nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" ) +const millisPerSecond = 1000 + type tag struct { Key string `json:"Key"` Value string `json:"Value"` } type subnetMapping struct { - SubnetID string `json:"SubnetId"` + SubnetID string `json:"SubnetId"` + IPAddressType string `json:"IPAddressType,omitempty"` +} + +type zoneMapping struct { + AvailabilityZone string `json:"AvailabilityZone"` +} + +// epochSeconds renders a timestamp the way AWS JSON 1.0 does (seconds since the +// epoch, fractional), which is what the SDK deserializer expects. +func epochSeconds(t time.Time) float64 { + return float64(t.UnixMilli()) / millisPerSecond } // ---- Firewall ---- type firewallJSON struct { - FirewallName string `json:"FirewallName"` - FirewallArn string `json:"FirewallArn"` - FirewallID string `json:"FirewallId,omitempty"` - FirewallPolicyArn string `json:"FirewallPolicyArn,omitempty"` - VpcID string `json:"VpcId,omitempty"` - SubnetMappings []subnetMapping `json:"SubnetMappings,omitempty"` - Description string `json:"Description,omitempty"` - DeleteProtection bool `json:"DeleteProtection"` - Tags []tag `json:"Tags,omitempty"` + FirewallName string `json:"FirewallName"` + FirewallArn string `json:"FirewallArn"` + FirewallID string `json:"FirewallId,omitempty"` + FirewallPolicyArn string `json:"FirewallPolicyArn,omitempty"` + VpcID string `json:"VpcId,omitempty"` + SubnetMappings []subnetMapping `json:"SubnetMappings,omitempty"` + AvailabilityZoneMappings []zoneMapping `json:"AvailabilityZoneMappings,omitempty"` + TransitGatewayID string `json:"TransitGatewayId,omitempty"` + Description string `json:"Description,omitempty"` + DeleteProtection bool `json:"DeleteProtection"` + SubnetChangeProtection bool `json:"SubnetChangeProtection"` + FirewallPolicyChangeProtection bool `json:"FirewallPolicyChangeProtection"` + AvailabilityZoneChangeProtection bool `json:"AvailabilityZoneChangeProtection"` + EnabledAnalysisTypes []string `json:"EnabledAnalysisTypes,omitempty"` + NumberOfAssociations int `json:"NumberOfAssociations"` + Tags []tag `json:"Tags,omitempty"` } type attachmentJSON struct { @@ -48,12 +69,6 @@ type firewallStatusJSON struct { SyncStates map[string]syncStateJSON `json:"SyncStates,omitempty"` } -// azSuffixes indexes subnets to Availability Zone letters for synthetic -// SyncStates keys. -// -//nolint:gochecknoglobals // immutable lookup table. -var azSuffixes = [...]string{"a", "b", "c", "d", "e", "f"} - // toFirewallStatusJSON builds the FirewallStatus block. A firewall in the // emulator is always fully provisioned, so it reports READY / IN_SYNC with one // SyncState per attached subnet keyed by a synthetic Availability Zone. @@ -62,14 +77,17 @@ func toFirewallStatusJSON(f *nfdriver.Firewall) firewallStatusJSON { states := make(map[string]syncStateJSON, len(f.SubnetIDs)) for i, subnet := range f.SubnetIDs { - az := region + azSuffixes[i%len(azSuffixes)] - states[az] = syncStateJSON{Attachment: attachmentJSON{ + states[nfdriver.AvailabilityZoneFor(region, i)] = syncStateJSON{Attachment: attachmentJSON{ SubnetID: subnet, EndpointID: "vpce-" + f.ID, Status: "READY", }} } + for _, az := range f.AvailabilityZones { + states[az] = syncStateJSON{Attachment: attachmentJSON{EndpointID: "vpce-" + f.ID, Status: "READY"}} + } + if len(states) == 0 { states = nil } @@ -93,13 +111,19 @@ func arnRegion(arn string) string { } type createFirewallRequest struct { - FirewallName string `json:"FirewallName"` - FirewallPolicyArn string `json:"FirewallPolicyArn"` - VpcID string `json:"VpcId"` - SubnetMappings []subnetMapping `json:"SubnetMappings"` - Description string `json:"Description"` - DeleteProtection bool `json:"DeleteProtection"` - Tags []tag `json:"Tags"` + FirewallName string `json:"FirewallName"` + FirewallPolicyArn string `json:"FirewallPolicyArn"` + VpcID string `json:"VpcId"` + SubnetMappings []subnetMapping `json:"SubnetMappings"` + AvailabilityZoneMappings []zoneMapping `json:"AvailabilityZoneMappings"` + TransitGatewayID string `json:"TransitGatewayId"` + Description string `json:"Description"` + DeleteProtection bool `json:"DeleteProtection"` + SubnetChangeProtection bool `json:"SubnetChangeProtection"` + FirewallPolicyChangeProtection bool `json:"FirewallPolicyChangeProtection"` + AvailabilityZoneChangeProtection bool `json:"AvailabilityZoneChangeProtection"` + EnabledAnalysisTypes []string `json:"EnabledAnalysisTypes"` + Tags []tag `json:"Tags"` } type nameArnRequest struct { @@ -114,13 +138,19 @@ func (h *Handler) createFirewall(w http.ResponseWriter, r *http.Request) { } fw, err := h.db.CreateFirewall(r.Context(), nfdriver.CreateFirewallConfig{ - Name: req.FirewallName, - PolicyARN: req.FirewallPolicyArn, - VPCID: req.VpcID, - SubnetIDs: subnetIDs(req.SubnetMappings), - Description: req.Description, - DeleteProtection: req.DeleteProtection, - Tags: tagsToMap(req.Tags), + Name: req.FirewallName, + PolicyARN: req.FirewallPolicyArn, + VPCID: req.VpcID, + SubnetIDs: subnetIDs(req.SubnetMappings), + AvailabilityZones: zoneNames(req.AvailabilityZoneMappings), + TransitGatewayID: req.TransitGatewayID, + Description: req.Description, + DeleteProtection: req.DeleteProtection, + SubnetChangeProtection: req.SubnetChangeProtection, + FirewallPolicyChangeProtection: req.FirewallPolicyChangeProtection, + AvailabilityZoneChangeProtection: req.AvailabilityZoneChangeProtection, + EnabledAnalysisTypes: req.EnabledAnalysisTypes, + Tags: tagsToMap(req.Tags), }) if err != nil { writeErr(w, err) @@ -146,7 +176,7 @@ func (h *Handler) describeFirewall(w http.ResponseWriter, r *http.Request) { } wire.WriteJSON(w, map[string]any{ - "UpdateToken": updateToken, + "UpdateToken": fw.UpdateToken, "Firewall": toFirewallJSON(fw), "FirewallStatus": toFirewallStatusJSON(fw), }) @@ -170,168 +200,19 @@ func (h *Handler) deleteFirewall(w http.ResponseWriter, r *http.Request) { }) } -func (h *Handler) listFirewalls(w http.ResponseWriter, r *http.Request) { - items, err := h.db.ListFirewalls(r.Context()) - if err != nil { - writeErr(w, err) - return - } - - metas := make([]map[string]string, 0, len(items)) - for i := range items { - metas = append(metas, map[string]string{"FirewallName": items[i].Name, "FirewallArn": items[i].ARN}) - } - - wire.WriteJSON(w, map[string]any{"Firewalls": metas}) +type listFirewallsRequest struct { + MaxResults int `json:"MaxResults"` + NextToken string `json:"NextToken"` + VpcIDs []string `json:"VpcIds"` } -func toFirewallJSON(f *nfdriver.Firewall) firewallJSON { - mappings := make([]subnetMapping, 0, len(f.SubnetIDs)) - for _, s := range f.SubnetIDs { - mappings = append(mappings, subnetMapping{SubnetID: s}) - } - - return firewallJSON{ - FirewallName: f.Name, FirewallArn: f.ARN, FirewallID: f.ID, FirewallPolicyArn: f.PolicyARN, - VpcID: f.VPCID, SubnetMappings: mappings, Description: f.Description, - DeleteProtection: f.DeleteProtection, Tags: mapToTags(f.Tags), - } -} - -// ---- Firewall Policy ---- - -type firewallPolicyResponseJSON struct { - FirewallPolicyName string `json:"FirewallPolicyName"` - FirewallPolicyArn string `json:"FirewallPolicyArn"` - FirewallPolicyID string `json:"FirewallPolicyId"` - Description string `json:"Description,omitempty"` - Tags []tag `json:"Tags,omitempty"` -} - -type ruleGroupReferenceJSON struct { - ResourceArn string `json:"ResourceArn"` - Priority int `json:"Priority,omitempty"` -} - -type firewallPolicyDetailJSON struct { - StatelessDefaultActions []string `json:"StatelessDefaultActions,omitempty"` - StatelessFragmentDefaultActions []string `json:"StatelessFragmentDefaultActions,omitempty"` - StatefulRuleGroupReferences []ruleGroupReferenceJSON `json:"StatefulRuleGroupReferences,omitempty"` - StatelessRuleGroupReferences []ruleGroupReferenceJSON `json:"StatelessRuleGroupReferences,omitempty"` -} - -type createFirewallPolicyRequest struct { - FirewallPolicyName string `json:"FirewallPolicyName"` - FirewallPolicy firewallPolicyDetailJSON `json:"FirewallPolicy"` - Description string `json:"Description"` - Tags []tag `json:"Tags"` -} - -type policyNameArnRequest struct { - FirewallPolicyName string `json:"FirewallPolicyName"` - FirewallPolicyArn string `json:"FirewallPolicyArn"` -} - -func (h *Handler) createFirewallPolicy(w http.ResponseWriter, r *http.Request) { - var req createFirewallPolicyRequest - if !wire.DecodeJSON(w, r, &req) { - return - } - - p, err := h.db.CreateFirewallPolicy(r.Context(), nfdriver.CreateFirewallPolicyConfig{ - Name: req.FirewallPolicyName, - Description: req.Description, - StatelessDefaultActions: req.FirewallPolicy.StatelessDefaultActions, - StatelessFragmentDefaultActions: req.FirewallPolicy.StatelessFragmentDefaultActions, - StatefulRuleGroupReferences: toRuleGroupRefs(req.FirewallPolicy.StatefulRuleGroupReferences), - StatelessRuleGroupReferences: toRuleGroupRefs(req.FirewallPolicy.StatelessRuleGroupReferences), - Tags: tagsToMap(req.Tags), - }) - if err != nil { - writeErr(w, err) - return - } - - wire.WriteJSON(w, map[string]any{ - "UpdateToken": updateToken, - "FirewallPolicyResponse": toPolicyResponseJSON(p), - }) -} - -func (h *Handler) describeFirewallPolicy(w http.ResponseWriter, r *http.Request) { - var req policyNameArnRequest - if !wire.DecodeJSON(w, r, &req) { - return - } - - p, err := h.db.DescribeFirewallPolicy(r.Context(), req.FirewallPolicyName, req.FirewallPolicyArn) - if err != nil { - writeErr(w, err) - return - } - - wire.WriteJSON(w, map[string]any{ - "UpdateToken": updateToken, - "FirewallPolicyResponse": toPolicyResponseJSON(p), - "FirewallPolicy": firewallPolicyDetailJSON{ - StatelessDefaultActions: p.StatelessDefaultActions, - StatelessFragmentDefaultActions: p.StatelessFragmentDefaultActions, - StatefulRuleGroupReferences: fromRuleGroupRefs(p.StatefulRuleGroupReferences), - StatelessRuleGroupReferences: fromRuleGroupRefs(p.StatelessRuleGroupReferences), - }, - }) -} - -type updateFirewallPolicyRequest struct { - UpdateToken string `json:"UpdateToken"` - FirewallPolicyName string `json:"FirewallPolicyName"` - FirewallPolicyArn string `json:"FirewallPolicyArn"` - FirewallPolicy firewallPolicyDetailJSON `json:"FirewallPolicy"` - Description string `json:"Description"` -} - -func (h *Handler) updateFirewallPolicy(w http.ResponseWriter, r *http.Request) { - var req updateFirewallPolicyRequest - if !wire.DecodeJSON(w, r, &req) { - return - } - - p, err := h.db.UpdateFirewallPolicy(r.Context(), req.FirewallPolicyName, req.FirewallPolicyArn, - nfdriver.UpdateFirewallPolicyConfig{ - Description: req.Description, - StatelessDefaultActions: req.FirewallPolicy.StatelessDefaultActions, - StatelessFragmentDefaultActions: req.FirewallPolicy.StatelessFragmentDefaultActions, - StatefulRuleGroupReferences: toRuleGroupRefs(req.FirewallPolicy.StatefulRuleGroupReferences), - StatelessRuleGroupReferences: toRuleGroupRefs(req.FirewallPolicy.StatelessRuleGroupReferences), - }) - if err != nil { - writeErr(w, err) - return - } - - wire.WriteJSON(w, map[string]any{ - "UpdateToken": updateToken, - "FirewallPolicyResponse": toPolicyResponseJSON(p), - }) -} - -func (h *Handler) deleteFirewallPolicy(w http.ResponseWriter, r *http.Request) { - var req policyNameArnRequest +func (h *Handler) listFirewalls(w http.ResponseWriter, r *http.Request) { + var req listFirewallsRequest if !wire.DecodeJSON(w, r, &req) { return } - p, err := h.db.DeleteFirewallPolicy(r.Context(), req.FirewallPolicyName, req.FirewallPolicyArn) - if err != nil { - writeErr(w, err) - return - } - - wire.WriteJSON(w, map[string]any{"FirewallPolicyResponse": toPolicyResponseJSON(p)}) -} - -func (h *Handler) listFirewallPolicies(w http.ResponseWriter, r *http.Request) { - items, err := h.db.ListFirewallPolicies(r.Context()) + items, next, err := h.db.ListFirewalls(r.Context(), req.VpcIDs, nfdriver.ListOptions{MaxResults: req.MaxResults, NextToken: req.NextToken}) if err != nil { writeErr(w, err) return @@ -339,165 +220,67 @@ func (h *Handler) listFirewallPolicies(w http.ResponseWriter, r *http.Request) { metas := make([]map[string]string, 0, len(items)) for i := range items { - metas = append(metas, map[string]string{"Name": items[i].Name, "Arn": items[i].ARN}) - } - - wire.WriteJSON(w, map[string]any{"FirewallPolicies": metas}) -} - -func toPolicyResponseJSON(p *nfdriver.FirewallPolicy) firewallPolicyResponseJSON { - return firewallPolicyResponseJSON{ - FirewallPolicyName: p.Name, FirewallPolicyArn: p.ARN, FirewallPolicyID: p.ID, - Description: p.Description, Tags: mapToTags(p.Tags), + metas = append(metas, map[string]string{"FirewallName": items[i].Name, "FirewallArn": items[i].ARN}) } -} - -// ---- Rule Group ---- - -type ruleGroupResponseJSON struct { - RuleGroupName string `json:"RuleGroupName"` - RuleGroupArn string `json:"RuleGroupArn"` - RuleGroupID string `json:"RuleGroupId"` - Type string `json:"Type"` - Capacity int `json:"Capacity,omitempty"` - Description string `json:"Description,omitempty"` - Tags []tag `json:"Tags,omitempty"` -} - -type createRuleGroupRequest struct { - RuleGroupName string `json:"RuleGroupName"` - RuleGroup json.RawMessage `json:"RuleGroup"` - Rules string `json:"Rules"` - Type string `json:"Type"` - Capacity int `json:"Capacity"` - Description string `json:"Description"` - Tags []tag `json:"Tags"` -} -type ruleGroupNameArnRequest struct { - RuleGroupName string `json:"RuleGroupName"` - RuleGroupArn string `json:"RuleGroupArn"` - Type string `json:"Type"` + wire.WriteJSON(w, withNextToken(map[string]any{"Firewalls": metas}, next)) } -func (h *Handler) createRuleGroup(w http.ResponseWriter, r *http.Request) { - var req createRuleGroupRequest - if !wire.DecodeJSON(w, r, &req) { - return +// withNextToken adds NextToken to a list response when there is another page. +func withNextToken(resp map[string]any, next string) map[string]any { + if next != "" { + resp["NextToken"] = next } - rg, err := h.db.CreateRuleGroup(r.Context(), nfdriver.CreateRuleGroupConfig{ - Name: req.RuleGroupName, Type: req.Type, Capacity: req.Capacity, - Description: req.Description, Rules: ruleGroupPayload(req.RuleGroup, req.Rules), Tags: tagsToMap(req.Tags), - }) - if err != nil { - writeErr(w, err) - return - } - - wire.WriteJSON(w, map[string]any{ - "UpdateToken": updateToken, - "RuleGroupResponse": toRuleGroupResponseJSON(rg), - "RuleGroup": rg.Rules, - }) + return resp } -func (h *Handler) describeRuleGroup(w http.ResponseWriter, r *http.Request) { - var req ruleGroupNameArnRequest - if !wire.DecodeJSON(w, r, &req) { - return - } - - rg, err := h.db.DescribeRuleGroup(r.Context(), req.RuleGroupName, req.RuleGroupArn, req.Type) - if err != nil { - writeErr(w, err) - return +func toFirewallJSON(f *nfdriver.Firewall) firewallJSON { + mappings := make([]subnetMapping, 0, len(f.SubnetIDs)) + for _, s := range f.SubnetIDs { + mappings = append(mappings, subnetMapping{SubnetID: s}) } - wire.WriteJSON(w, map[string]any{ - "UpdateToken": updateToken, - "RuleGroupResponse": toRuleGroupResponseJSON(rg), - "RuleGroup": rg.Rules, - }) -} - -type updateRuleGroupRequest struct { - UpdateToken string `json:"UpdateToken"` - RuleGroupName string `json:"RuleGroupName"` - RuleGroupArn string `json:"RuleGroupArn"` - RuleGroup json.RawMessage `json:"RuleGroup"` - Rules string `json:"Rules"` - Type string `json:"Type"` - Description string `json:"Description"` -} - -func (h *Handler) updateRuleGroup(w http.ResponseWriter, r *http.Request) { - var req updateRuleGroupRequest - if !wire.DecodeJSON(w, r, &req) { - return + zones := make([]zoneMapping, 0, len(f.AvailabilityZones)) + for _, z := range f.AvailabilityZones { + zones = append(zones, zoneMapping{AvailabilityZone: z}) } - rg, err := h.db.UpdateRuleGroup(r.Context(), req.RuleGroupName, req.RuleGroupArn, req.Type, - nfdriver.UpdateRuleGroupConfig{Description: req.Description, Rules: ruleGroupPayload(req.RuleGroup, req.Rules)}) - if err != nil { - writeErr(w, err) - return + return firewallJSON{ + FirewallName: f.Name, FirewallArn: f.ARN, FirewallID: f.ID, FirewallPolicyArn: f.PolicyARN, + VpcID: f.VPCID, SubnetMappings: mappings, AvailabilityZoneMappings: zones, + TransitGatewayID: f.TransitGatewayID, Description: f.Description, + DeleteProtection: f.DeleteProtection, SubnetChangeProtection: f.SubnetChangeProtection, + FirewallPolicyChangeProtection: f.FirewallPolicyChangeProtection, + AvailabilityZoneChangeProtection: f.AvailabilityZoneChangeProtection, + EnabledAnalysisTypes: f.EnabledAnalysisTypes, NumberOfAssociations: f.NumberOfAssociations, + Tags: mapToTags(f.Tags), } - - wire.WriteJSON(w, map[string]any{ - "UpdateToken": updateToken, - "RuleGroupResponse": toRuleGroupResponseJSON(rg), - "RuleGroup": rg.Rules, - }) } -func (h *Handler) deleteRuleGroup(w http.ResponseWriter, r *http.Request) { - var req ruleGroupNameArnRequest - if !wire.DecodeJSON(w, r, &req) { - return - } - - rg, err := h.db.DeleteRuleGroup(r.Context(), req.RuleGroupName, req.RuleGroupArn, req.Type) - if err != nil { - writeErr(w, err) - return - } - - wire.WriteJSON(w, map[string]any{"RuleGroupResponse": toRuleGroupResponseJSON(rg)}) -} +// ---- helpers ---- -func (h *Handler) listRuleGroups(w http.ResponseWriter, r *http.Request) { - items, err := h.db.ListRuleGroups(r.Context()) - if err != nil { - writeErr(w, err) - return +func subnetIDs(mappings []subnetMapping) []string { + if len(mappings) == 0 { + return nil } - metas := make([]map[string]string, 0, len(items)) - for i := range items { - metas = append(metas, map[string]string{"Name": items[i].Name, "Arn": items[i].ARN}) + out := make([]string, 0, len(mappings)) + for _, m := range mappings { + out = append(out, m.SubnetID) } - wire.WriteJSON(w, map[string]any{"RuleGroups": metas}) -} - -func toRuleGroupResponseJSON(rg *nfdriver.RuleGroup) ruleGroupResponseJSON { - return ruleGroupResponseJSON{ - RuleGroupName: rg.Name, RuleGroupArn: rg.ARN, RuleGroupID: rg.ID, Type: rg.Type, - Capacity: rg.Capacity, Description: rg.Description, Tags: mapToTags(rg.Tags), - } + return out } -// ---- helpers ---- - -func subnetIDs(mappings []subnetMapping) []string { +func zoneNames(mappings []zoneMapping) []string { if len(mappings) == 0 { return nil } out := make([]string, 0, len(mappings)) for _, m := range mappings { - out = append(out, m.SubnetID) + out = append(out, m.AvailabilityZone) } return out @@ -554,29 +337,3 @@ func ruleGroupPayload(ruleGroup json.RawMessage, legacyRules string) json.RawMes return b } - -func toRuleGroupRefs(refs []ruleGroupReferenceJSON) []nfdriver.RuleGroupReference { - if len(refs) == 0 { - return nil - } - - out := make([]nfdriver.RuleGroupReference, 0, len(refs)) - for _, r := range refs { - out = append(out, nfdriver.RuleGroupReference{ResourceARN: r.ResourceArn, Priority: r.Priority}) - } - - return out -} - -func fromRuleGroupRefs(refs []nfdriver.RuleGroupReference) []ruleGroupReferenceJSON { - if len(refs) == 0 { - return nil - } - - out := make([]ruleGroupReferenceJSON, 0, len(refs)) - for _, r := range refs { - out = append(out, ruleGroupReferenceJSON{ResourceArn: r.ResourceARN, Priority: r.Priority}) - } - - return out -} diff --git a/server/aws/networkfirewall/policy.go b/server/aws/networkfirewall/policy.go new file mode 100644 index 000000000..0fad596cb --- /dev/null +++ b/server/aws/networkfirewall/policy.go @@ -0,0 +1,258 @@ +package networkfirewall + +import ( + "encoding/json" + "net/http" + + "github.com/stackshy/cloudemu/v2/server/wire" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +type firewallPolicyResponseJSON struct { + FirewallPolicyName string `json:"FirewallPolicyName"` + FirewallPolicyArn string `json:"FirewallPolicyArn"` + FirewallPolicyID string `json:"FirewallPolicyId"` + Description string `json:"Description,omitempty"` + FirewallPolicyStatus string `json:"FirewallPolicyStatus,omitempty"` + NumberOfAssociations int `json:"NumberOfAssociations"` + ConsumedStatelessRuleCapacity int `json:"ConsumedStatelessRuleCapacity"` + ConsumedStatefulRuleCapacity int `json:"ConsumedStatefulRuleCapacity"` + ConsumedStatefulDomainCapacity int `json:"ConsumedStatefulDomainCapacity"` + LastModifiedTime *float64 `json:"LastModifiedTime,omitempty"` + Tags []tag `json:"Tags,omitempty"` +} + +type ruleGroupReferenceJSON struct { + ResourceArn string `json:"ResourceArn"` + Priority int `json:"Priority,omitempty"` + Override json.RawMessage `json:"Override,omitempty"` + DeepThreatInspection *bool `json:"DeepThreatInspection,omitempty"` +} + +type firewallPolicyDetailJSON struct { + StatelessDefaultActions []string `json:"StatelessDefaultActions,omitempty"` + StatelessFragmentDefaultActions []string `json:"StatelessFragmentDefaultActions,omitempty"` + StatefulDefaultActions []string `json:"StatefulDefaultActions,omitempty"` + StatefulRuleGroupReferences []ruleGroupReferenceJSON `json:"StatefulRuleGroupReferences,omitempty"` + StatelessRuleGroupReferences []ruleGroupReferenceJSON `json:"StatelessRuleGroupReferences,omitempty"` + TLSInspectionConfigurationArn string `json:"TLSInspectionConfigurationArn,omitempty"` + StatelessCustomActions json.RawMessage `json:"StatelessCustomActions,omitempty"` + PolicyVariables json.RawMessage `json:"PolicyVariables,omitempty"` + StatefulEngineOptions json.RawMessage `json:"StatefulEngineOptions,omitempty"` + EnableTLSSessionHolding *bool `json:"EnableTLSSessionHolding,omitempty"` +} + +type createFirewallPolicyRequest struct { + FirewallPolicyName string `json:"FirewallPolicyName"` + FirewallPolicy firewallPolicyDetailJSON `json:"FirewallPolicy"` + Description string `json:"Description"` + Tags []tag `json:"Tags"` +} + +type policyNameArnRequest struct { + FirewallPolicyName string `json:"FirewallPolicyName"` + FirewallPolicyArn string `json:"FirewallPolicyArn"` +} + +func (h *Handler) createFirewallPolicy(w http.ResponseWriter, r *http.Request) { + var req createFirewallPolicyRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + d := req.FirewallPolicy + + p, err := h.db.CreateFirewallPolicy(r.Context(), nfdriver.CreateFirewallPolicyConfig{ + Name: req.FirewallPolicyName, + Description: req.Description, + StatelessDefaultActions: d.StatelessDefaultActions, + StatelessFragmentDefaultActions: d.StatelessFragmentDefaultActions, + StatefulDefaultActions: d.StatefulDefaultActions, + StatefulRuleGroupReferences: toRuleGroupRefs(d.StatefulRuleGroupReferences), + StatelessRuleGroupReferences: toRuleGroupRefs(d.StatelessRuleGroupReferences), + TLSInspectionConfigurationARN: d.TLSInspectionConfigurationArn, + Extra: policyExtra(&d), + Tags: tagsToMap(req.Tags), + }) + if err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{ + "UpdateToken": p.UpdateToken, + "FirewallPolicyResponse": toPolicyResponseJSON(p), + }) +} + +func (h *Handler) describeFirewallPolicy(w http.ResponseWriter, r *http.Request) { + var req policyNameArnRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + p, err := h.db.DescribeFirewallPolicy(r.Context(), req.FirewallPolicyName, req.FirewallPolicyArn) + if err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{ + "UpdateToken": p.UpdateToken, + "FirewallPolicyResponse": toPolicyResponseJSON(p), + "FirewallPolicy": toPolicyDetailJSON(p), + }) +} + +type updateFirewallPolicyRequest struct { + UpdateToken string `json:"UpdateToken"` + FirewallPolicyName string `json:"FirewallPolicyName"` + FirewallPolicyArn string `json:"FirewallPolicyArn"` + FirewallPolicy firewallPolicyDetailJSON `json:"FirewallPolicy"` + Description string `json:"Description"` +} + +func (h *Handler) updateFirewallPolicy(w http.ResponseWriter, r *http.Request) { + var req updateFirewallPolicyRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + d := req.FirewallPolicy + + p, err := h.db.UpdateFirewallPolicy(r.Context(), req.FirewallPolicyName, req.FirewallPolicyArn, + nfdriver.UpdateFirewallPolicyConfig{ + UpdateToken: req.UpdateToken, + Description: req.Description, + StatelessDefaultActions: d.StatelessDefaultActions, + StatelessFragmentDefaultActions: d.StatelessFragmentDefaultActions, + StatefulDefaultActions: d.StatefulDefaultActions, + StatefulRuleGroupReferences: toRuleGroupRefs(d.StatefulRuleGroupReferences), + StatelessRuleGroupReferences: toRuleGroupRefs(d.StatelessRuleGroupReferences), + TLSInspectionConfigurationARN: d.TLSInspectionConfigurationArn, + Extra: policyExtra(&d), + }) + if err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{ + "UpdateToken": p.UpdateToken, + "FirewallPolicyResponse": toPolicyResponseJSON(p), + }) +} + +func (h *Handler) deleteFirewallPolicy(w http.ResponseWriter, r *http.Request) { + var req policyNameArnRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + p, err := h.db.DeleteFirewallPolicy(r.Context(), req.FirewallPolicyName, req.FirewallPolicyArn) + if err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{"FirewallPolicyResponse": toPolicyResponseJSON(p)}) +} + +type listRequest struct { + MaxResults int `json:"MaxResults"` + NextToken string `json:"NextToken"` +} + +func (l listRequest) options() nfdriver.ListOptions { + return nfdriver.ListOptions{MaxResults: l.MaxResults, NextToken: l.NextToken} +} + +func (h *Handler) listFirewallPolicies(w http.ResponseWriter, r *http.Request) { + var req listRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + items, next, err := h.db.ListFirewallPolicies(r.Context(), req.options()) + if err != nil { + writeErr(w, err) + return + } + + metas := make([]map[string]string, 0, len(items)) + for i := range items { + metas = append(metas, map[string]string{"Name": items[i].Name, "Arn": items[i].ARN}) + } + + wire.WriteJSON(w, withNextToken(map[string]any{"FirewallPolicies": metas}, next)) +} + +func toPolicyResponseJSON(p *nfdriver.FirewallPolicy) firewallPolicyResponseJSON { + modified := epochSeconds(p.LastModified) + + return firewallPolicyResponseJSON{ + FirewallPolicyName: p.Name, FirewallPolicyArn: p.ARN, FirewallPolicyID: p.ID, + Description: p.Description, FirewallPolicyStatus: p.Status, + NumberOfAssociations: p.NumberOfAssociations, + ConsumedStatelessRuleCapacity: p.ConsumedStatelessRuleCapacity, + ConsumedStatefulRuleCapacity: p.ConsumedStatefulRuleCapacity, + ConsumedStatefulDomainCapacity: p.ConsumedStatefulDomainCapacity, + LastModifiedTime: &modified, Tags: mapToTags(p.Tags), + } +} + +func toPolicyDetailJSON(p *nfdriver.FirewallPolicy) firewallPolicyDetailJSON { + return firewallPolicyDetailJSON{ + StatelessDefaultActions: p.StatelessDefaultActions, + StatelessFragmentDefaultActions: p.StatelessFragmentDefaultActions, + StatefulDefaultActions: p.StatefulDefaultActions, + StatefulRuleGroupReferences: fromRuleGroupRefs(p.StatefulRuleGroupReferences), + StatelessRuleGroupReferences: fromRuleGroupRefs(p.StatelessRuleGroupReferences), + TLSInspectionConfigurationArn: p.TLSInspectionConfigurationARN, + StatelessCustomActions: p.Extra.StatelessCustomActions, + PolicyVariables: p.Extra.PolicyVariables, + StatefulEngineOptions: p.Extra.StatefulEngineOptions, + EnableTLSSessionHolding: p.Extra.EnableTLSSessionHolding, + } +} + +func policyExtra(d *firewallPolicyDetailJSON) nfdriver.PolicyExtra { + return nfdriver.PolicyExtra{ + StatelessCustomActions: d.StatelessCustomActions, + PolicyVariables: d.PolicyVariables, + StatefulEngineOptions: d.StatefulEngineOptions, + EnableTLSSessionHolding: d.EnableTLSSessionHolding, + } +} + +func toRuleGroupRefs(refs []ruleGroupReferenceJSON) []nfdriver.RuleGroupReference { + if len(refs) == 0 { + return nil + } + + out := make([]nfdriver.RuleGroupReference, 0, len(refs)) + for _, r := range refs { + out = append(out, nfdriver.RuleGroupReference{ + ResourceARN: r.ResourceArn, Priority: r.Priority, + Override: r.Override, DeepThreatInspection: r.DeepThreatInspection, + }) + } + + return out +} + +func fromRuleGroupRefs(refs []nfdriver.RuleGroupReference) []ruleGroupReferenceJSON { + if len(refs) == 0 { + return nil + } + + out := make([]ruleGroupReferenceJSON, 0, len(refs)) + for _, r := range refs { + out = append(out, ruleGroupReferenceJSON{ + ResourceArn: r.ResourceARN, Priority: r.Priority, + Override: r.Override, DeepThreatInspection: r.DeepThreatInspection, + }) + } + + return out +} diff --git a/server/aws/networkfirewall/resource_policy.go b/server/aws/networkfirewall/resource_policy.go new file mode 100644 index 000000000..8567dcf23 --- /dev/null +++ b/server/aws/networkfirewall/resource_policy.go @@ -0,0 +1,75 @@ +package networkfirewall + +import ( + "net/http" + + "github.com/stackshy/cloudemu/v2/server/wire" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +type putResourcePolicyRequest struct { + ResourceArn string `json:"ResourceArn"` + Policy string `json:"Policy"` +} + +type resourceArnRequest struct { + ResourceArn string `json:"ResourceArn"` +} + +func (h *Handler) putResourcePolicy(w http.ResponseWriter, r *http.Request) { + var req putResourcePolicyRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + policies, ok := capability[nfdriver.ResourcePolicies](h, w) + if !ok { + return + } + + if err := policies.PutResourcePolicy(r.Context(), req.ResourceArn, req.Policy); err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{}) +} + +func (h *Handler) describeResourcePolicy(w http.ResponseWriter, r *http.Request) { + var req resourceArnRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + policies, ok := capability[nfdriver.ResourcePolicies](h, w) + if !ok { + return + } + + policy, err := policies.DescribeResourcePolicy(r.Context(), req.ResourceArn) + if err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{"Policy": policy}) +} + +func (h *Handler) deleteResourcePolicy(w http.ResponseWriter, r *http.Request) { + var req resourceArnRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + policies, ok := capability[nfdriver.ResourcePolicies](h, w) + if !ok { + return + } + + if err := policies.DeleteResourcePolicy(r.Context(), req.ResourceArn); err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{}) +} diff --git a/server/aws/networkfirewall/rule_group.go b/server/aws/networkfirewall/rule_group.go new file mode 100644 index 000000000..9eceaadc6 --- /dev/null +++ b/server/aws/networkfirewall/rule_group.go @@ -0,0 +1,219 @@ +package networkfirewall + +import ( + "encoding/json" + "net/http" + + cerrors "github.com/stackshy/cloudemu/v2/errors" + "github.com/stackshy/cloudemu/v2/server/wire" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +type summaryConfigurationJSON struct { + RuleOptions []string `json:"RuleOptions"` +} + +type ruleGroupResponseJSON struct { + RuleGroupName string `json:"RuleGroupName"` + RuleGroupArn string `json:"RuleGroupArn"` + RuleGroupID string `json:"RuleGroupId"` + Type string `json:"Type"` + Capacity int `json:"Capacity,omitempty"` + ConsumedCapacity int `json:"ConsumedCapacity"` + NumberOfAssociations int `json:"NumberOfAssociations"` + Description string `json:"Description,omitempty"` + RuleGroupStatus string `json:"RuleGroupStatus,omitempty"` + LastModifiedTime *float64 `json:"LastModifiedTime,omitempty"` + SummaryConfiguration *summaryConfigurationJSON `json:"SummaryConfiguration,omitempty"` + Tags []tag `json:"Tags,omitempty"` +} + +type createRuleGroupRequest struct { + RuleGroupName string `json:"RuleGroupName"` + RuleGroup json.RawMessage `json:"RuleGroup"` + Rules string `json:"Rules"` + Type string `json:"Type"` + Capacity int `json:"Capacity"` + Description string `json:"Description"` + SummaryConfiguration *summaryConfigurationJSON `json:"SummaryConfiguration"` + Tags []tag `json:"Tags"` +} + +type ruleGroupNameArnRequest struct { + RuleGroupName string `json:"RuleGroupName"` + RuleGroupArn string `json:"RuleGroupArn"` + Type string `json:"Type"` +} + +// ruleGroupBody resolves the rules of a create/update request. RuleGroup and +// Rules are alternatives (AWS: "either this or Rules, but not both"); giving +// neither stores an empty rule group, as the emulator always has. +func ruleGroupBody(ruleGroup json.RawMessage, rules string) (json.RawMessage, error) { + hasGroup := len(ruleGroup) > 0 && string(ruleGroup) != "null" + + if hasGroup && rules != "" { + return nil, cerrors.New(cerrors.InvalidArgument, "provide either RuleGroup or Rules, not both") + } + + if !hasGroup && rules == "" { + return nil, nil + } + + if !hasGroup { + ruleGroup = nil + } + + return ruleGroupPayload(ruleGroup, rules), nil +} + +func summaryOptions(c *summaryConfigurationJSON) []string { + if c == nil { + return nil + } + + return append([]string{}, c.RuleOptions...) +} + +func (h *Handler) createRuleGroup(w http.ResponseWriter, r *http.Request) { + var req createRuleGroupRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + body, err := ruleGroupBody(req.RuleGroup, req.Rules) + if err != nil { + writeErr(w, err) + return + } + + rg, err := h.db.CreateRuleGroup(r.Context(), nfdriver.CreateRuleGroupConfig{ + Name: req.RuleGroupName, Type: req.Type, Capacity: req.Capacity, Description: req.Description, + Rules: body, SummaryRuleOptions: summaryOptions(req.SummaryConfiguration), Tags: tagsToMap(req.Tags), + }) + if err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{ + "UpdateToken": rg.UpdateToken, + "RuleGroupResponse": toRuleGroupResponseJSON(rg), + }) +} + +func (h *Handler) describeRuleGroup(w http.ResponseWriter, r *http.Request) { + var req ruleGroupNameArnRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + rg, err := h.db.DescribeRuleGroup(r.Context(), req.RuleGroupName, req.RuleGroupArn, req.Type) + if err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{ + "UpdateToken": rg.UpdateToken, + "RuleGroupResponse": toRuleGroupResponseJSON(rg), + "RuleGroup": rg.Rules, + }) +} + +type updateRuleGroupRequest struct { + UpdateToken string `json:"UpdateToken"` + RuleGroupName string `json:"RuleGroupName"` + RuleGroupArn string `json:"RuleGroupArn"` + RuleGroup json.RawMessage `json:"RuleGroup"` + Rules string `json:"Rules"` + Type string `json:"Type"` + Description string `json:"Description"` + SummaryConfiguration *summaryConfigurationJSON `json:"SummaryConfiguration"` +} + +func (h *Handler) updateRuleGroup(w http.ResponseWriter, r *http.Request) { + var req updateRuleGroupRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + body, err := ruleGroupBody(req.RuleGroup, req.Rules) + if err != nil { + writeErr(w, err) + return + } + + rg, err := h.db.UpdateRuleGroup(r.Context(), req.RuleGroupName, req.RuleGroupArn, req.Type, + nfdriver.UpdateRuleGroupConfig{ + UpdateToken: req.UpdateToken, Description: req.Description, Rules: body, + SummaryRuleOptions: summaryOptions(req.SummaryConfiguration), + }) + if err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{ + "UpdateToken": rg.UpdateToken, + "RuleGroupResponse": toRuleGroupResponseJSON(rg), + }) +} + +func (h *Handler) deleteRuleGroup(w http.ResponseWriter, r *http.Request) { + var req ruleGroupNameArnRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + rg, err := h.db.DeleteRuleGroup(r.Context(), req.RuleGroupName, req.RuleGroupArn, req.Type) + if err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{"RuleGroupResponse": toRuleGroupResponseJSON(rg)}) +} + +type listRuleGroupsRequest struct { + listRequest + Type string `json:"Type"` + Scope string `json:"Scope"` + ManagedType string `json:"ManagedType"` +} + +func (h *Handler) listRuleGroups(w http.ResponseWriter, r *http.Request) { + var req listRuleGroupsRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + filter := nfdriver.RuleGroupFilter{Type: req.Type, Scope: req.Scope, ManagedType: req.ManagedType} + + items, next, err := h.db.ListRuleGroups(r.Context(), filter, req.options()) + if err != nil { + writeErr(w, err) + return + } + + metas := make([]map[string]string, 0, len(items)) + for i := range items { + metas = append(metas, map[string]string{"Name": items[i].Name, "Arn": items[i].ARN}) + } + + wire.WriteJSON(w, withNextToken(map[string]any{"RuleGroups": metas}, next)) +} + +func toRuleGroupResponseJSON(rg *nfdriver.RuleGroup) ruleGroupResponseJSON { + modified := epochSeconds(rg.LastModified) + + out := ruleGroupResponseJSON{ + RuleGroupName: rg.Name, RuleGroupArn: rg.ARN, RuleGroupID: rg.ID, Type: rg.Type, + Capacity: rg.Capacity, ConsumedCapacity: rg.ConsumedCapacity, NumberOfAssociations: rg.NumberOfAssociations, + Description: rg.Description, RuleGroupStatus: rg.Status, LastModifiedTime: &modified, Tags: mapToTags(rg.Tags), + } + if len(rg.SummaryRuleOptions) > 0 { + out.SummaryConfiguration = &summaryConfigurationJSON{RuleOptions: rg.SummaryRuleOptions} + } + + return out +} diff --git a/server/aws/networkfirewall/sdk_parity_test.go b/server/aws/networkfirewall/sdk_parity_test.go new file mode 100644 index 000000000..fbaf0e579 --- /dev/null +++ b/server/aws/networkfirewall/sdk_parity_test.go @@ -0,0 +1,708 @@ +package networkfirewall_test + +import ( + "context" + "encoding/json" + "fmt" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/networkfirewall" + nftypes "github.com/aws/aws-sdk-go-v2/service/networkfirewall/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var bg = context.Background() + +// stack is a policy plus a firewall using it, created through the SDK. +type stack struct { + c *networkfirewall.Client + policyARN string + firewallID string + fwARN string +} + +func newStack(t *testing.T) *stack { + t.Helper() + + c := newClient(t) + + pol, err := c.CreateFirewallPolicy(bg, &networkfirewall.CreateFirewallPolicyInput{ + FirewallPolicyName: aws.String("pol-1"), + FirewallPolicy: &nftypes.FirewallPolicy{ + StatelessDefaultActions: []string{"aws:forward_to_sfe"}, StatelessFragmentDefaultActions: []string{"aws:forward_to_sfe"}, + }, + }) + require.NoError(t, err) + + fw, err := c.CreateFirewall(bg, &networkfirewall.CreateFirewallInput{ + FirewallName: aws.String("fw-1"), FirewallPolicyArn: pol.FirewallPolicyResponse.FirewallPolicyArn, + VpcId: aws.String("vpc-1a"), SubnetMappings: []nftypes.SubnetMapping{{SubnetId: aws.String("subnet-1")}}, + }) + require.NoError(t, err) + + return &stack{c: c, policyARN: aws.ToString(pol.FirewallPolicyResponse.FirewallPolicyArn), fwARN: aws.ToString(fw.Firewall.FirewallArn)} +} + +func (s *stack) token(t *testing.T) *string { + t.Helper() + + d, err := s.c.DescribeFirewall(bg, &networkfirewall.DescribeFirewallInput{FirewallName: aws.String("fw-1")}) + require.NoError(t, err) + + return d.UpdateToken +} + +func TestSDK_UpdateToken_Flow(t *testing.T) { + s := newStack(t) + stale := s.token(t) + + first, err := s.c.UpdateFirewallDeleteProtection(bg, &networkfirewall.UpdateFirewallDeleteProtectionInput{ + FirewallName: aws.String("fw-1"), DeleteProtection: true, UpdateToken: stale, + }) + require.NoError(t, err) + assert.NotEqual(t, aws.ToString(stale), aws.ToString(first.UpdateToken), "the token rotates on every mutation") + + _, err = s.c.UpdateFirewallDeleteProtection(bg, &networkfirewall.UpdateFirewallDeleteProtectionInput{ + FirewallName: aws.String("fw-1"), DeleteProtection: false, UpdateToken: stale, + }) + + var invalidToken *nftypes.InvalidTokenException + require.ErrorAs(t, err, &invalidToken) + + _, err = s.c.UpdateFirewallDeleteProtection(bg, &networkfirewall.UpdateFirewallDeleteProtectionInput{ + FirewallName: aws.String("fw-1"), DeleteProtection: false, + }) + require.NoError(t, err, "an update without a token is unconditional") + + // Policies and rule groups need a current token too. + _, err = s.c.UpdateFirewallPolicy(bg, &networkfirewall.UpdateFirewallPolicyInput{ + FirewallPolicyArn: aws.String(s.policyARN), UpdateToken: aws.String("11111111-1111-1111-1111-111111111111"), + FirewallPolicy: &nftypes.FirewallPolicy{ + StatelessDefaultActions: []string{"aws:drop"}, StatelessFragmentDefaultActions: []string{"aws:drop"}, + }, + }) + require.ErrorAs(t, err, &invalidToken) +} + +func TestSDK_ChangeProtection_AllOps(t *testing.T) { + s := newStack(t) + + sub, err := s.c.UpdateSubnetChangeProtection(bg, &networkfirewall.UpdateSubnetChangeProtectionInput{ + FirewallName: aws.String("fw-1"), SubnetChangeProtection: true, + }) + require.NoError(t, err) + assert.True(t, sub.SubnetChangeProtection) + + pol, err := s.c.UpdateFirewallPolicyChangeProtection(bg, &networkfirewall.UpdateFirewallPolicyChangeProtectionInput{ + FirewallArn: aws.String(s.fwARN), FirewallPolicyChangeProtection: true, UpdateToken: sub.UpdateToken, + }) + require.NoError(t, err) + assert.True(t, pol.FirewallPolicyChangeProtection) + + az, err := s.c.UpdateAvailabilityZoneChangeProtection(bg, &networkfirewall.UpdateAvailabilityZoneChangeProtectionInput{ + FirewallName: aws.String("fw-1"), AvailabilityZoneChangeProtection: true, + }) + require.NoError(t, err) + assert.True(t, az.AvailabilityZoneChangeProtection) + + d, err := s.c.DescribeFirewall(bg, &networkfirewall.DescribeFirewallInput{FirewallName: aws.String("fw-1")}) + require.NoError(t, err) + assert.True(t, d.Firewall.SubnetChangeProtection && d.Firewall.FirewallPolicyChangeProtection && d.Firewall.AvailabilityZoneChangeProtection) + + var invalidOp *nftypes.InvalidOperationException + + _, err = s.c.AssociateSubnets(bg, &networkfirewall.AssociateSubnetsInput{ + FirewallName: aws.String("fw-1"), SubnetMappings: []nftypes.SubnetMapping{{SubnetId: aws.String("subnet-2")}}, + }) + require.ErrorAs(t, err, &invalidOp) + + _, err = s.c.DisassociateSubnets(bg, &networkfirewall.DisassociateSubnetsInput{FirewallName: aws.String("fw-1"), SubnetIds: []string{"subnet-1"}}) + require.ErrorAs(t, err, &invalidOp) + + other, err := s.c.CreateFirewallPolicy(bg, &networkfirewall.CreateFirewallPolicyInput{ + FirewallPolicyName: aws.String("pol-2"), + FirewallPolicy: &nftypes.FirewallPolicy{ + StatelessDefaultActions: []string{"aws:pass"}, StatelessFragmentDefaultActions: []string{"aws:pass"}, + }, + }) + require.NoError(t, err) + + _, err = s.c.AssociateFirewallPolicy(bg, &networkfirewall.AssociateFirewallPolicyInput{ + FirewallName: aws.String("fw-1"), FirewallPolicyArn: other.FirewallPolicyResponse.FirewallPolicyArn, + }) + require.ErrorAs(t, err, &invalidOp) + + // Availability Zone operations only apply to transit gateway-attached firewalls. + _, err = s.c.AssociateAvailabilityZones(bg, &networkfirewall.AssociateAvailabilityZonesInput{ + FirewallName: aws.String("fw-1"), AvailabilityZoneMappings: []nftypes.AvailabilityZoneMapping{{AvailabilityZone: aws.String("us-east-1b")}}, + }) + require.ErrorAs(t, err, &invalidOp) + + tgw, err := s.c.CreateFirewall(bg, &networkfirewall.CreateFirewallInput{ + FirewallName: aws.String("fw-tgw"), FirewallPolicyArn: aws.String(s.policyARN), TransitGatewayId: aws.String("tgw-0abc"), + AvailabilityZoneMappings: []nftypes.AvailabilityZoneMapping{{AvailabilityZone: aws.String("us-east-1a")}}, + }) + require.NoError(t, err) + assert.Equal(t, "tgw-0abc", aws.ToString(tgw.Firewall.TransitGatewayId)) + + added, err := s.c.AssociateAvailabilityZones(bg, &networkfirewall.AssociateAvailabilityZonesInput{ + FirewallName: aws.String("fw-tgw"), AvailabilityZoneMappings: []nftypes.AvailabilityZoneMapping{{AvailabilityZone: aws.String("us-east-1b")}}, + }) + require.NoError(t, err) + assert.Len(t, added.AvailabilityZoneMappings, 2) + + removed, err := s.c.DisassociateAvailabilityZones(bg, &networkfirewall.DisassociateAvailabilityZonesInput{ + FirewallName: aws.String("fw-tgw"), AvailabilityZoneMappings: []nftypes.AvailabilityZoneMapping{{AvailabilityZone: aws.String("us-east-1a")}}, + }) + require.NoError(t, err) + require.Len(t, removed.AvailabilityZoneMappings, 1) + assert.Equal(t, "us-east-1b", aws.ToString(removed.AvailabilityZoneMappings[0].AvailabilityZone)) +} + +func TestSDK_UpdateFirewallDescription(t *testing.T) { + s := newStack(t) + + set, err := s.c.UpdateFirewallDescription(bg, &networkfirewall.UpdateFirewallDescriptionInput{ + FirewallName: aws.String("fw-1"), Description: aws.String("edge"), UpdateToken: s.token(t), + }) + require.NoError(t, err) + assert.Equal(t, "edge", aws.ToString(set.Description)) + assert.Equal(t, s.fwARN, aws.ToString(set.FirewallArn)) + assert.Equal(t, "fw-1", aws.ToString(set.FirewallName)) + + cleared, err := s.c.UpdateFirewallDescription(bg, &networkfirewall.UpdateFirewallDescriptionInput{FirewallArn: aws.String(s.fwARN)}) + require.NoError(t, err) + assert.Empty(t, aws.ToString(cleared.Description)) + + d, _ := s.c.DescribeFirewall(bg, &networkfirewall.DescribeFirewallInput{FirewallName: aws.String("fw-1")}) + assert.Empty(t, aws.ToString(d.Firewall.Description)) +} + +func TestSDK_CreateFirewall_NoVpcId(t *testing.T) { + s := newStack(t) + + _, err := s.c.CreateFirewall(bg, &networkfirewall.CreateFirewallInput{ + FirewallName: aws.String("fw-novpc"), FirewallPolicyArn: aws.String(s.policyARN), + SubnetMappings: []nftypes.SubnetMapping{{SubnetId: aws.String("subnet-1")}}, + }) + + var invalid *nftypes.InvalidRequestException + require.ErrorAs(t, err, &invalid) +} + +func TestSDK_DeleteGuards_TypedErrors(t *testing.T) { + s := newStack(t) + + var invalidOp *nftypes.InvalidOperationException + + _, err := s.c.DeleteFirewallPolicy(bg, &networkfirewall.DeleteFirewallPolicyInput{FirewallPolicyName: aws.String("pol-1")}) + require.ErrorAs(t, err, &invalidOp, "policy in use by a firewall") + + _, err = s.c.UpdateFirewallDeleteProtection(bg, &networkfirewall.UpdateFirewallDeleteProtectionInput{FirewallName: aws.String("fw-1"), DeleteProtection: true}) + require.NoError(t, err) + + _, err = s.c.DeleteFirewall(bg, &networkfirewall.DeleteFirewallInput{FirewallName: aws.String("fw-1")}) + require.ErrorAs(t, err, &invalidOp, "delete protection") + + rg, err := s.c.CreateRuleGroup(bg, &networkfirewall.CreateRuleGroupInput{RuleGroupName: aws.String("rg-1"), Type: nftypes.RuleGroupTypeStateful, Capacity: aws.Int32(5)}) + require.NoError(t, err) + + _, err = s.c.CreateFirewallPolicy(bg, &networkfirewall.CreateFirewallPolicyInput{ + FirewallPolicyName: aws.String("pol-rg"), + FirewallPolicy: &nftypes.FirewallPolicy{ + StatelessDefaultActions: []string{"aws:pass"}, StatelessFragmentDefaultActions: []string{"aws:pass"}, + StatefulRuleGroupReferences: []nftypes.StatefulRuleGroupReference{{ResourceArn: rg.RuleGroupResponse.RuleGroupArn}}, + }, + }) + require.NoError(t, err) + + _, err = s.c.DeleteRuleGroup(bg, &networkfirewall.DeleteRuleGroupInput{RuleGroupName: aws.String("rg-1"), Type: nftypes.RuleGroupTypeStateful}) + require.ErrorAs(t, err, &invalidOp, "rule group referenced by a policy") +} + +func TestSDK_LoggingConfiguration_RoundTrip(t *testing.T) { + s := newStack(t) + + cfg := func(dests ...nftypes.LogDestinationConfig) *networkfirewall.UpdateLoggingConfigurationInput { + return &networkfirewall.UpdateLoggingConfigurationInput{ + FirewallName: aws.String("fw-1"), LoggingConfiguration: &nftypes.LoggingConfiguration{LogDestinationConfigs: dests}, + } + } + s3 := func(lt nftypes.LogType, bucket string) nftypes.LogDestinationConfig { + return nftypes.LogDestinationConfig{LogType: lt, LogDestinationType: nftypes.LogDestinationTypeS3, LogDestination: map[string]string{"bucketName": bucket}} + } + + var invalid *nftypes.InvalidRequestException + + _, err := s.c.UpdateLoggingConfiguration(bg, cfg(nftypes.LogDestinationConfig{ + LogType: nftypes.LogType("BOGUS"), LogDestinationType: nftypes.LogDestinationTypeS3, LogDestination: map[string]string{"bucketName": "b"}, + })) + require.ErrorAs(t, err, &invalid) + + _, err = s.c.UpdateLoggingConfiguration(bg, cfg(s3(nftypes.LogTypeFlow, "b1"))) + require.NoError(t, err) + + _, err = s.c.UpdateLoggingConfiguration(bg, cfg(s3(nftypes.LogTypeFlow, "b1"), s3(nftypes.LogTypeAlert, "b1"), s3(nftypes.LogTypeTls, "b1"))) + require.ErrorAs(t, err, &invalid, "two additions in one call") + + dash := true + in := cfg(s3(nftypes.LogTypeFlow, "b1"), s3(nftypes.LogTypeAlert, "b2")) + in.EnableMonitoringDashboard = &dash + + up, err := s.c.UpdateLoggingConfiguration(bg, in) + require.NoError(t, err) + assert.Len(t, up.LoggingConfiguration.LogDestinationConfigs, 2) + assert.True(t, aws.ToBool(up.EnableMonitoringDashboard)) + + d, err := s.c.DescribeLoggingConfiguration(bg, &networkfirewall.DescribeLoggingConfigurationInput{FirewallName: aws.String("fw-1")}) + require.NoError(t, err) + assert.Equal(t, up.LoggingConfiguration.LogDestinationConfigs, d.LoggingConfiguration.LogDestinationConfigs) + assert.True(t, aws.ToBool(d.EnableMonitoringDashboard)) + + // An omitted configuration disables logging. + _, err = s.c.UpdateLoggingConfiguration(bg, &networkfirewall.UpdateLoggingConfigurationInput{FirewallName: aws.String("fw-1")}) + require.ErrorAs(t, err, &invalid, "removing two destinations at once") +} + +func TestSDK_CreateRuleGroup_Capacity0(t *testing.T) { + c := newClient(t) + + _, err := c.CreateRuleGroup(bg, &networkfirewall.CreateRuleGroupInput{RuleGroupName: aws.String("rg"), Type: nftypes.RuleGroupTypeStateful, Capacity: aws.Int32(0)}) + + var invalid *nftypes.InvalidRequestException + require.ErrorAs(t, err, &invalid) + + _, err = c.CreateRuleGroup(bg, &networkfirewall.CreateRuleGroupInput{ + RuleGroupName: aws.String("rg"), Type: nftypes.RuleGroupTypeStateful, Capacity: aws.Int32(5), + RuleGroup: &nftypes.RuleGroup{RulesSource: &nftypes.RulesSource{RulesString: aws.String("pass tcp any any -> any any (sid:1;)")}}, + Rules: aws.String("pass tcp any any -> any any (sid:2;)"), + }) + require.ErrorAs(t, err, &invalid, "RuleGroup and Rules together") +} + +func TestSDK_DeleteRuleGroup_InUse(t *testing.T) { + TestSDK_DeleteGuards_TypedErrors(t) +} + +func TestSDK_ComputedFieldsDeserialize(t *testing.T) { + s := newStack(t) + + rg, err := s.c.CreateRuleGroup(bg, &networkfirewall.CreateRuleGroupInput{ + RuleGroupName: aws.String("rg-c"), Type: nftypes.RuleGroupTypeStateful, Capacity: aws.Int32(10), + Rules: aws.String("pass tcp any any -> any any (sid:1;)\npass udp any any -> any any (sid:2;)\n"), + }) + require.NoError(t, err) + assert.Equal(t, int32(2), aws.ToInt32(rg.RuleGroupResponse.ConsumedCapacity)) + assert.Equal(t, nftypes.ResourceStatusActive, rg.RuleGroupResponse.RuleGroupStatus) + assert.NotNil(t, rg.RuleGroupResponse.LastModifiedTime) + + pol, err := s.c.CreateFirewallPolicy(bg, &networkfirewall.CreateFirewallPolicyInput{ + FirewallPolicyName: aws.String("pol-c"), + FirewallPolicy: &nftypes.FirewallPolicy{ + StatelessDefaultActions: []string{"aws:pass"}, StatelessFragmentDefaultActions: []string{"aws:pass"}, + StatefulRuleGroupReferences: []nftypes.StatefulRuleGroupReference{{ResourceArn: rg.RuleGroupResponse.RuleGroupArn}}, + }, + }) + require.NoError(t, err) + assert.Equal(t, int32(10), aws.ToInt32(pol.FirewallPolicyResponse.ConsumedStatefulRuleCapacity)) + + d, err := s.c.DescribeFirewallPolicy(bg, &networkfirewall.DescribeFirewallPolicyInput{FirewallPolicyName: aws.String("pol-1")}) + require.NoError(t, err) + assert.Equal(t, int32(1), aws.ToInt32(d.FirewallPolicyResponse.NumberOfAssociations)) + assert.Equal(t, nftypes.ResourceStatusActive, d.FirewallPolicyResponse.FirewallPolicyStatus) + assert.NotNil(t, d.FirewallPolicyResponse.LastModifiedTime) + + rgd, err := s.c.DescribeRuleGroup(bg, &networkfirewall.DescribeRuleGroupInput{RuleGroupName: aws.String("rg-c"), Type: nftypes.RuleGroupTypeStateful}) + require.NoError(t, err) + assert.Equal(t, int32(1), aws.ToInt32(rgd.RuleGroupResponse.NumberOfAssociations)) +} + +func TestSDK_ResourcePolicy(t *testing.T) { + s := newStack(t) + + doc, _ := json.Marshal(map[string]any{ + "Version": "2012-10-17", + "Statement": []map[string]any{{ + "Effect": "Allow", "Principal": map[string]string{"AWS": "arn:aws:iam::111122223333:root"}, + "Action": []string{"network-firewall:AssociateFirewallPolicy"}, "Resource": s.policyARN, + }}, + }) + + _, err := s.c.PutResourcePolicy(bg, &networkfirewall.PutResourcePolicyInput{ResourceArn: aws.String(s.policyARN), Policy: aws.String(string(doc))}) + require.NoError(t, err) + + got, err := s.c.DescribeResourcePolicy(bg, &networkfirewall.DescribeResourcePolicyInput{ResourceArn: aws.String(s.policyARN)}) + require.NoError(t, err) + assert.JSONEq(t, string(doc), aws.ToString(got.Policy)) + + var badPolicy *nftypes.InvalidResourcePolicyException + + _, err = s.c.PutResourcePolicy(bg, &networkfirewall.PutResourcePolicyInput{ + ResourceArn: aws.String(s.policyARN), Policy: aws.String(`{"Statement":[{"Action":"network-firewall:ListFirewalls"}]}`), + }) + require.ErrorAs(t, err, &badPolicy) + + _, err = s.c.DeleteResourcePolicy(bg, &networkfirewall.DeleteResourcePolicyInput{ResourceArn: aws.String(s.policyARN)}) + require.NoError(t, err) + + var notFound *nftypes.ResourceNotFoundException + + _, err = s.c.DescribeResourcePolicy(bg, &networkfirewall.DescribeResourcePolicyInput{ResourceArn: aws.String(s.policyARN)}) + require.ErrorAs(t, err, ¬Found) +} + +func tlsConfig(certARN string) *nftypes.TLSInspectionConfiguration { + return &nftypes.TLSInspectionConfiguration{ + ServerCertificateConfigurations: []nftypes.ServerCertificateConfiguration{{ + ServerCertificates: []nftypes.ServerCertificate{{ResourceArn: aws.String(certARN)}}, + }}, + } +} + +func TestSDK_TLSInspection_RoundTrip(t *testing.T) { + c := newClient(t) + certARN := "arn:aws:acm:us-east-1:123456789012:certificate/c1" + + created, err := c.CreateTLSInspectionConfiguration(bg, &networkfirewall.CreateTLSInspectionConfigurationInput{ + TLSInspectionConfigurationName: aws.String("tls-1"), TLSInspectionConfiguration: tlsConfig(certARN), + Description: aws.String("d"), Tags: []nftypes.Tag{{Key: aws.String("k"), Value: aws.String("v")}}, + }) + require.NoError(t, err) + + resp := created.TLSInspectionConfigurationResponse + assert.Equal(t, nftypes.ResourceStatusActive, resp.TLSInspectionConfigurationStatus) + require.Len(t, resp.Certificates, 1) + assert.Equal(t, certARN, aws.ToString(resp.Certificates[0].CertificateArn)) + assert.NotNil(t, resp.LastModifiedTime) + + d, err := c.DescribeTLSInspectionConfiguration(bg, &networkfirewall.DescribeTLSInspectionConfigurationInput{TLSInspectionConfigurationArn: resp.TLSInspectionConfigurationArn}) + require.NoError(t, err) + assert.Equal(t, aws.ToString(created.UpdateToken), aws.ToString(d.UpdateToken)) + require.NotNil(t, d.TLSInspectionConfiguration) + assert.Len(t, d.TLSInspectionConfiguration.ServerCertificateConfigurations, 1) + + _, err = c.UpdateTLSInspectionConfiguration(bg, &networkfirewall.UpdateTLSInspectionConfigurationInput{ + TLSInspectionConfigurationName: aws.String("tls-1"), TLSInspectionConfiguration: tlsConfig(certARN), UpdateToken: aws.String("11111111-1111-1111-1111-111111111111"), + }) + + var invalidToken *nftypes.InvalidTokenException + require.ErrorAs(t, err, &invalidToken) + + up, err := c.UpdateTLSInspectionConfiguration(bg, &networkfirewall.UpdateTLSInspectionConfigurationInput{ + TLSInspectionConfigurationName: aws.String("tls-1"), TLSInspectionConfiguration: tlsConfig("arn:aws:acm:us-east-1:123456789012:certificate/c2"), + UpdateToken: d.UpdateToken, Description: aws.String("d2"), + }) + require.NoError(t, err) + assert.Equal(t, "d2", aws.ToString(up.TLSInspectionConfigurationResponse.Description)) + + list, err := c.ListTLSInspectionConfigurations(bg, &networkfirewall.ListTLSInspectionConfigurationsInput{}) + require.NoError(t, err) + require.Len(t, list.TLSInspectionConfigurations, 1) + + _, err = c.DeleteTLSInspectionConfiguration(bg, &networkfirewall.DeleteTLSInspectionConfigurationInput{TLSInspectionConfigurationName: aws.String("tls-1")}) + require.NoError(t, err) +} + +func TestSDK_VPCEndpointAssociation_RoundTrip(t *testing.T) { + s := newStack(t) + + created, err := s.c.CreateVpcEndpointAssociation(bg, &networkfirewall.CreateVpcEndpointAssociationInput{ + FirewallArn: aws.String(s.fwARN), VpcId: aws.String("vpc-2b"), SubnetMapping: &nftypes.SubnetMapping{SubnetId: aws.String("subnet-9")}, + Description: aws.String("extra"), Tags: []nftypes.Tag{{Key: aws.String("k"), Value: aws.String("v")}}, + }) + require.NoError(t, err) + + arn := aws.ToString(created.VpcEndpointAssociation.VpcEndpointAssociationArn) + assert.Equal(t, nftypes.FirewallStatusValueReady, created.VpcEndpointAssociationStatus.Status) + assert.NotEmpty(t, created.VpcEndpointAssociationStatus.AssociationSyncState) + + d, err := s.c.DescribeVpcEndpointAssociation(bg, &networkfirewall.DescribeVpcEndpointAssociationInput{VpcEndpointAssociationArn: aws.String(arn)}) + require.NoError(t, err) + assert.Equal(t, "subnet-9", aws.ToString(d.VpcEndpointAssociation.SubnetMapping.SubnetId)) + + list, err := s.c.ListVpcEndpointAssociations(bg, &networkfirewall.ListVpcEndpointAssociationsInput{FirewallArn: aws.String(s.fwARN)}) + require.NoError(t, err) + assert.Len(t, list.VpcEndpointAssociations, 1) + + tags, err := s.c.ListTagsForResource(bg, &networkfirewall.ListTagsForResourceInput{ResourceArn: aws.String(arn)}) + require.NoError(t, err) + assert.Len(t, tags.Tags, 1) + + fwd, _ := s.c.DescribeFirewall(bg, &networkfirewall.DescribeFirewallInput{FirewallName: aws.String("fw-1")}) + assert.Equal(t, int32(1), aws.ToInt32(fwd.Firewall.NumberOfAssociations)) + + var invalidOp *nftypes.InvalidOperationException + + _, err = s.c.DeleteFirewall(bg, &networkfirewall.DeleteFirewallInput{FirewallName: aws.String("fw-1")}) + require.ErrorAs(t, err, &invalidOp, "firewall with associations") + + _, err = s.c.DeleteVpcEndpointAssociation(bg, &networkfirewall.DeleteVpcEndpointAssociationInput{VpcEndpointAssociationArn: aws.String(arn)}) + require.NoError(t, err) + + var notFound *nftypes.ResourceNotFoundException + + _, err = s.c.DescribeVpcEndpointAssociation(bg, &networkfirewall.DescribeVpcEndpointAssociationInput{VpcEndpointAssociationArn: aws.String(arn)}) + require.ErrorAs(t, err, ¬Found) +} + +func TestSDK_Metadata_Ops(t *testing.T) { + s := newStack(t) + + rg, err := s.c.CreateRuleGroup(bg, &networkfirewall.CreateRuleGroupInput{ + RuleGroupName: aws.String("rg-m"), Type: nftypes.RuleGroupTypeStateful, Capacity: aws.Int32(10), + Rules: aws.String(`alert tcp any any -> any 80 (msg:"web"; sid:7;)`), + SummaryConfiguration: &nftypes.SummaryConfiguration{RuleOptions: []nftypes.SummaryRuleOption{nftypes.SummaryRuleOptionMsg, nftypes.SummaryRuleOptionSid}}, + }) + require.NoError(t, err) + + fm, err := s.c.DescribeFirewallMetadata(bg, &networkfirewall.DescribeFirewallMetadataInput{FirewallArn: aws.String(s.fwARN)}) + require.NoError(t, err) + assert.Equal(t, s.policyARN, aws.ToString(fm.FirewallPolicyArn)) + assert.Equal(t, nftypes.FirewallStatusValueReady, fm.Status) + assert.Contains(t, fm.SupportedAvailabilityZones, "us-east-1a") + + rm, err := s.c.DescribeRuleGroupMetadata(bg, &networkfirewall.DescribeRuleGroupMetadataInput{RuleGroupArn: rg.RuleGroupResponse.RuleGroupArn}) + require.NoError(t, err) + assert.Equal(t, int32(10), aws.ToInt32(rm.Capacity)) + assert.Equal(t, nftypes.RuleGroupTypeStateful, rm.Type) + + sum, err := s.c.DescribeRuleGroupSummary(bg, &networkfirewall.DescribeRuleGroupSummaryInput{RuleGroupName: aws.String("rg-m"), Type: nftypes.RuleGroupTypeStateful}) + require.NoError(t, err) + require.Len(t, sum.Summary.RuleSummaries, 1) + assert.Equal(t, "web", aws.ToString(sum.Summary.RuleSummaries[0].Msg)) + assert.Equal(t, "7", aws.ToString(sum.Summary.RuleSummaries[0].SID)) +} + +func TestSDK_FlowAndAnalysis_Ops(t *testing.T) { + s := newStack(t) + + _, err := s.c.UpdateFirewallAnalysisSettings(bg, &networkfirewall.UpdateFirewallAnalysisSettingsInput{ + FirewallName: aws.String("fw-1"), EnabledAnalysisTypes: []nftypes.EnabledAnalysisType{nftypes.EnabledAnalysisTypeTlsSni}, + }) + require.NoError(t, err) + + capture, err := s.c.StartFlowCapture(bg, &networkfirewall.StartFlowCaptureInput{FirewallArn: aws.String(s.fwARN), AvailabilityZone: aws.String("us-east-1a"), FlowFilters: []nftypes.FlowFilter{{SourcePort: aws.String("80")}}}) + require.NoError(t, err) + assert.Equal(t, nftypes.FlowOperationStatusCompleted, capture.FlowOperationStatus) + + flush, err := s.c.StartFlowFlush(bg, &networkfirewall.StartFlowFlushInput{FirewallArn: aws.String(s.fwARN), AvailabilityZone: aws.String("us-east-1a"), FlowFilters: []nftypes.FlowFilter{{SourcePort: aws.String("80")}}}) + require.NoError(t, err) + + d, err := s.c.DescribeFlowOperation(bg, &networkfirewall.DescribeFlowOperationInput{ + FirewallArn: aws.String(s.fwARN), AvailabilityZone: aws.String("us-east-1a"), FlowOperationId: capture.FlowOperationId, + }) + require.NoError(t, err) + assert.Equal(t, nftypes.FlowOperationTypeFlowCapture, d.FlowOperationType) + assert.NotNil(t, d.FlowRequestTimestamp) + + ops, err := s.c.ListFlowOperations(bg, &networkfirewall.ListFlowOperationsInput{ + FirewallArn: aws.String(s.fwARN), AvailabilityZone: aws.String("us-east-1a"), FlowOperationType: nftypes.FlowOperationTypeFlowFlush, + }) + require.NoError(t, err) + require.Len(t, ops.FlowOperations, 1) + assert.Equal(t, aws.ToString(flush.FlowOperationId), aws.ToString(ops.FlowOperations[0].FlowOperationId)) + + res, err := s.c.ListFlowOperationResults(bg, &networkfirewall.ListFlowOperationResultsInput{ + FirewallArn: aws.String(s.fwARN), AvailabilityZone: aws.String("us-east-1a"), FlowOperationId: capture.FlowOperationId, + }) + require.NoError(t, err) + assert.Empty(t, res.Flows, "no data plane, no flows") + + started, err := s.c.StartAnalysisReport(bg, &networkfirewall.StartAnalysisReportInput{FirewallName: aws.String("fw-1"), AnalysisType: nftypes.EnabledAnalysisTypeTlsSni}) + require.NoError(t, err) + + reports, err := s.c.ListAnalysisReports(bg, &networkfirewall.ListAnalysisReportsInput{FirewallArn: aws.String(s.fwARN)}) + require.NoError(t, err) + require.Len(t, reports.AnalysisReports, 1) + assert.Equal(t, nftypes.EnabledAnalysisTypeTlsSni, reports.AnalysisReports[0].AnalysisType) + + got, err := s.c.GetAnalysisReportResults(bg, &networkfirewall.GetAnalysisReportResultsInput{FirewallName: aws.String("fw-1"), AnalysisReportId: started.AnalysisReportId}) + require.NoError(t, err) + assert.Equal(t, nftypes.EnabledAnalysisTypeTlsSni, got.AnalysisType) + assert.Empty(t, got.AnalysisReportResults) + + var invalid *nftypes.InvalidRequestException + + _, err = s.c.StartAnalysisReport(bg, &networkfirewall.StartAnalysisReportInput{FirewallName: aws.String("fw-1"), AnalysisType: nftypes.EnabledAnalysisTypeHttpHost}) + require.ErrorAs(t, err, &invalid, "HTTP_HOST analysis is not enabled") +} + +func TestSDK_Pagination_Paginators(t *testing.T) { + s := newStack(t) + + for i := 2; i <= 4; i++ { + _, err := s.c.CreateFirewall(bg, &networkfirewall.CreateFirewallInput{ + FirewallName: aws.String(fmt.Sprintf("fw-%d", i)), FirewallPolicyArn: aws.String(s.policyARN), VpcId: aws.String(fmt.Sprintf("vpc-%da", i)), + }) + require.NoError(t, err) + } + + pager := networkfirewall.NewListFirewallsPaginator(s.c, &networkfirewall.ListFirewallsInput{MaxResults: aws.Int32(1)}) + + var names []string + + for pager.HasMorePages() { + page, err := pager.NextPage(bg) + require.NoError(t, err) + require.Len(t, page.Firewalls, 1) + + names = append(names, aws.ToString(page.Firewalls[0].FirewallName)) + } + + assert.Equal(t, []string{"fw-1", "fw-2", "fw-3", "fw-4"}, names) + + filtered, err := s.c.ListFirewalls(bg, &networkfirewall.ListFirewallsInput{VpcIds: []string{"vpc-3a"}}) + require.NoError(t, err) + require.Len(t, filtered.Firewalls, 1) + assert.Equal(t, "fw-3", aws.ToString(filtered.Firewalls[0].FirewallName)) + + var invalid *nftypes.InvalidRequestException + + _, err = s.c.ListFirewalls(bg, &networkfirewall.ListFirewallsInput{NextToken: aws.String("zzz!")}) + require.ErrorAs(t, err, &invalid) + + _, err = s.c.ListFirewallPolicies(bg, &networkfirewall.ListFirewallPoliciesInput{MaxResults: aws.Int32(101)}) + require.ErrorAs(t, err, &invalid) + + pols := networkfirewall.NewListFirewallPoliciesPaginator(s.c, &networkfirewall.ListFirewallPoliciesInput{MaxResults: aws.Int32(1)}) + + seen := 0 + + for pols.HasMorePages() { + page, err := pols.NextPage(bg) + require.NoError(t, err) + + seen += len(page.FirewallPolicies) + } + + assert.Equal(t, 1, seen) +} + +func TestSDK_Policy_FullRoundTrip(t *testing.T) { + c := newClient(t) + + tls, err := c.CreateTLSInspectionConfiguration(bg, &networkfirewall.CreateTLSInspectionConfigurationInput{ + TLSInspectionConfigurationName: aws.String("tls-p"), TLSInspectionConfiguration: tlsConfig("arn:aws:acm:us-east-1:123456789012:certificate/c1"), + }) + require.NoError(t, err) + + _, err = c.CreateFirewallPolicy(bg, &networkfirewall.CreateFirewallPolicyInput{ + FirewallPolicyName: aws.String("pol-full"), + FirewallPolicy: &nftypes.FirewallPolicy{ + StatelessDefaultActions: []string{"aws:pass", "mine"}, + StatelessFragmentDefaultActions: []string{"aws:drop"}, + StatelessCustomActions: []nftypes.CustomAction{{ + ActionName: aws.String("mine"), + ActionDefinition: &nftypes.ActionDefinition{PublishMetricAction: &nftypes.PublishMetricAction{ + Dimensions: []nftypes.Dimension{{Value: aws.String("v")}}, + }}, + }}, + StatefulDefaultActions: []string{"aws:drop_strict"}, + StatefulEngineOptions: &nftypes.StatefulEngineOptions{RuleOrder: nftypes.RuleOrderStrictOrder}, + PolicyVariables: &nftypes.PolicyVariables{RuleVariables: map[string]nftypes.IPSet{"HOME_NET": {Definition: []string{"10.0.0.0/8"}}}}, + TLSInspectionConfigurationArn: tls.TLSInspectionConfigurationResponse.TLSInspectionConfigurationArn, + EnableTLSSessionHolding: aws.Bool(true), + }, + }) + require.NoError(t, err) + + d, err := c.DescribeFirewallPolicy(bg, &networkfirewall.DescribeFirewallPolicyInput{FirewallPolicyName: aws.String("pol-full")}) + require.NoError(t, err) + + p := d.FirewallPolicy + assert.Equal(t, []string{"aws:pass", "mine"}, p.StatelessDefaultActions) + assert.Equal(t, []string{"aws:drop_strict"}, p.StatefulDefaultActions) + assert.Equal(t, nftypes.RuleOrderStrictOrder, p.StatefulEngineOptions.RuleOrder) + require.Len(t, p.StatelessCustomActions, 1) + assert.Equal(t, "mine", aws.ToString(p.StatelessCustomActions[0].ActionName)) + assert.Equal(t, []string{"10.0.0.0/8"}, p.PolicyVariables.RuleVariables["HOME_NET"].Definition) + assert.True(t, aws.ToBool(p.EnableTLSSessionHolding)) + assert.Equal(t, aws.ToString(tls.TLSInspectionConfigurationResponse.TLSInspectionConfigurationArn), aws.ToString(p.TLSInspectionConfigurationArn)) + + var invalid *nftypes.InvalidRequestException + + _, err = c.CreateFirewallPolicy(bg, &networkfirewall.CreateFirewallPolicyInput{ + FirewallPolicyName: aws.String("pol-bad"), + FirewallPolicy: &nftypes.FirewallPolicy{ + StatelessDefaultActions: []string{"aws:nope"}, StatelessFragmentDefaultActions: []string{"aws:drop"}, + }, + }) + require.ErrorAs(t, err, &invalid) +} + +func TestSDK_ListRuleGroups_FiltersAndTags(t *testing.T) { + s := newStack(t) + + for _, rg := range []struct { + name string + typ nftypes.RuleGroupType + }{{"rg-a", nftypes.RuleGroupTypeStateless}, {"rg-b", nftypes.RuleGroupTypeStateful}} { + _, err := s.c.CreateRuleGroup(bg, &networkfirewall.CreateRuleGroupInput{RuleGroupName: aws.String(rg.name), Type: rg.typ, Capacity: aws.Int32(3)}) + require.NoError(t, err) + } + + all, err := s.c.ListRuleGroups(bg, &networkfirewall.ListRuleGroupsInput{}) + require.NoError(t, err) + assert.Len(t, all.RuleGroups, 2) + + stateless, err := s.c.ListRuleGroups(bg, &networkfirewall.ListRuleGroupsInput{Type: nftypes.RuleGroupTypeStateless}) + require.NoError(t, err) + require.Len(t, stateless.RuleGroups, 1) + assert.Equal(t, "rg-a", aws.ToString(stateless.RuleGroups[0].Name)) + + managed, err := s.c.ListRuleGroups(bg, &networkfirewall.ListRuleGroupsInput{Scope: nftypes.ResourceManagedStatusManaged}) + require.NoError(t, err) + assert.Empty(t, managed.RuleGroups) + + // Tags work on every resource kind, addressed by ARN. + for _, arn := range []string{s.policyARN, s.fwARN, aws.ToString(all.RuleGroups[0].Arn)} { + _, err := s.c.TagResource(bg, &networkfirewall.TagResourceInput{ResourceArn: aws.String(arn), Tags: []nftypes.Tag{{Key: aws.String("k"), Value: aws.String("v")}}}) + require.NoError(t, err) + + got, err := s.c.ListTagsForResource(bg, &networkfirewall.ListTagsForResourceInput{ResourceArn: aws.String(arn)}) + require.NoError(t, err) + assert.Len(t, got.Tags, 1) + } + + fw, err := s.c.DescribeFirewall(bg, &networkfirewall.DescribeFirewallInput{FirewallName: aws.String("fw-1")}) + require.NoError(t, err) + assert.Len(t, fw.Firewall.Tags, 1) +} + +func TestSDK_DescribeByARN_And_Deletes(t *testing.T) { + s := newStack(t) + + rg, err := s.c.CreateRuleGroup(bg, &networkfirewall.CreateRuleGroupInput{RuleGroupName: aws.String("rg"), Type: nftypes.RuleGroupTypeStateful, Capacity: aws.Int32(3)}) + require.NoError(t, err) + + byARN, err := s.c.DescribeRuleGroup(bg, &networkfirewall.DescribeRuleGroupInput{RuleGroupArn: rg.RuleGroupResponse.RuleGroupArn}) + require.NoError(t, err) + assert.Equal(t, "rg", aws.ToString(byARN.RuleGroupResponse.RuleGroupName)) + + _, err = s.c.DeleteRuleGroup(bg, &networkfirewall.DeleteRuleGroupInput{RuleGroupArn: rg.RuleGroupResponse.RuleGroupArn}) + require.NoError(t, err) + + var notFound *nftypes.ResourceNotFoundException + + _, err = s.c.DescribeRuleGroup(bg, &networkfirewall.DescribeRuleGroupInput{RuleGroupArn: rg.RuleGroupResponse.RuleGroupArn}) + require.ErrorAs(t, err, ¬Found) + + _, err = s.c.DeleteFirewall(bg, &networkfirewall.DeleteFirewallInput{FirewallArn: aws.String(s.fwARN)}) + require.NoError(t, err) + + _, err = s.c.DeleteFirewallPolicy(bg, &networkfirewall.DeleteFirewallPolicyInput{FirewallPolicyArn: aws.String(s.policyARN)}) + require.NoError(t, err) + + var invalid *nftypes.InvalidRequestException + + _, err = s.c.DescribeFirewall(bg, &networkfirewall.DescribeFirewallInput{FirewallArn: aws.String("not-an-arn")}) + require.ErrorAs(t, err, &invalid) + + _, err = s.c.CreateRuleGroup(bg, &networkfirewall.CreateRuleGroupInput{RuleGroupName: aws.String("dup"), Type: nftypes.RuleGroupTypeStateful, Capacity: aws.Int32(1)}) + require.NoError(t, err) + + _, err = s.c.CreateRuleGroup(bg, &networkfirewall.CreateRuleGroupInput{RuleGroupName: aws.String("dup"), Type: nftypes.RuleGroupTypeStateful, Capacity: aws.Int32(1)}) + require.ErrorAs(t, err, &invalid, "a duplicate name is InvalidRequestException") +} diff --git a/server/aws/networkfirewall/sdk_roundtrip_test.go b/server/aws/networkfirewall/sdk_roundtrip_test.go index 9f41b5d19..82299f0e2 100644 --- a/server/aws/networkfirewall/sdk_roundtrip_test.go +++ b/server/aws/networkfirewall/sdk_roundtrip_test.go @@ -36,6 +36,26 @@ func newClient(t *testing.T) *networkfirewall.Client { }) } +// policyToken reads the current update token of a firewall policy. +func policyToken(t *testing.T, c *networkfirewall.Client, name string) *string { + t.Helper() + + d, err := c.DescribeFirewallPolicy(context.Background(), &networkfirewall.DescribeFirewallPolicyInput{FirewallPolicyName: aws.String(name)}) + require.NoError(t, err) + + return d.UpdateToken +} + +// ruleGroupToken reads the current update token of a rule group. +func ruleGroupToken(t *testing.T, c *networkfirewall.Client, name string, typ nftypes.RuleGroupType) *string { + t.Helper() + + d, err := c.DescribeRuleGroup(context.Background(), &networkfirewall.DescribeRuleGroupInput{RuleGroupName: aws.String(name), Type: typ}) + require.NoError(t, err) + + return d.UpdateToken +} + func TestSDKNetworkFirewall(t *testing.T) { client := newClient(t) ctx := context.Background() @@ -222,7 +242,7 @@ func TestSDKUpdateFirewallPolicy(t *testing.T) { _, err = client.UpdateFirewallPolicy(ctx, &networkfirewall.UpdateFirewallPolicyInput{ FirewallPolicyName: aws.String("pol-upd"), - UpdateToken: aws.String("00000000-0000-0000-0000-000000000000"), + UpdateToken: policyToken(t, client, "pol-upd"), Description: aws.String("updated"), FirewallPolicy: &nftypes.FirewallPolicy{ StatelessDefaultActions: []string{"aws:drop"}, @@ -256,7 +276,7 @@ func TestSDKUpdateRuleGroup(t *testing.T) { _, err = client.UpdateRuleGroup(ctx, &networkfirewall.UpdateRuleGroupInput{ RuleGroupName: aws.String("rg-upd"), Type: nftypes.RuleGroupTypeStateful, - UpdateToken: aws.String("00000000-0000-0000-0000-000000000000"), + UpdateToken: ruleGroupToken(t, client, "rg-upd", nftypes.RuleGroupTypeStateful), Description: aws.String("after"), }) require.NoError(t, err) @@ -338,7 +358,7 @@ func TestSDKCreateRuleGroupWithRules(t *testing.T) { _, err = client.UpdateRuleGroup(ctx, &networkfirewall.UpdateRuleGroupInput{ RuleGroupName: aws.String("rg-stateful"), Type: nftypes.RuleGroupTypeStateful, - UpdateToken: aws.String("00000000-0000-0000-0000-000000000000"), + UpdateToken: ruleGroupToken(t, client, "rg-stateful", nftypes.RuleGroupTypeStateful), RuleGroup: &nftypes.RuleGroup{ RulesSource: &nftypes.RulesSource{ RulesString: aws.String(`drop tcp any any -> any any (msg:"blocked"; sid:2;)`), @@ -407,7 +427,7 @@ func TestSDKFirewallPolicyRuleGroupReferences(t *testing.T) { // UpdateFirewallPolicy with a different reference set round-trips too. _, err = client.UpdateFirewallPolicy(ctx, &networkfirewall.UpdateFirewallPolicyInput{ FirewallPolicyName: aws.String("pol-refs"), - UpdateToken: aws.String("00000000-0000-0000-0000-000000000000"), + UpdateToken: policyToken(t, client, "pol-refs"), FirewallPolicy: &nftypes.FirewallPolicy{ StatelessDefaultActions: []string{"aws:forward_to_sfe"}, StatelessFragmentDefaultActions: []string{"aws:forward_to_sfe"}, diff --git a/server/aws/networkfirewall/tls_inspection.go b/server/aws/networkfirewall/tls_inspection.go new file mode 100644 index 000000000..b819f6b5b --- /dev/null +++ b/server/aws/networkfirewall/tls_inspection.go @@ -0,0 +1,181 @@ +package networkfirewall + +import ( + "encoding/json" + "net/http" + + "github.com/stackshy/cloudemu/v2/server/wire" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +type certificateJSON struct { + CertificateArn string `json:"CertificateArn"` +} + +type tlsResponseJSON struct { + TLSInspectionConfigurationName string `json:"TLSInspectionConfigurationName"` + TLSInspectionConfigurationArn string `json:"TLSInspectionConfigurationArn"` + TLSInspectionConfigurationID string `json:"TLSInspectionConfigurationId"` + TLSInspectionConfigurationStatus string `json:"TLSInspectionConfigurationStatus,omitempty"` + Description string `json:"Description,omitempty"` + NumberOfAssociations int `json:"NumberOfAssociations"` + LastModifiedTime *float64 `json:"LastModifiedTime,omitempty"` + Certificates []certificateJSON `json:"Certificates,omitempty"` + Tags []tag `json:"Tags,omitempty"` +} + +type createTLSRequest struct { + TLSInspectionConfigurationName string `json:"TLSInspectionConfigurationName"` + TLSInspectionConfiguration json.RawMessage `json:"TLSInspectionConfiguration"` + Description string `json:"Description"` + Tags []tag `json:"Tags"` +} + +type tlsNameArnRequest struct { + TLSInspectionConfigurationName string `json:"TLSInspectionConfigurationName"` + TLSInspectionConfigurationArn string `json:"TLSInspectionConfigurationArn"` +} + +type updateTLSRequest struct { + tlsNameArnRequest + UpdateToken string `json:"UpdateToken"` + TLSInspectionConfiguration json.RawMessage `json:"TLSInspectionConfiguration"` + Description string `json:"Description"` +} + +func toTLSResponseJSON(t *nfdriver.TLSInspectionConfig) tlsResponseJSON { + modified := epochSeconds(t.LastModified) + + certs := make([]certificateJSON, 0, len(t.CertificateARNs)) + for _, arn := range t.CertificateARNs { + certs = append(certs, certificateJSON{CertificateArn: arn}) + } + + return tlsResponseJSON{ + TLSInspectionConfigurationName: t.Name, TLSInspectionConfigurationArn: t.ARN, + TLSInspectionConfigurationID: t.ID, TLSInspectionConfigurationStatus: t.Status, + Description: t.Description, NumberOfAssociations: t.NumberOfAssociations, + LastModifiedTime: &modified, Certificates: certs, Tags: mapToTags(t.Tags), + } +} + +func (h *Handler) createTLSInspectionConfiguration(w http.ResponseWriter, r *http.Request) { + var req createTLSRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + tls, ok := capability[nfdriver.TLSInspection](h, w) + if !ok { + return + } + + t, err := tls.CreateTLSInspectionConfiguration(r.Context(), nfdriver.CreateTLSInspectionConfig{ + Name: req.TLSInspectionConfigurationName, Description: req.Description, + Configuration: req.TLSInspectionConfiguration, Tags: tagsToMap(req.Tags), + }) + if err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{ + "UpdateToken": t.UpdateToken, + "TLSInspectionConfigurationResponse": toTLSResponseJSON(t), + }) +} + +func (h *Handler) describeTLSInspectionConfiguration(w http.ResponseWriter, r *http.Request) { + var req tlsNameArnRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + tls, ok := capability[nfdriver.TLSInspection](h, w) + if !ok { + return + } + + t, err := tls.DescribeTLSInspectionConfiguration(r.Context(), req.TLSInspectionConfigurationName, req.TLSInspectionConfigurationArn) + if err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{ + "UpdateToken": t.UpdateToken, + "TLSInspectionConfigurationResponse": toTLSResponseJSON(t), + "TLSInspectionConfiguration": t.Configuration, + }) +} + +func (h *Handler) updateTLSInspectionConfiguration(w http.ResponseWriter, r *http.Request) { + var req updateTLSRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + tls, ok := capability[nfdriver.TLSInspection](h, w) + if !ok { + return + } + + t, err := tls.UpdateTLSInspectionConfiguration(r.Context(), req.TLSInspectionConfigurationName, req.TLSInspectionConfigurationArn, + nfdriver.UpdateTLSInspectionConfig{ + UpdateToken: req.UpdateToken, Description: req.Description, Configuration: req.TLSInspectionConfiguration, + }) + if err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{ + "UpdateToken": t.UpdateToken, + "TLSInspectionConfigurationResponse": toTLSResponseJSON(t), + }) +} + +func (h *Handler) deleteTLSInspectionConfiguration(w http.ResponseWriter, r *http.Request) { + var req tlsNameArnRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + tls, ok := capability[nfdriver.TLSInspection](h, w) + if !ok { + return + } + + t, err := tls.DeleteTLSInspectionConfiguration(r.Context(), req.TLSInspectionConfigurationName, req.TLSInspectionConfigurationArn) + if err != nil { + writeErr(w, err) + return + } + + wire.WriteJSON(w, map[string]any{"TLSInspectionConfigurationResponse": toTLSResponseJSON(t)}) +} + +func (h *Handler) listTLSInspectionConfigurations(w http.ResponseWriter, r *http.Request) { + var req listRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + tls, ok := capability[nfdriver.TLSInspection](h, w) + if !ok { + return + } + + items, next, err := tls.ListTLSInspectionConfigurations(r.Context(), req.options()) + if err != nil { + writeErr(w, err) + return + } + + metas := make([]map[string]string, 0, len(items)) + for i := range items { + metas = append(metas, map[string]string{"Name": items[i].Name, "Arn": items[i].ARN}) + } + + wire.WriteJSON(w, withNextToken(map[string]any{"TLSInspectionConfigurations": metas}, next)) +} diff --git a/server/aws/networkfirewall/vpc_endpoint_association.go b/server/aws/networkfirewall/vpc_endpoint_association.go new file mode 100644 index 000000000..66bd58e74 --- /dev/null +++ b/server/aws/networkfirewall/vpc_endpoint_association.go @@ -0,0 +1,156 @@ +package networkfirewall + +import ( + "net/http" + + "github.com/stackshy/cloudemu/v2/server/wire" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +type vpcEndpointAssociationJSON struct { + VpcEndpointAssociationArn string `json:"VpcEndpointAssociationArn"` + VpcEndpointAssociationID string `json:"VpcEndpointAssociationId"` + FirewallArn string `json:"FirewallArn"` + VpcID string `json:"VpcId"` + SubnetMapping *subnetMapping `json:"SubnetMapping,omitempty"` + Description string `json:"Description,omitempty"` + Tags []tag `json:"Tags,omitempty"` +} + +type associationStatusJSON struct { + Status string `json:"Status"` + AssociationSyncState map[string]syncStateJSON `json:"AssociationSyncState,omitempty"` +} + +func toAssociationJSON(a *nfdriver.VPCEndpointAssociation) vpcEndpointAssociationJSON { + return vpcEndpointAssociationJSON{ + VpcEndpointAssociationArn: a.ARN, VpcEndpointAssociationID: a.ID, FirewallArn: a.FirewallARN, VpcID: a.VPCID, + SubnetMapping: &subnetMapping{SubnetID: a.SubnetID, IPAddressType: a.IPAddressType}, + Description: a.Description, Tags: mapToTags(a.Tags), + } +} + +func toAssociationStatusJSON(a *nfdriver.VPCEndpointAssociation) associationStatusJSON { + return associationStatusJSON{ + Status: a.Status, + AssociationSyncState: map[string]syncStateJSON{ + a.AvailabilityZone: {Attachment: attachmentJSON{SubnetID: a.SubnetID, EndpointID: "vpce-" + a.ID, Status: "READY"}}, + }, + } +} + +func writeAssociation(w http.ResponseWriter, a *nfdriver.VPCEndpointAssociation) { + wire.WriteJSON(w, map[string]any{ + "VpcEndpointAssociation": toAssociationJSON(a), + "VpcEndpointAssociationStatus": toAssociationStatusJSON(a), + }) +} + +type createAssociationRequest struct { + FirewallArn string `json:"FirewallArn"` + VpcID string `json:"VpcId"` + SubnetMapping *subnetMapping `json:"SubnetMapping"` + Description string `json:"Description"` + Tags []tag `json:"Tags"` +} + +func (h *Handler) createVpcEndpointAssociation(w http.ResponseWriter, r *http.Request) { + var req createAssociationRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + assoc, ok := capability[nfdriver.VPCEndpointAssociations](h, w) + if !ok { + return + } + + cfg := nfdriver.CreateVPCEndpointAssociationConfig{ + FirewallARN: req.FirewallArn, VPCID: req.VpcID, Description: req.Description, Tags: tagsToMap(req.Tags), + } + if req.SubnetMapping != nil { + cfg.SubnetID, cfg.IPAddressType = req.SubnetMapping.SubnetID, req.SubnetMapping.IPAddressType + } + + a, err := assoc.CreateVpcEndpointAssociation(r.Context(), cfg) + if err != nil { + writeErr(w, err) + return + } + + writeAssociation(w, a) +} + +type associationArnRequest struct { + VpcEndpointAssociationArn string `json:"VpcEndpointAssociationArn"` +} + +func (h *Handler) describeVpcEndpointAssociation(w http.ResponseWriter, r *http.Request) { + var req associationArnRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + assoc, ok := capability[nfdriver.VPCEndpointAssociations](h, w) + if !ok { + return + } + + a, err := assoc.DescribeVpcEndpointAssociation(r.Context(), req.VpcEndpointAssociationArn) + if err != nil { + writeErr(w, err) + return + } + + writeAssociation(w, a) +} + +func (h *Handler) deleteVpcEndpointAssociation(w http.ResponseWriter, r *http.Request) { + var req associationArnRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + assoc, ok := capability[nfdriver.VPCEndpointAssociations](h, w) + if !ok { + return + } + + a, err := assoc.DeleteVpcEndpointAssociation(r.Context(), req.VpcEndpointAssociationArn) + if err != nil { + writeErr(w, err) + return + } + + writeAssociation(w, a) +} + +type listAssociationsRequest struct { + listRequest + FirewallArn string `json:"FirewallArn"` +} + +func (h *Handler) listVpcEndpointAssociations(w http.ResponseWriter, r *http.Request) { + var req listAssociationsRequest + if !wire.DecodeJSON(w, r, &req) { + return + } + + assoc, ok := capability[nfdriver.VPCEndpointAssociations](h, w) + if !ok { + return + } + + items, next, err := assoc.ListVpcEndpointAssociations(r.Context(), req.FirewallArn, req.options()) + if err != nil { + writeErr(w, err) + return + } + + metas := make([]map[string]string, 0, len(items)) + for i := range items { + metas = append(metas, map[string]string{"VpcEndpointAssociationArn": items[i].ARN}) + } + + wire.WriteJSON(w, withNextToken(map[string]any{"VpcEndpointAssociations": metas}, next)) +} diff --git a/services/networkfirewall/driver/availability_zones.go b/services/networkfirewall/driver/availability_zones.go new file mode 100644 index 000000000..71870263e --- /dev/null +++ b/services/networkfirewall/driver/availability_zones.go @@ -0,0 +1,43 @@ +package driver + +import "hash/fnv" + +// azLetters are the zone suffixes used to give a firewall's subnets stable, +// synthetic Availability Zone names (the emulator has no real subnet to AZ +// mapping). +const azLetters = "abcdef" + +// AvailabilityZoneFor returns the synthetic Availability Zone name for the +// index-th subnet of a firewall in region (index 0 -> "a"). +func AvailabilityZoneFor(region string, index int) string { + if index < 0 { + index = -index + } + + return region + string(azLetters[index%len(azLetters)]) +} + +// SyncZones returns the Availability Zones a firewall runs in: its explicit +// zones for a transit gateway-attached firewall, else one synthetic zone per +// subnet. +func SyncZones(f *Firewall, region string) []string { + if len(f.AvailabilityZones) > 0 { + return append([]string(nil), f.AvailabilityZones...) + } + + zones := make([]string, 0, len(f.SubnetIDs)) + for i := range f.SubnetIDs { + zones = append(zones, AvailabilityZoneFor(region, i)) + } + + return zones +} + +// ZoneForKey returns a stable synthetic Availability Zone name for an opaque key +// (a subnet id): the same key always maps to the same zone. +func ZoneForKey(region, key string) string { + h := fnv.New32a() + _, _ = h.Write([]byte(key)) + + return AvailabilityZoneFor(region, int(h.Sum32()%uint32(len(azLetters)))) +} diff --git a/services/networkfirewall/driver/capabilities.go b/services/networkfirewall/driver/capabilities.go new file mode 100644 index 000000000..3f24b4430 --- /dev/null +++ b/services/networkfirewall/driver/capabilities.go @@ -0,0 +1,195 @@ +package driver + +import ( + "context" + "encoding/json" + "time" +) + +// The interfaces below are optional capability groups. A driver implements the +// ones it supports; the wire handler finds them by type assertion and answers +// UnsupportedOperationException for a group the driver lacks, so the base +// NetworkFirewall interface is not widened for every implementer. + +// FirewallSettings covers the firewall-level setters. +type FirewallSettings interface { + UpdateFirewallDescription(ctx context.Context, firewallName, description, updateToken string) (*Firewall, error) + UpdateSubnetChangeProtection(ctx context.Context, firewallName string, enabled bool, updateToken string) (*Firewall, error) + UpdateFirewallPolicyChangeProtection(ctx context.Context, firewallName string, enabled bool, updateToken string) (*Firewall, error) + UpdateAvailabilityZoneChangeProtection(ctx context.Context, firewallName string, enabled bool, updateToken string) (*Firewall, error) + UpdateFirewallAnalysisSettings(ctx context.Context, firewallName string, analysisTypes []string, updateToken string) (*Firewall, error) +} + +// AvailabilityZones covers the Availability-Zone associations of a transit +// gateway-attached firewall. +type AvailabilityZones interface { + AssociateAvailabilityZones(ctx context.Context, firewallName string, zones []string, updateToken string) (*Firewall, error) + DisassociateAvailabilityZones(ctx context.Context, firewallName string, zones []string, updateToken string) (*Firewall, error) +} + +// ResourcePolicies covers the resource-sharing IAM policies attached to a rule +// group, firewall policy or firewall. +type ResourcePolicies interface { + PutResourcePolicy(ctx context.Context, resourceARN, policy string) error + DescribeResourcePolicy(ctx context.Context, resourceARN string) (string, error) + DeleteResourcePolicy(ctx context.Context, resourceARN string) error +} + +// TLSInspectionConfig is a TLS inspection configuration a firewall policy can +// reference. Configuration holds the "TLSInspectionConfiguration" payload +// (ServerCertificateConfigurations) exactly as the caller provided it. +type TLSInspectionConfig struct { + Name string + ARN string + ID string + Description string + Configuration json.RawMessage + CertificateARNs []string + Status string + NumberOfAssociations int + LastModified time.Time + UpdateToken string + Tags map[string]string +} + +// CreateTLSInspectionConfig is the input to CreateTLSInspectionConfiguration. +type CreateTLSInspectionConfig struct { + Name string + Description string + Configuration json.RawMessage + Tags map[string]string +} + +// UpdateTLSInspectionConfig is the input to UpdateTLSInspectionConfiguration. +// UpdateToken is required. +type UpdateTLSInspectionConfig struct { + UpdateToken string + Description string + Configuration json.RawMessage +} + +// TLSInspection covers the TLS inspection configuration family. +type TLSInspection interface { + CreateTLSInspectionConfiguration(ctx context.Context, cfg CreateTLSInspectionConfig) (*TLSInspectionConfig, error) + DescribeTLSInspectionConfiguration(ctx context.Context, name, arn string) (*TLSInspectionConfig, error) + UpdateTLSInspectionConfiguration(ctx context.Context, name, arn string, cfg UpdateTLSInspectionConfig) (*TLSInspectionConfig, error) + DeleteTLSInspectionConfiguration(ctx context.Context, name, arn string) (*TLSInspectionConfig, error) + ListTLSInspectionConfigurations(ctx context.Context, opts ListOptions) ([]TLSInspectionConfig, string, error) +} + +// VPCEndpointAssociation is an extra firewall endpoint in another VPC/subnet. +type VPCEndpointAssociation struct { + ARN string + ID string + FirewallARN string + VPCID string + SubnetID string + IPAddressType string + AvailabilityZone string + Description string + Status string + Tags map[string]string +} + +// CreateVPCEndpointAssociationConfig is the input to CreateVpcEndpointAssociation. +type CreateVPCEndpointAssociationConfig struct { + FirewallARN string + VPCID string + SubnetID string + IPAddressType string + Description string + Tags map[string]string +} + +// VPCEndpointAssociations covers the VPC endpoint association family. +type VPCEndpointAssociations interface { + CreateVpcEndpointAssociation(ctx context.Context, cfg CreateVPCEndpointAssociationConfig) (*VPCEndpointAssociation, error) + DescribeVpcEndpointAssociation(ctx context.Context, arn string) (*VPCEndpointAssociation, error) + DeleteVpcEndpointAssociation(ctx context.Context, arn string) (*VPCEndpointAssociation, error) + ListVpcEndpointAssociations(ctx context.Context, firewallARN string, opts ListOptions) ([]VPCEndpointAssociation, string, error) +} + +// FirewallMetadata is the DescribeFirewallMetadata result. +type FirewallMetadata struct { + FirewallARN string + PolicyARN string + Description string + Status string + AvailabilityZones []string +} + +// RuleSummary is one entry of a rule group summary. +type RuleSummary struct { + Msg string + SID string + Metadata string +} + +// Metadata covers the read-only metadata/summary operations. +type Metadata interface { + DescribeFirewallMetadata(ctx context.Context, firewallARN string) (*FirewallMetadata, error) + DescribeRuleGroupMetadata(ctx context.Context, name, arn, ruleType string) (*RuleGroup, error) + DescribeRuleGroupSummary(ctx context.Context, name, arn, ruleType string) (*RuleGroup, []RuleSummary, error) +} + +// FlowOperation is a flow capture or flush request. The emulator has no data +// plane, so an operation completes without results. +type FlowOperation struct { + ID string + FirewallARN string + Type string // FLOW_CAPTURE | FLOW_FLUSH + Status string + StatusMessage string + AvailabilityZone string + VPCEndpointID string + VPCEndpointAssociationARN string + MinimumFlowAgeSeconds *int32 + Filters json.RawMessage + RequestedAt time.Time +} + +// FlowOperationRequest is the input to StartFlowCapture / StartFlowFlush. +type FlowOperationRequest struct { + FirewallARN string + AvailabilityZone string + VPCEndpointID string + VPCEndpointAssociationARN string + MinimumFlowAgeSeconds *int32 + Filters json.RawMessage +} + +// FlowOperationScope identifies the firewall endpoint a flow operation ran on. +type FlowOperationScope struct { + FirewallARN string + AvailabilityZone string + VPCEndpointID string + VPCEndpointAssociationARN string +} + +// FlowOperations covers the flow capture / flush family. +type FlowOperations interface { + StartFlowCapture(ctx context.Context, req FlowOperationRequest) (*FlowOperation, error) + StartFlowFlush(ctx context.Context, req FlowOperationRequest) (*FlowOperation, error) + DescribeFlowOperation(ctx context.Context, scope FlowOperationScope, id string) (*FlowOperation, error) + ListFlowOperations(ctx context.Context, scope FlowOperationScope, opType string, opts ListOptions) ([]FlowOperation, string, error) + // ListFlowOperationResults returns the operation and its (always empty, there is no + // data plane) flows. + ListFlowOperationResults(ctx context.Context, scope FlowOperationScope, id string, opts ListOptions) (*FlowOperation, string, error) +} + +// AnalysisReport is a traffic analysis report request. +type AnalysisReport struct { + ID string + FirewallARN string + AnalysisType string + Status string + ReportTime time.Time +} + +// AnalysisReports covers the analysis report family. +type AnalysisReports interface { + StartAnalysisReport(ctx context.Context, firewallName, firewallARN, analysisType string) (*AnalysisReport, error) + ListAnalysisReports(ctx context.Context, firewallName, firewallARN string, opts ListOptions) ([]AnalysisReport, string, error) + // GetAnalysisReport returns one report (its results are always empty). + GetAnalysisReport(ctx context.Context, firewallName, firewallARN, reportID string) (*AnalysisReport, error) +} diff --git a/services/networkfirewall/driver/driver.go b/services/networkfirewall/driver/driver.go index aafcf24ea..d95f9bf4e 100644 --- a/services/networkfirewall/driver/driver.go +++ b/services/networkfirewall/driver/driver.go @@ -6,42 +6,76 @@ package driver import ( "context" "encoding/json" + "time" ) -// Firewall is a Network Firewall attached to a VPC across subnets. +// Firewall is a Network Firewall attached to a VPC across subnets, or to a +// transit gateway across Availability Zones. +// +// UpdateToken is the optimistic-locking token of the firewall: it is minted at +// create and rotated by every mutation. NumberOfAssociations is computed (the +// firewall's VPC endpoint associations). type Firewall struct { - Name string - ARN string - ID string - PolicyARN string - VPCID string - SubnetIDs []string - Description string - DeleteProtection bool - Status string - Tags map[string]string + Name string + ARN string + ID string + PolicyARN string + VPCID string + SubnetIDs []string + AvailabilityZones []string + TransitGatewayID string + Description string + DeleteProtection bool + SubnetChangeProtection bool + FirewallPolicyChangeProtection bool + AvailabilityZoneChangeProtection bool + EnabledAnalysisTypes []string + NumberOfAssociations int + Status string + UpdateToken string + Tags map[string]string } // CreateFirewallConfig is the input to CreateFirewall. type CreateFirewallConfig struct { - Name string - PolicyARN string - VPCID string - SubnetIDs []string - Description string - DeleteProtection bool - Tags map[string]string + Name string + PolicyARN string + VPCID string + SubnetIDs []string + AvailabilityZones []string + TransitGatewayID string + Description string + DeleteProtection bool + SubnetChangeProtection bool + FirewallPolicyChangeProtection bool + AvailabilityZoneChangeProtection bool + EnabledAnalysisTypes []string + Tags map[string]string } // RuleGroupReference links a firewall policy to a rule group, by ARN. Priority // orders stateless rule groups (required by AWS) and, for STRICT_ORDER -// stateful policies, stateful rule groups too. +// stateful policies, stateful rule groups too. Override and +// DeepThreatInspection are stateful-only settings kept byte-faithfully. type RuleGroupReference struct { - ResourceARN string - Priority int + ResourceARN string + Priority int + Override json.RawMessage + DeepThreatInspection *bool +} + +// PolicyExtra holds the firewall-policy settings the emulator stores and +// returns verbatim without interpreting them. +type PolicyExtra struct { + StatelessCustomActions json.RawMessage + PolicyVariables json.RawMessage + StatefulEngineOptions json.RawMessage + EnableTLSSessionHolding *bool } -// FirewallPolicy groups stateless/stateful rule-group references + default actions. +// FirewallPolicy groups stateless/stateful rule-group references + default +// actions. The Consumed* capacities, NumberOfAssociations, Status and +// LastModified are computed by the provider. type FirewallPolicy struct { Name string ARN string @@ -49,8 +83,18 @@ type FirewallPolicy struct { Description string StatelessDefaultActions []string StatelessFragmentDefaultActions []string + StatefulDefaultActions []string StatefulRuleGroupReferences []RuleGroupReference StatelessRuleGroupReferences []RuleGroupReference + TLSInspectionConfigurationARN string + Extra PolicyExtra + Status string + NumberOfAssociations int + ConsumedStatelessRuleCapacity int + ConsumedStatefulRuleCapacity int + ConsumedStatefulDomainCapacity int + LastModified time.Time + UpdateToken string Tags map[string]string } @@ -60,54 +104,72 @@ type CreateFirewallPolicyConfig struct { Description string StatelessDefaultActions []string StatelessFragmentDefaultActions []string + StatefulDefaultActions []string StatefulRuleGroupReferences []RuleGroupReference StatelessRuleGroupReferences []RuleGroupReference + TLSInspectionConfigurationARN string + Extra PolicyExtra Tags map[string]string } +// UpdateFirewallPolicyConfig is the input to UpdateFirewallPolicy. UpdateToken +// is required (AWS marks it required on this operation). +type UpdateFirewallPolicyConfig struct { + UpdateToken string + Description string + StatelessDefaultActions []string + StatelessFragmentDefaultActions []string + StatefulDefaultActions []string + StatefulRuleGroupReferences []RuleGroupReference + StatelessRuleGroupReferences []RuleGroupReference + TLSInspectionConfigurationARN string + Extra PolicyExtra +} + // RuleGroup is a reusable collection of stateful or stateless rules. // // Rules holds the full "RuleGroup" payload (RulesSource, RuleVariables, // ReferenceSets, StatefulRuleOptions) exactly as the caller provided it. The -// emulator doesn't interpret Suricata/stateful/stateless rule content, so it -// is stored and returned byte-faithfully rather than modeled field-by-field. +// emulator doesn't interpret Suricata/stateful/stateless rule content beyond +// computing the capacity it consumes and the rule summaries, so it is stored +// and returned byte-faithfully rather than modeled field-by-field. type RuleGroup struct { - Name string - ARN string - ID string - Type string // STATEFUL | STATELESS - Capacity int - Description string - Rules json.RawMessage - Tags map[string]string + Name string + ARN string + ID string + Type string // STATEFUL | STATELESS | STATEFUL_DOMAIN + Capacity int + ConsumedCapacity int + NumberOfAssociations int + Description string + Rules json.RawMessage + SummaryRuleOptions []string + Status string + LastModified time.Time + UpdateToken string + Tags map[string]string } // CreateRuleGroupConfig is the input to CreateRuleGroup. type CreateRuleGroupConfig struct { - Name string - Type string - Capacity int - Description string - Rules json.RawMessage - Tags map[string]string -} - -// UpdateFirewallPolicyConfig is the input to UpdateFirewallPolicy. -type UpdateFirewallPolicyConfig struct { - Description string - StatelessDefaultActions []string - StatelessFragmentDefaultActions []string - StatefulRuleGroupReferences []RuleGroupReference - StatelessRuleGroupReferences []RuleGroupReference + Name string + Type string + Capacity int + Description string + Rules json.RawMessage + SummaryRuleOptions []string + Tags map[string]string } // UpdateRuleGroupConfig is the input to UpdateRuleGroup. Capacity is immutable // in real Network Firewall. Rules is left nil when the caller didn't send a // RuleGroup/Rules payload, so an update that only changes the description -// doesn't wipe existing rule content. +// doesn't wipe existing rule content. UpdateToken is required. type UpdateRuleGroupConfig struct { - Description string - Rules json.RawMessage + UpdateToken string + Description string + Rules json.RawMessage + SummaryRuleOptions []string } // LogDestinationConfig configures where one log type (ALERT/FLOW/TLS) is @@ -119,33 +181,63 @@ type LogDestinationConfig struct { LogDestination map[string]string } -// NetworkFirewall is the AWS Network Firewall control plane. +// LoggingConfiguration is a firewall's log destinations plus the monitoring +// dashboard switch. A nil EnableMonitoringDashboard on update leaves the stored +// switch unchanged. +type LoggingConfiguration struct { + Destinations []LogDestinationConfig + EnableMonitoringDashboard *bool +} + +// ListOptions carries MaxResults/NextToken for a list operation. A zero +// MaxResults means "the service default" (100). +type ListOptions struct { + MaxResults int + NextToken string +} + +// RuleGroupFilter narrows ListRuleGroups. Scope (MANAGED | ACCOUNT) and +// ManagedType select AWS-managed rule groups, which the emulator does not have, +// so MANAGED or a ManagedType yields an empty list. +type RuleGroupFilter struct { + Type string + Scope string + ManagedType string +} + +// NetworkFirewall is the AWS Network Firewall control plane (the operations +// every driver implements). Further operation families are optional +// capability interfaces in capabilities.go. +// +// Mutations take the update token the caller last read ("" = unconditional, +// permitted only where AWS marks the token optional): a stale token fails with +// InvalidToken. // //nolint:interfacebloat // mirrors the network-firewall API surface. type NetworkFirewall interface { CreateFirewall(ctx context.Context, cfg CreateFirewallConfig) (*Firewall, error) DescribeFirewall(ctx context.Context, name, arn string) (*Firewall, error) DeleteFirewall(ctx context.Context, name, arn string) (*Firewall, error) - ListFirewalls(ctx context.Context) ([]Firewall, error) + ListFirewalls(ctx context.Context, vpcIDs []string, opts ListOptions) ([]Firewall, string, error) CreateFirewallPolicy(ctx context.Context, cfg CreateFirewallPolicyConfig) (*FirewallPolicy, error) DescribeFirewallPolicy(ctx context.Context, name, arn string) (*FirewallPolicy, error) UpdateFirewallPolicy(ctx context.Context, name, arn string, cfg UpdateFirewallPolicyConfig) (*FirewallPolicy, error) DeleteFirewallPolicy(ctx context.Context, name, arn string) (*FirewallPolicy, error) - ListFirewallPolicies(ctx context.Context) ([]FirewallPolicy, error) + ListFirewallPolicies(ctx context.Context, opts ListOptions) ([]FirewallPolicy, string, error) CreateRuleGroup(ctx context.Context, cfg CreateRuleGroupConfig) (*RuleGroup, error) DescribeRuleGroup(ctx context.Context, name, arn, ruleType string) (*RuleGroup, error) UpdateRuleGroup(ctx context.Context, name, arn, ruleType string, cfg UpdateRuleGroupConfig) (*RuleGroup, error) DeleteRuleGroup(ctx context.Context, name, arn, ruleType string) (*RuleGroup, error) - ListRuleGroups(ctx context.Context) ([]RuleGroup, error) - - AssociateFirewallPolicy(ctx context.Context, firewallName, policyARN string) (*Firewall, error) - AssociateSubnets(ctx context.Context, firewallName string, subnetIDs []string) (*Firewall, error) - DisassociateSubnets(ctx context.Context, firewallName string, subnetIDs []string) (*Firewall, error) - UpdateFirewallDeleteProtection(ctx context.Context, firewallName string, enabled bool) (*Firewall, error) - UpdateLoggingConfiguration(ctx context.Context, firewallName string, configs []LogDestinationConfig) error - DescribeLoggingConfiguration(ctx context.Context, firewallName string) ([]LogDestinationConfig, error) + ListRuleGroups(ctx context.Context, filter RuleGroupFilter, opts ListOptions) ([]RuleGroup, string, error) + + AssociateFirewallPolicy(ctx context.Context, firewallName, policyARN, updateToken string) (*Firewall, error) + AssociateSubnets(ctx context.Context, firewallName string, subnetIDs []string, updateToken string) (*Firewall, error) + DisassociateSubnets(ctx context.Context, firewallName string, subnetIDs []string, updateToken string) (*Firewall, error) + UpdateFirewallDeleteProtection(ctx context.Context, firewallName string, enabled bool, updateToken string) (*Firewall, error) + UpdateLoggingConfiguration(ctx context.Context, firewallName string, cfg *LoggingConfiguration) error + DescribeLoggingConfiguration(ctx context.Context, firewallName string) (*LoggingConfiguration, error) TagResource(ctx context.Context, arn string, tags map[string]string) error UntagResource(ctx context.Context, arn string, keys []string) error ListTagsForResource(ctx context.Context, arn string) (map[string]string, error) diff --git a/services/networkfirewall/driver/errors.go b/services/networkfirewall/driver/errors.go new file mode 100644 index 000000000..666c82bd2 --- /dev/null +++ b/services/networkfirewall/driver/errors.go @@ -0,0 +1,59 @@ +package driver + +import ( + "errors" + "fmt" +) + +// Network Firewall exception names, as they appear in the "__type" member of an +// AWS JSON 1.0 error. The wire handler renders these verbatim, so the SDK +// surfaces the exact typed exception a real firewall returns. +const ( + ExInvalidOperation = "InvalidOperationException" + ExInvalidToken = "InvalidTokenException" + ExInvalidResourcePolicy = "InvalidResourcePolicyException" + ExUnsupportedOperation = "UnsupportedOperationException" +) + +// APIError tags an error with the Network Firewall exception it must surface +// as. Errors without a tag fall back to the generic code mapping in the wire +// handler (NotFound -> ResourceNotFoundException and so on). +type APIError struct { + Exception string + Err error +} + +func (e *APIError) Error() string { return e.Err.Error() } +func (e *APIError) Unwrap() error { return e.Err } + +func newAPIError(exception, format string, args ...any) error { + return &APIError{Exception: exception, Err: fmt.Errorf(format, args...)} //nolint:err113 // typed API error carrying a formatted message +} + +// InvalidOperation returns an InvalidOperationException: the request is valid +// but not allowed in the resource's current state (delete protection, a +// resource that is still in use, change protection). +func InvalidOperation(format string, args ...any) error { + return newAPIError(ExInvalidOperation, format, args...) +} + +// InvalidToken returns an InvalidTokenException: the update token is stale. +func InvalidToken(format string, args ...any) error { + return newAPIError(ExInvalidToken, format, args...) +} + +// InvalidResourcePolicy returns an InvalidResourcePolicyException: a resource +// policy statement failed validation. +func InvalidResourcePolicy(format string, args ...any) error { + return newAPIError(ExInvalidResourcePolicy, format, args...) +} + +// ExceptionOf returns the exception tagged on err and true, or "" and false. +func ExceptionOf(err error) (string, bool) { + var api *APIError + if errors.As(err, &api) { + return api.Exception, true + } + + return "", false +} From b9bef54e9d787fa0ec5b7138c6b3f63a1a3a92c0 Mon Sep 17 00:00:00 2001 From: Gajendra Malviya Date: Thu, 22 Oct 2026 11:32:25 +0530 Subject: [PATCH 2/2] fix(aws-networkfirewall): address review on #1652 (rule group ARN clash, per-subnet zones and IP type, subnet and tag validation) --- docs/coverage/aws/networkfirewall.md | 4 +- docs/coverage/nongoals/networkfirewall.md | 4 +- .../aws/networkfirewall/families_test.go | 22 +-- providers/aws/networkfirewall/firewall.go | 65 ++++++-- .../aws/networkfirewall/flow_operation.go | 2 +- providers/aws/networkfirewall/metadata.go | 2 +- .../networkfirewall/networkfirewall_test.go | 146 +++++++++++++++++- .../aws/networkfirewall/reference_test.go | 4 +- providers/aws/networkfirewall/rule_group.go | 9 ++ providers/aws/networkfirewall/snapshot.go | 11 ++ .../aws/networkfirewall/snapshot_test.go | 4 +- providers/aws/networkfirewall/subnets.go | 113 ++++++++++++++ providers/aws/networkfirewall/tags.go | 16 +- providers/aws/networkfirewall/token_test.go | 6 +- .../vpc_endpoint_association.go | 19 ++- server/aws/networkfirewall/depth.go | 4 +- server/aws/networkfirewall/operations.go | 59 ++++--- server/aws/networkfirewall/sdk_parity_test.go | 120 +++++++++++++- .../driver/availability_zones.go | 43 ------ services/networkfirewall/driver/driver.go | 24 ++- 20 files changed, 559 insertions(+), 118 deletions(-) create mode 100644 providers/aws/networkfirewall/subnets.go delete mode 100644 services/networkfirewall/driver/availability_zones.go diff --git a/docs/coverage/aws/networkfirewall.md b/docs/coverage/aws/networkfirewall.md index 5a1d27706..bcc8b3580 100644 --- a/docs/coverage/aws/networkfirewall.md +++ b/docs/coverage/aws/networkfirewall.md @@ -126,9 +126,9 @@ VPCEndpointAssociations covers the VPC endpoint association family. - Not implemented (the operations answer `InvalidRequestException: unknown operation`): the proxy family (`CreateProxy`, `CreateProxyConfiguration`, `CreateProxyRuleGroup`, `CreateProxyRules`, the matching describe, update, delete and list operations, `AttachRuleGroupsToProxyConfiguration`, `DetachRuleGroupsFromProxyConfiguration`, `UpdateProxyRulePriorities`, `UpdateProxyRuleGroupPriorities`), the container association family (`CreateContainerAssociation` and its describe, update, delete and list operations), the transit gateway attachment operations (`AcceptNetworkFirewallTransitGatewayAttachment`, `RejectNetworkFirewallTransitGatewayAttachment`, `DeleteNetworkFirewallTransitGatewayAttachment`) and `UpdateFirewallEncryptionConfiguration`. `EncryptionConfiguration` on create and update requests is accepted and ignored. - There is no packet data plane. Flow capture and flush operations are accepted and complete (immediately, or after the settle window under `--async-settle`) but their results list no flows. Analysis reports complete with no results. Nothing is published to the `AWS/NetworkFirewall` CloudWatch namespace, and the logging configuration is validated and stored but no alert, flow or TLS log is delivered to S3, CloudWatch Logs or Kinesis Data Firehose. - Checks that need another service are not made: the VPC, subnet and Availability Zone ids a firewall or VPC endpoint association names are syntax-checked only, and the certificates, certificate authorities, KMS keys, log destinations and IAM principals named in TLS inspection configurations, logging configurations and resource policies are not looked up. Resource policies are validated (JSON, allowed actions per resource kind) and stored but never evaluated; sharing through Resource Access Manager is not modeled. -- Availability Zones are synthesized. A VPC firewall gets one zone per subnet in the order the subnets were added (`a`, `b`, ...) and a VPC endpoint association gets a zone derived from its subnet id; the real zone of a subnet is not known. +- Availability Zones are synthesized, not read from EC2. When a subnet is attached to a firewall it is given a zone derived from its id (the next free zone if that one is taken, since a firewall has one subnet per zone) and its own endpoint id; both stay fixed while the subnet stays attached, and a VPC endpoint association for the same subnet reports the same zone. The zone is therefore stable and consistent across `DescribeFirewall`, `DescribeFirewallMetadata`, flow operations and associations, but it is not the subnet's real zone. - A transit gateway-attached firewall can be created, described and have Availability Zones associated and disassociated, but no transit gateway attachment is created, so its status never reports a transit gateway attachment sync state. -- Firewalls, policies, rule groups and TLS inspection configurations are `READY` or `ACTIVE` as soon as they are created; there is no `PROVISIONING` period. `DryRun` and `AnalyzeRuleGroup` on create and update requests are accepted and ignored, so a dry run really makes the change and no rule group analysis results are produced. +- Firewalls, policies, rule groups and TLS inspection configurations are `READY` or `ACTIVE` as soon as they are created; there is no `PROVISIONING` period, and `DeleteFirewall` removes the record at once while answering `DELETING`, so `--async-settle` never shows those intermediate states for these resources (only flow operations settle). `DryRun` and `AnalyzeRuleGroup` on create and update requests are accepted and ignored, so a dry run really makes the change and no rule group analysis results are produced. - Rule content is stored and returned byte for byte. Only the parts needed for capacity and summaries are read: stateful rules (one unit per rule in `RulesString`, `StatefulRules` and `RulesSourceList` targets) and stateless rules (the product of the element counts of the match settings, as the CreateRuleGroup reference describes). Suricata syntax, rule variables and reference sets are not validated, and a rule group whose rules need more than its `Capacity` is rejected with `InvalidRequestException` (the exception real AWS uses for this is unconfirmed). - Behaviours the AWS reference does not state were chosen conservatively and are unconfirmed against the live service: a duplicate name answers `InvalidRequestException` (the one exception every Create operation models); deleting a firewall that still has VPC endpoint associations is refused with `InvalidOperationException`; describing or deleting a resource policy that does not exist answers `ResourceNotFoundException`; `DescribeRuleGroupSummary` on a stateless rule group answers `InvalidRequestException` and reports only the options named in the rule group's `SummaryConfiguration`; tagging a resource does not change its update token; a request that gives both a name and an ARN uses the name. - List operations take `MaxResults` (1 to 100, default 100) and `NextToken`, an opaque offset over results sorted by name, so it is only stable while the list does not change between pages. `ListRuleGroups` filters on `Type`, `Scope` and `ManagedType`; the emulator holds no AWS-managed rule groups, so `Scope=MANAGED` or any `ManagedType` returns an empty list. diff --git a/docs/coverage/nongoals/networkfirewall.md b/docs/coverage/nongoals/networkfirewall.md index c01c4f30b..9eaf41357 100644 --- a/docs/coverage/nongoals/networkfirewall.md +++ b/docs/coverage/nongoals/networkfirewall.md @@ -1,9 +1,9 @@ - Not implemented (the operations answer `InvalidRequestException: unknown operation`): the proxy family (`CreateProxy`, `CreateProxyConfiguration`, `CreateProxyRuleGroup`, `CreateProxyRules`, the matching describe, update, delete and list operations, `AttachRuleGroupsToProxyConfiguration`, `DetachRuleGroupsFromProxyConfiguration`, `UpdateProxyRulePriorities`, `UpdateProxyRuleGroupPriorities`), the container association family (`CreateContainerAssociation` and its describe, update, delete and list operations), the transit gateway attachment operations (`AcceptNetworkFirewallTransitGatewayAttachment`, `RejectNetworkFirewallTransitGatewayAttachment`, `DeleteNetworkFirewallTransitGatewayAttachment`) and `UpdateFirewallEncryptionConfiguration`. `EncryptionConfiguration` on create and update requests is accepted and ignored. - There is no packet data plane. Flow capture and flush operations are accepted and complete (immediately, or after the settle window under `--async-settle`) but their results list no flows. Analysis reports complete with no results. Nothing is published to the `AWS/NetworkFirewall` CloudWatch namespace, and the logging configuration is validated and stored but no alert, flow or TLS log is delivered to S3, CloudWatch Logs or Kinesis Data Firehose. - Checks that need another service are not made: the VPC, subnet and Availability Zone ids a firewall or VPC endpoint association names are syntax-checked only, and the certificates, certificate authorities, KMS keys, log destinations and IAM principals named in TLS inspection configurations, logging configurations and resource policies are not looked up. Resource policies are validated (JSON, allowed actions per resource kind) and stored but never evaluated; sharing through Resource Access Manager is not modeled. -- Availability Zones are synthesized. A VPC firewall gets one zone per subnet in the order the subnets were added (`a`, `b`, ...) and a VPC endpoint association gets a zone derived from its subnet id; the real zone of a subnet is not known. +- Availability Zones are synthesized, not read from EC2. When a subnet is attached to a firewall it is given a zone derived from its id (the next free zone if that one is taken, since a firewall has one subnet per zone) and its own endpoint id; both stay fixed while the subnet stays attached, and a VPC endpoint association for the same subnet reports the same zone. The zone is therefore stable and consistent across `DescribeFirewall`, `DescribeFirewallMetadata`, flow operations and associations, but it is not the subnet's real zone. - A transit gateway-attached firewall can be created, described and have Availability Zones associated and disassociated, but no transit gateway attachment is created, so its status never reports a transit gateway attachment sync state. -- Firewalls, policies, rule groups and TLS inspection configurations are `READY` or `ACTIVE` as soon as they are created; there is no `PROVISIONING` period. `DryRun` and `AnalyzeRuleGroup` on create and update requests are accepted and ignored, so a dry run really makes the change and no rule group analysis results are produced. +- Firewalls, policies, rule groups and TLS inspection configurations are `READY` or `ACTIVE` as soon as they are created; there is no `PROVISIONING` period, and `DeleteFirewall` removes the record at once while answering `DELETING`, so `--async-settle` never shows those intermediate states for these resources (only flow operations settle). `DryRun` and `AnalyzeRuleGroup` on create and update requests are accepted and ignored, so a dry run really makes the change and no rule group analysis results are produced. - Rule content is stored and returned byte for byte. Only the parts needed for capacity and summaries are read: stateful rules (one unit per rule in `RulesString`, `StatefulRules` and `RulesSourceList` targets) and stateless rules (the product of the element counts of the match settings, as the CreateRuleGroup reference describes). Suricata syntax, rule variables and reference sets are not validated, and a rule group whose rules need more than its `Capacity` is rejected with `InvalidRequestException` (the exception real AWS uses for this is unconfirmed). - Behaviours the AWS reference does not state were chosen conservatively and are unconfirmed against the live service: a duplicate name answers `InvalidRequestException` (the one exception every Create operation models); deleting a firewall that still has VPC endpoint associations is refused with `InvalidOperationException`; describing or deleting a resource policy that does not exist answers `ResourceNotFoundException`; `DescribeRuleGroupSummary` on a stateless rule group answers `InvalidRequestException` and reports only the options named in the rule group's `SummaryConfiguration`; tagging a resource does not change its update token; a request that gives both a name and an ARN uses the name. - List operations take `MaxResults` (1 to 100, default 100) and `NextToken`, an opaque offset over results sorted by name, so it is only stable while the list does not change between pages. `ListRuleGroups` filters on `Type`, `Scope` and `ManagedType`; the emulator holds no AWS-managed rule groups, so `Scope=MANAGED` or any `ManagedType` returns an empty list. diff --git a/providers/aws/networkfirewall/families_test.go b/providers/aws/networkfirewall/families_test.go index 4b24a7669..ea7660df2 100644 --- a/providers/aws/networkfirewall/families_test.go +++ b/providers/aws/networkfirewall/families_test.go @@ -333,7 +333,7 @@ func TestMetadata_Firewall_RuleGroup(t *testing.T) { assert.Equal(t, fw.ARN, meta.FirewallARN) assert.Equal(t, pol.ARN, meta.PolicyARN) assert.Equal(t, "READY", meta.Status) - assert.Equal(t, []string{"us-east-1a"}, meta.AvailabilityZones) + assert.Equal(t, []string{seedZone}, meta.AvailabilityZones) _, err = m.DescribeFirewallMetadata(bg, "arn:aws:network-firewall:us-east-1:000000000000:firewall/ghost") assert.True(t, cerrors.IsNotFound(err)) @@ -384,9 +384,9 @@ func TestRuleGroupSummary_Stateless_InvalidRequest(t *testing.T) { func TestFlowOperations_StartDescribeListResults(t *testing.T) { m, clock := newClockMock(t) _, fw := seedStack(t, m) - scope := nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"} + scope := nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: seedZone} - capture, err := m.StartFlowCapture(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}) + capture, err := m.StartFlowCapture(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: seedZone}) require.NoError(t, err) assert.Regexp(t, uuidPattern, capture.ID) assert.Equal(t, "COMPLETED", capture.Status) @@ -394,7 +394,7 @@ func TestFlowOperations_StartDescribeListResults(t *testing.T) { clock.Advance(time.Second) - flush, err := m.StartFlowFlush(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}) + flush, err := m.StartFlowFlush(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: seedZone}) require.NoError(t, err) assert.Equal(t, "FLOW_FLUSH", flush.Type) @@ -424,7 +424,7 @@ func TestFlowOperations_Validation(t *testing.T) { assoc := vpcAssociation(t, m, fw.ARN, "subnet-a") other := seedFirewall(t, m, "fw-2", pol.ARN) - _, err := m.StartFlowCapture(bg, nfdriver.FlowOperationRequest{FirewallARN: "arn:aws:network-firewall:us-east-1:000000000000:firewall/ghost", AvailabilityZone: "us-east-1a"}) + _, err := m.StartFlowCapture(bg, nfdriver.FlowOperationRequest{FirewallARN: "arn:aws:network-firewall:us-east-1:000000000000:firewall/ghost", AvailabilityZone: seedZone}) assert.True(t, cerrors.IsNotFound(err), "%v", err) _, err = m.StartFlowCapture(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN}) @@ -437,19 +437,19 @@ func TestFlowOperations_Validation(t *testing.T) { assert.True(t, cerrors.IsInvalidArgument(err), "association of another firewall: %v", err) neg := int32(-1) - _, err = m.StartFlowFlush(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a", MinimumFlowAgeSeconds: &neg}) + _, err = m.StartFlowFlush(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: seedZone, MinimumFlowAgeSeconds: &neg}) assert.True(t, cerrors.IsInvalidArgument(err), "%v", err) - _, _, err = m.ListFlowOperations(bg, nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}, "BOGUS", nfdriver.ListOptions{}) + _, _, err = m.ListFlowOperations(bg, nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: seedZone}, "BOGUS", nfdriver.ListOptions{}) assert.True(t, cerrors.IsInvalidArgument(err), "%v", err) - _, err = m.DescribeFlowOperation(bg, nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}, "no-such-op") + _, err = m.DescribeFlowOperation(bg, nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: seedZone}, "no-such-op") assert.True(t, cerrors.IsNotFound(err), "%v", err) ok, err := m.StartFlowCapture(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, VPCEndpointAssociationARN: assoc.ARN}) require.NoError(t, err) - _, err = m.DescribeFlowOperation(bg, nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}, ok.ID) + _, err = m.DescribeFlowOperation(bg, nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: seedZone}, ok.ID) assert.True(t, cerrors.IsNotFound(err), "an operation of another endpoint is not visible: %v", err) } @@ -458,13 +458,13 @@ func TestFlowOperations_AsyncSettle(t *testing.T) { m := New(config.NewOptions(config.WithClock(clock), config.WithAsyncSettle())) _, fw := seedStack(t, m) - op, err := m.StartFlowFlush(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}) + op, err := m.StartFlowFlush(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: seedZone}) require.NoError(t, err) assert.Equal(t, "IN_PROGRESS", op.Status) clock.Advance(10 * time.Second) - got, err := m.DescribeFlowOperation(bg, nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}, op.ID) + got, err := m.DescribeFlowOperation(bg, nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: seedZone}, op.ID) require.NoError(t, err) assert.Equal(t, "COMPLETED", got.Status) } diff --git a/providers/aws/networkfirewall/firewall.go b/providers/aws/networkfirewall/firewall.go index 1e847f867..08237cbb0 100644 --- a/providers/aws/networkfirewall/firewall.go +++ b/providers/aws/networkfirewall/firewall.go @@ -31,7 +31,6 @@ func (m *Mock) CreateFirewall(_ context.Context, cfg nfdriver.CreateFirewallConf ID: idgen.GenerateID(""), PolicyARN: cfg.PolicyARN, VPCID: cfg.VPCID, - SubnetIDs: cloneStrings(cfg.SubnetIDs), AvailabilityZones: cloneStrings(cfg.AvailabilityZones), TransitGatewayID: cfg.TransitGatewayID, Description: cfg.Description, @@ -44,6 +43,18 @@ func (m *Mock) CreateFirewall(_ context.Context, cfg nfdriver.CreateFirewallConf UpdateToken: newToken(), Tags: copyTags(cfg.Tags), } + for _, s := range cfg.SubnetIDs { + if oneOf(s, fw.SubnetIDs...) { + continue + } + + if err := m.assignSubnet(fw, s, cfg.SubnetIPTypes[s]); err != nil { + return nil, err + } + + fw.SubnetIDs = append(fw.SubnetIDs, s) + } + if !m.firewalls.SetIfAbsent(cfg.Name, fw) { return nil, cerrors.Newf(cerrors.AlreadyExists, "firewall %q already exists", cfg.Name) } @@ -112,6 +123,16 @@ func validateFirewallPlacement(cfg *nfdriver.CreateFirewallConfig) error { return invalid("VpcId is required") } + for _, s := range cfg.SubnetIDs { + if err := validateSubnetID(s); err != nil { + return err + } + + if err := validateIPType(cfg.SubnetIPTypes[s]); err != nil { + return err + } + } + return validateVPCID(cfg.VPCID) } @@ -230,6 +251,7 @@ func (m *Mock) lookupFirewall(name, arn string) (*nfdriver.Firewall, bool) { func (m *Mock) outFirewall(f *nfdriver.Firewall) *nfdriver.Firewall { out := *f out.SubnetIDs = cloneStrings(f.SubnetIDs) + out.SubnetDetails = cloneSubnetDetails(f.SubnetDetails) out.AvailabilityZones = cloneStrings(f.AvailabilityZones) out.EnabledAnalysisTypes = cloneStrings(f.EnabledAnalysisTypes) out.Tags = copyTags(f.Tags) @@ -301,7 +323,7 @@ func (m *Mock) AssociateFirewallPolicy(_ context.Context, firewallName, policyAR func (m *Mock) AssociateSubnets( _ context.Context, firewallName string, - subnetIDs []string, + subnets []nfdriver.SubnetMapping, updateToken string, ) (*nfdriver.Firewall, error) { return m.mutateFirewall(firewallName, updateToken, func(fw *nfdriver.Firewall) error { @@ -309,20 +331,30 @@ func (m *Mock) AssociateSubnets( return err } - if len(subnetIDs) == 0 { + if len(subnets) == 0 { return invalid("SubnetMappings is required") } - seen := make(map[string]bool, len(fw.SubnetIDs)) - for _, s := range fw.SubnetIDs { - seen[s] = true + for _, s := range subnets { + if err := validateSubnetID(s.SubnetID); err != nil { + return err + } + + if err := validateIPType(s.IPAddressType); err != nil { + return err + } } - for _, s := range subnetIDs { - if !seen[s] { - fw.SubnetIDs = append(fw.SubnetIDs, s) - seen[s] = true + for _, s := range subnets { + if oneOf(s.SubnetID, fw.SubnetIDs...) { + continue + } + + if err := m.assignSubnet(fw, s.SubnetID, s.IPAddressType); err != nil { + return err } + + fw.SubnetIDs = append(fw.SubnetIDs, s.SubnetID) } return nil @@ -346,7 +378,16 @@ func (m *Mock) DisassociateSubnets( } remove := make(map[string]bool, len(subnetIDs)) + for _, s := range subnetIDs { + if err := validateSubnetID(s); err != nil { + return err + } + + if !oneOf(s, fw.SubnetIDs...) { + return invalid("subnet %q is not associated with firewall %q", s, fw.Name) + } + remove[s] = true } @@ -360,6 +401,10 @@ func (m *Mock) DisassociateSubnets( fw.SubnetIDs = kept + for s := range remove { + delete(fw.SubnetDetails, s) + } + return nil }) } diff --git a/providers/aws/networkfirewall/flow_operation.go b/providers/aws/networkfirewall/flow_operation.go index 8a66b559d..f93e32ba7 100644 --- a/providers/aws/networkfirewall/flow_operation.go +++ b/providers/aws/networkfirewall/flow_operation.go @@ -95,7 +95,7 @@ func (m *Mock) validateFlowScope(s nfdriver.FlowOperationScope) error { return invalid("either AvailabilityZone or VpcEndpointAssociationArn is required") } - if !oneOf(s.AvailabilityZone, nfdriver.SyncZones(fw, m.opts.Region)...) { + if !oneOf(s.AvailabilityZone, syncZones(fw)...) { return invalid("firewall %q has no endpoint in Availability Zone %q", fw.Name, s.AvailabilityZone) } diff --git a/providers/aws/networkfirewall/metadata.go b/providers/aws/networkfirewall/metadata.go index 499062af9..4699a04ff 100644 --- a/providers/aws/networkfirewall/metadata.go +++ b/providers/aws/networkfirewall/metadata.go @@ -37,7 +37,7 @@ func (m *Mock) DescribeFirewallMetadata(_ context.Context, firewallARN string) ( PolicyARN: fw.PolicyARN, Description: fw.Description, Status: fw.Status, - AvailabilityZones: nfdriver.SyncZones(fw, m.opts.Region), + AvailabilityZones: syncZones(fw), }, nil } diff --git a/providers/aws/networkfirewall/networkfirewall_test.go b/providers/aws/networkfirewall/networkfirewall_test.go index 821d9d542..d1f5c3798 100644 --- a/providers/aws/networkfirewall/networkfirewall_test.go +++ b/providers/aws/networkfirewall/networkfirewall_test.go @@ -3,6 +3,7 @@ package networkfirewall import ( "context" "encoding/json" + "fmt" "sync" "testing" "time" @@ -178,7 +179,7 @@ func TestFirewallDepth(t *testing.T) { _ = pol - assoc, err := m.AssociateSubnets(bg, "fw-1", []string{"subnet-1", "subnet-2"}, "") + assoc, err := m.AssociateSubnets(bg, "fw-1", []nfdriver.SubnetMapping{{SubnetID: "subnet-1"}, {SubnetID: "subnet-2"}}, "") require.NoError(t, err) assert.Len(t, assoc.SubnetIDs, 2) @@ -245,3 +246,146 @@ func TestFirewallConcurrentAccess(t *testing.T) { wg.Wait() } + +func TestRuleGroup_StatefulAndDomainShareNamespace(t *testing.T) { + m := newMock() + + stateful := seedRuleGroup(t, m, "dup", "STATEFUL", 10) + + _, err := m.CreateRuleGroup(bg, nfdriver.CreateRuleGroupConfig{Name: "dup", Type: "STATEFUL_DOMAIN", Capacity: 10}) + require.Error(t, err) + assert.True(t, cerrors.IsAlreadyExists(err)) + + // The ARN of the first group still resolves to it, and it is the only one. + got, err := m.DescribeRuleGroup(bg, "", stateful.ARN, "") + require.NoError(t, err) + assert.Equal(t, "STATEFUL", got.Type) + + list, _, err := m.ListRuleGroups(bg, nfdriver.RuleGroupFilter{}, nfdriver.ListOptions{}) + require.NoError(t, err) + assert.Len(t, list, 1) +} + +func TestRuleGroup_NameWithoutTypeIsRejected(t *testing.T) { + m := newMock() + seedRuleGroup(t, m, "y", "STATELESS", 10) + seedRuleGroup(t, m, "y", "STATEFUL", 10) + + _, err := m.DescribeRuleGroup(bg, "y", "", "") + require.True(t, cerrors.IsInvalidArgument(err), "got %v", err) + + _, err = m.DescribeRuleGroupMetadata(bg, "y", "", "") + require.True(t, cerrors.IsInvalidArgument(err), "got %v", err) + + got, err := m.DescribeRuleGroup(bg, "y", "", "STATEFUL") + require.NoError(t, err) + assert.Equal(t, "STATEFUL", got.Type) +} + +func TestTags_RetagAtLimitAllowed_NewKeyRefused(t *testing.T) { + m := newMock() + pol := seedPolicy(t, m, "pol-1") + + full := make(map[string]string, maxTags) + for i := 0; i < maxTags; i++ { + full[fmt.Sprintf("k%d", i)] = "v" + } + + require.NoError(t, m.TagResource(bg, pol.ARN, full)) + + // Same keys, new values: not new tags, so allowed. + require.NoError(t, m.TagResource(bg, pol.ARN, map[string]string{"k0": "changed", "k1": "changed"})) + + err := m.TagResource(bg, pol.ARN, map[string]string{"extra": "v"}) + require.True(t, cerrors.IsInvalidArgument(err), "got %v", err) +} + +func TestSubnets_EmptyAndUnknownIDsRejected(t *testing.T) { + m := newMock() + _, fw := seedStack(t, m) + + _, err := m.AssociateSubnets(bg, "fw-1", []nfdriver.SubnetMapping{{SubnetID: ""}}, "") + require.True(t, cerrors.IsInvalidArgument(err), "got %v", err) + + _, err = m.DisassociateSubnets(bg, "fw-1", []string{"subnet-unknown"}, "") + require.True(t, cerrors.IsInvalidArgument(err), "got %v", err) + + got, err := m.DescribeFirewall(bg, "fw-1", "") + require.NoError(t, err) + assert.Equal(t, fw.UpdateToken, got.UpdateToken, "a rejected call must not rotate the token") + assert.Equal(t, []string{"subnet-1"}, got.SubnetIDs) + + _, err = m.CreateFirewall(bg, nfdriver.CreateFirewallConfig{ + Name: "fw-empty", PolicyARN: fw.PolicyARN, VPCID: "vpc-1a2b", SubnetIDs: []string{""}, + }) + require.True(t, cerrors.IsInvalidArgument(err), "got %v", err) +} + +func TestSubnets_ZonePerSubnetIsStableAndUnique(t *testing.T) { + m := newMock() + pol := seedPolicy(t, m, "pol-1") + + fw, err := m.CreateFirewall(bg, nfdriver.CreateFirewallConfig{ + Name: "fw-az", PolicyARN: pol.ARN, VPCID: "vpc-1a2b", SubnetIDs: []string{"subnet-a", "subnet-b"}, + SubnetIPTypes: map[string]string{"subnet-a": "IPV4"}, + }) + require.NoError(t, err) + + za, zb := fw.SubnetDetails["subnet-a"], fw.SubnetDetails["subnet-b"] + assert.NotEmpty(t, za.AvailabilityZone) + assert.NotEqual(t, za.AvailabilityZone, zb.AvailabilityZone, "one subnet per zone") + assert.NotEqual(t, za.EndpointID, zb.EndpointID, "each zone has its own endpoint") + assert.Equal(t, "IPV4", za.IPAddressType) + + // Removing the first subnet must not move the second one. + after, err := m.DisassociateSubnets(bg, "fw-az", []string{"subnet-a"}, "") + require.NoError(t, err) + assert.Equal(t, zb, after.SubnetDetails["subnet-b"]) + assert.NotContains(t, after.SubnetDetails, "subnet-a") + + // The zone a flow operation accepts is the zone the subnet reports. + _, err = m.StartFlowCapture(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: zb.AvailabilityZone}) + require.NoError(t, err) + + meta, err := m.DescribeFirewallMetadata(bg, fw.ARN) + require.NoError(t, err) + assert.Equal(t, []string{zb.AvailabilityZone}, meta.AvailabilityZones) + + // A VPC endpoint association for the same subnet lands in the same zone. + assoc, err := m.CreateVpcEndpointAssociation(bg, nfdriver.CreateVPCEndpointAssociationConfig{ + FirewallARN: fw.ARN, VPCID: "vpc-1a2b", SubnetID: "subnet-b", + }) + require.NoError(t, err) + assert.Equal(t, zb.AvailabilityZone, assoc.AvailabilityZone) +} + +func TestSubnets_AssociateKeepsIPAddressType(t *testing.T) { + m := newMock() + seedStack(t, m) + + fw, err := m.AssociateSubnets(bg, "fw-1", []nfdriver.SubnetMapping{{SubnetID: "subnet-2", IPAddressType: "DUALSTACK"}}, "") + require.NoError(t, err) + assert.Equal(t, "DUALSTACK", fw.SubnetDetails["subnet-2"].IPAddressType) + + _, err = m.AssociateSubnets(bg, "fw-1", []nfdriver.SubnetMapping{{SubnetID: "subnet-3", IPAddressType: "BOGUS"}}, "") + require.True(t, cerrors.IsInvalidArgument(err), "got %v", err) +} + +func TestSnapshot_FirewallWithoutSubnetDetailsGetsZones(t *testing.T) { + m := newMock() + _, fw := seedStack(t, m) + + m.mu.Lock() + stored, _ := m.firewalls.Get(fw.Name) + stored.SubnetDetails = nil + m.backfillRestoredState() + m.mu.Unlock() + + got, err := m.DescribeFirewall(bg, "fw-1", "") + require.NoError(t, err) + assert.NotEmpty(t, got.SubnetDetails["subnet-1"].AvailabilityZone) +} + +// seedZone is the Availability Zone the emulator assigns "subnet-1", the subnet +// every seeded firewall is attached to. +var seedZone = zoneForKey("us-east-1", "subnet-1") diff --git a/providers/aws/networkfirewall/reference_test.go b/providers/aws/networkfirewall/reference_test.go index cd62a108d..3ff38a87c 100644 --- a/providers/aws/networkfirewall/reference_test.go +++ b/providers/aws/networkfirewall/reference_test.go @@ -299,9 +299,9 @@ func TestPagination_AllLists_PageSize1_Walk(t *testing.T) { require.NoError(t, err) } - scope := nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"} + scope := nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: seedZone} for i := 0; i < 3; i++ { - _, err := m.StartFlowFlush(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}) + _, err := m.StartFlowFlush(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: seedZone}) require.NoError(t, err) } diff --git a/providers/aws/networkfirewall/rule_group.go b/providers/aws/networkfirewall/rule_group.go index f44d9f119..1f81ea05c 100644 --- a/providers/aws/networkfirewall/rule_group.go +++ b/providers/aws/networkfirewall/rule_group.go @@ -66,6 +66,11 @@ func (m *Mock) CreateRuleGroup(_ context.Context, cfg nfdriver.CreateRuleGroupCo UpdateToken: newToken(), Tags: copyTags(cfg.Tags), } + // STATEFUL and STATEFUL_DOMAIN groups share the stateful ARN namespace. + if _, taken := m.ruleGroupByARN(rg.ARN); taken { + return nil, cerrors.Newf(cerrors.AlreadyExists, "rule group %q already exists", cfg.Name) + } + if !m.ruleGroups.SetIfAbsent(ruleGroupKey(cfg.Name, cfg.Type), rg) { return nil, cerrors.Newf(cerrors.AlreadyExists, "rule group %q already exists", cfg.Name) } @@ -241,6 +246,10 @@ func (m *Mock) findRuleGroup(name, arn, ruleType string) (*nfdriver.RuleGroup, e return nil, err } + if name != "" && ruleType == "" && arn == "" { + return nil, invalid("Type is required when RuleGroupArn is not set") + } + if name != "" && ruleType != "" && !oneOf(ruleType, ruleTypeStateful, ruleTypeStateless, ruleTypeStatefulDomain) { return nil, invalid("Type %q is not valid", ruleType) } diff --git a/providers/aws/networkfirewall/snapshot.go b/providers/aws/networkfirewall/snapshot.go index 0a355e5b1..72eb874d1 100644 --- a/providers/aws/networkfirewall/snapshot.go +++ b/providers/aws/networkfirewall/snapshot.go @@ -188,6 +188,7 @@ func (m *Mock) restoreStores(snap *networkfirewallSnapshot) error { func (m *Mock) backfillRestoredState() { for _, f := range m.firewalls.SortedValues() { ensureToken(&f.UpdateToken) + m.backfillSubnets(f) } for _, p := range m.policies.SortedValues() { @@ -217,3 +218,13 @@ func ensureActive(status *string) { *status = statusActive } } + +// backfillSubnets gives a restored firewall the per-subnet zones and endpoints +// state saved before this release does not carry. +func (m *Mock) backfillSubnets(f *nfdriver.Firewall) { + for _, s := range f.SubnetIDs { + if _, ok := f.SubnetDetails[s]; !ok { + _ = m.assignSubnet(f, s, "") + } + } +} diff --git a/providers/aws/networkfirewall/snapshot_test.go b/providers/aws/networkfirewall/snapshot_test.go index fcefe29de..be04a7660 100644 --- a/providers/aws/networkfirewall/snapshot_test.go +++ b/providers/aws/networkfirewall/snapshot_test.go @@ -35,7 +35,7 @@ func TestSnapshotRoundTripNetworkFirewall(t *testing.T) { })) require.NoError(t, src.PutResourcePolicy(bg, pol.ARN, policyDoc("network-firewall:AssociateFirewallPolicy"))) - flow, err := src.StartFlowFlush(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}) + flow, err := src.StartFlowFlush(bg, nfdriver.FlowOperationRequest{FirewallARN: fw.ARN, AvailabilityZone: seedZone}) require.NoError(t, err) _, err = src.UpdateFirewallAnalysisSettings(bg, "fw-1", []string{"TLS_SNI"}, "") @@ -77,7 +77,7 @@ func TestSnapshotRoundTripNetworkFirewall(t *testing.T) { require.NoError(t, err) assert.Contains(t, policy, "AssociateFirewallPolicy") - _, err = dst.DescribeFlowOperation(bg, nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: "us-east-1a"}, flow.ID) + _, err = dst.DescribeFlowOperation(bg, nfdriver.FlowOperationScope{FirewallARN: fw.ARN, AvailabilityZone: seedZone}, flow.ID) require.NoError(t, err) _, err = dst.GetAnalysisReport(bg, "fw-1", "", rep.ID) diff --git a/providers/aws/networkfirewall/subnets.go b/providers/aws/networkfirewall/subnets.go new file mode 100644 index 000000000..c56662db8 --- /dev/null +++ b/providers/aws/networkfirewall/subnets.go @@ -0,0 +1,113 @@ +package networkfirewall + +import ( + "hash/fnv" + + cerrors "github.com/stackshy/cloudemu/v2/errors" + nfdriver "github.com/stackshy/cloudemu/v2/services/networkfirewall/driver" +) + +// azLetters are the zone suffixes the emulator hands out. It has no real +// subnet-to-zone mapping, so a subnet gets a zone derived from its id. +const azLetters = "abcdef" + +// zoneForKey returns the Availability Zone a key (a subnet id) prefers: the same +// key always maps to the same zone. +func zoneForKey(region, key string) string { + h := fnv.New32a() + _, _ = h.Write([]byte(key)) + + return region + string(azLetters[int(h.Sum32()%uint32(len(azLetters)))]) +} + +// assignSubnet records a subnet's zone and endpoint on the firewall. A firewall +// has at most one subnet per zone, so when the preferred zone is taken the next +// free one is used. The assignment is stored and never recomputed. +func (m *Mock) assignSubnet(fw *nfdriver.Firewall, subnetID, ipType string) error { + if fw.SubnetDetails == nil { + fw.SubnetDetails = map[string]nfdriver.SubnetDetail{} + } + + if len(fw.SubnetDetails) >= len(azLetters) { + return invalid("a firewall can have at most %d subnets, one per Availability Zone", len(azLetters)) + } + + used := make(map[string]bool, len(fw.SubnetDetails)) + for _, d := range fw.SubnetDetails { + used[d.AvailabilityZone] = true + } + + zone := zoneForKey(m.opts.Region, subnetID) + + for i := 0; used[zone] && i < len(azLetters); i++ { + zone = m.opts.Region + string(azLetters[(indexOfLetter(zone)+1)%len(azLetters)]) + } + + fw.SubnetDetails[subnetID] = nfdriver.SubnetDetail{ + IPAddressType: ipType, + AvailabilityZone: zone, + EndpointID: endpointID(fw.ID, zone), + } + + return nil +} + +func indexOfLetter(zone string) int { + for i := range azLetters { + if zone[len(zone)-1] == azLetters[i] { + return i + } + } + + return 0 +} + +// endpointID names the firewall endpoint in one zone. +func endpointID(firewallID, zone string) string { + return "vpce-" + firewallID + "-" + zone[len(zone)-1:] +} + +// syncZones returns the zones a firewall runs in: its explicit zones for a +// transit gateway-attached firewall, else the zone of each attached subnet. +func syncZones(fw *nfdriver.Firewall) []string { + if len(fw.AvailabilityZones) > 0 { + return cloneStrings(fw.AvailabilityZones) + } + + zones := make([]string, 0, len(fw.SubnetIDs)) + for _, s := range fw.SubnetIDs { + zones = append(zones, fw.SubnetDetails[s].AvailabilityZone) + } + + return zones +} + +// validateSubnetID rejects an empty subnet id. +func validateSubnetID(id string) error { + if id == "" { + return invalid("SubnetId must not be empty") + } + + return nil +} + +func validateIPType(ipType string) error { + if ipType != "" && !oneOf(ipType, ipAddressType...) { + return cerrors.Newf(cerrors.InvalidArgument, "SubnetMapping.IPAddressType %q is not valid", ipType) + } + + return nil +} + +func cloneSubnetDetails(in map[string]nfdriver.SubnetDetail) map[string]nfdriver.SubnetDetail { + if in == nil { + return nil + } + + out := make(map[string]nfdriver.SubnetDetail, len(in)) + for k, v := range in { + out[k] = v + } + + return out +} diff --git a/providers/aws/networkfirewall/tags.go b/providers/aws/networkfirewall/tags.go index 1ddf8d1e5..e2f4f125c 100644 --- a/providers/aws/networkfirewall/tags.go +++ b/providers/aws/networkfirewall/tags.go @@ -22,7 +22,7 @@ func (m *Mock) TagResource(_ context.Context, arn string, tags map[string]string return cerrors.Newf(cerrors.NotFound, "resource %q not found", arn) } - if len(t)+len(tags) > maxTags { + if len(t)+newKeys(t, tags) > maxTags { return invalid("at most %d tags are allowed", maxTags) } @@ -129,3 +129,17 @@ func (m *Mock) taggableExtra(arn string) map[string]string { return nil } + +// newKeys counts the keys of add that the resource does not have yet: re-tagging +// an existing key is an overwrite, not a new tag. +func newKeys(have, add map[string]string) int { + n := 0 + + for k := range add { + if _, ok := have[k]; !ok { + n++ + } + } + + return n +} diff --git a/providers/aws/networkfirewall/token_test.go b/providers/aws/networkfirewall/token_test.go index afd49a156..ad7a3f120 100644 --- a/providers/aws/networkfirewall/token_test.go +++ b/providers/aws/networkfirewall/token_test.go @@ -198,7 +198,7 @@ func TestChangeProtection_BlocksSubnetAssociateDisassociate(t *testing.T) { _, err := m.UpdateSubnetChangeProtection(bg, "fw-1", true, "") require.NoError(t, err) - _, err = m.AssociateSubnets(bg, "fw-1", []string{"subnet-2"}, "") + _, err = m.AssociateSubnets(bg, "fw-1", []nfdriver.SubnetMapping{{SubnetID: "subnet-2"}}, "") requireException(t, err, nfdriver.ExInvalidOperation) _, err = m.DisassociateSubnets(bg, "fw-1", []string{"subnet-1"}, "") @@ -207,7 +207,7 @@ func TestChangeProtection_BlocksSubnetAssociateDisassociate(t *testing.T) { _, err = m.UpdateSubnetChangeProtection(bg, "fw-1", false, "") require.NoError(t, err) - _, err = m.AssociateSubnets(bg, "fw-1", []string{"subnet-2"}, "") + _, err = m.AssociateSubnets(bg, "fw-1", []nfdriver.SubnetMapping{{SubnetID: "subnet-2"}}, "") require.NoError(t, err) } @@ -285,7 +285,7 @@ func TestAvailabilityZones_OnVPCFirewall_Unsupported(t *testing.T) { _, err := m.AssociateAvailabilityZones(bg, vpc.Name, []string{"us-east-1b"}, "") requireException(t, err, nfdriver.ExInvalidOperation) - _, err = m.AssociateSubnets(bg, tgw.Name, []string{"subnet-1"}, "") + _, err = m.AssociateSubnets(bg, tgw.Name, []nfdriver.SubnetMapping{{SubnetID: "subnet-1"}}, "") requireException(t, err, nfdriver.ExInvalidOperation) } diff --git a/providers/aws/networkfirewall/vpc_endpoint_association.go b/providers/aws/networkfirewall/vpc_endpoint_association.go index f7e2582b5..41d534dd4 100644 --- a/providers/aws/networkfirewall/vpc_endpoint_association.go +++ b/providers/aws/networkfirewall/vpc_endpoint_association.go @@ -27,8 +27,8 @@ func (m *Mock) CreateVpcEndpointAssociation( return nil, invalid("SubnetMapping.SubnetId is required") } - if cfg.IPAddressType != "" && !oneOf(cfg.IPAddressType, ipAddressType...) { - return nil, invalid("SubnetMapping.IPAddressType %q is not valid", cfg.IPAddressType) + if err := validateIPType(cfg.IPAddressType); err != nil { + return nil, err } if err := validateDescription(cfg.Description); err != nil { @@ -39,7 +39,8 @@ func (m *Mock) CreateVpcEndpointAssociation( return nil, err } - if _, ok := m.firewallByARN(cfg.FirewallARN); !ok { + fw, ok := m.firewallByARN(cfg.FirewallARN) + if !ok { return nil, cerrors.Newf(cerrors.NotFound, "firewall %q not found", cfg.FirewallARN) } @@ -51,7 +52,7 @@ func (m *Mock) CreateVpcEndpointAssociation( VPCID: cfg.VPCID, SubnetID: cfg.SubnetID, IPAddressType: cfg.IPAddressType, - AvailabilityZone: nfdriver.ZoneForKey(m.opts.Region, cfg.SubnetID), + AvailabilityZone: m.associationZone(fw, cfg.SubnetID), Description: cfg.Description, Status: statusReady, Tags: copyTags(cfg.Tags), @@ -155,3 +156,13 @@ func cloneAssociation(a *nfdriver.VPCEndpointAssociation) *nfdriver.VPCEndpointA return &out } + +// associationZone is the Availability Zone of an association's subnet: the zone +// the firewall already assigned that subnet, else the zone its id maps to. +func (m *Mock) associationZone(fw *nfdriver.Firewall, subnetID string) string { + if d, ok := fw.SubnetDetails[subnetID]; ok { + return d.AvailabilityZone + } + + return zoneForKey(m.opts.Region, subnetID) +} diff --git a/server/aws/networkfirewall/depth.go b/server/aws/networkfirewall/depth.go index 6ae06d546..6f9ab4bed 100644 --- a/server/aws/networkfirewall/depth.go +++ b/server/aws/networkfirewall/depth.go @@ -106,7 +106,7 @@ type subnetsRequest struct { func (h *Handler) associateSubnets(w http.ResponseWriter, r *http.Request) { serveFirewallOp[subnetsRequest](h, w, r, func(c nfdriver.NetworkFirewall, name string, req *subnetsRequest) (*nfdriver.Firewall, map[string]any, error) { - fw, err := c.AssociateSubnets(r.Context(), name, subnetIDs(req.SubnetMappings), req.UpdateToken) + fw, err := c.AssociateSubnets(r.Context(), name, driverSubnets(req.SubnetMappings), req.UpdateToken) if err != nil { return nil, nil, err } @@ -130,7 +130,7 @@ func (h *Handler) disassociateSubnets(w http.ResponseWriter, r *http.Request) { func subnetMappingsOf(fw *nfdriver.Firewall) []subnetMapping { mappings := make([]subnetMapping, 0, len(fw.SubnetIDs)) for _, s := range fw.SubnetIDs { - mappings = append(mappings, subnetMapping{SubnetID: s}) + mappings = append(mappings, subnetMapping{SubnetID: s, IPAddressType: fw.SubnetDetails[s].IPAddressType}) } return mappings diff --git a/server/aws/networkfirewall/operations.go b/server/aws/networkfirewall/operations.go index 8b4791f49..33dacbacc 100644 --- a/server/aws/networkfirewall/operations.go +++ b/server/aws/networkfirewall/operations.go @@ -3,7 +3,6 @@ package networkfirewall import ( "encoding/json" "net/http" - "strings" "time" "github.com/stackshy/cloudemu/v2/server/wire" @@ -71,21 +70,22 @@ type firewallStatusJSON struct { // toFirewallStatusJSON builds the FirewallStatus block. A firewall in the // emulator is always fully provisioned, so it reports READY / IN_SYNC with one -// SyncState per attached subnet keyed by a synthetic Availability Zone. +// SyncState per attached subnet, keyed by the Availability Zone and endpoint +// the firewall assigned that subnet. func toFirewallStatusJSON(f *nfdriver.Firewall) firewallStatusJSON { - region := arnRegion(f.ARN) - states := make(map[string]syncStateJSON, len(f.SubnetIDs)) - for i, subnet := range f.SubnetIDs { - states[nfdriver.AvailabilityZoneFor(region, i)] = syncStateJSON{Attachment: attachmentJSON{ + + for _, subnet := range f.SubnetIDs { + d := f.SubnetDetails[subnet] + states[d.AvailabilityZone] = syncStateJSON{Attachment: attachmentJSON{ SubnetID: subnet, - EndpointID: "vpce-" + f.ID, + EndpointID: d.EndpointID, Status: "READY", }} } for _, az := range f.AvailabilityZones { - states[az] = syncStateJSON{Attachment: attachmentJSON{EndpointID: "vpce-" + f.ID, Status: "READY"}} + states[az] = syncStateJSON{Attachment: attachmentJSON{EndpointID: "vpce-" + f.ID + "-" + az, Status: "READY"}} } if len(states) == 0 { @@ -99,17 +99,6 @@ func toFirewallStatusJSON(f *nfdriver.Firewall) firewallStatusJSON { } } -// arnRegion extracts the region field (index 3) from an AWS ARN, defaulting to -// "us-east-1" when the ARN is malformed or region-less. -func arnRegion(arn string) string { - parts := strings.Split(arn, ":") - if len(parts) > 3 && parts[3] != "" { - return parts[3] - } - - return "us-east-1" -} - type createFirewallRequest struct { FirewallName string `json:"FirewallName"` FirewallPolicyArn string `json:"FirewallPolicyArn"` @@ -142,6 +131,7 @@ func (h *Handler) createFirewall(w http.ResponseWriter, r *http.Request) { PolicyARN: req.FirewallPolicyArn, VPCID: req.VpcID, SubnetIDs: subnetIDs(req.SubnetMappings), + SubnetIPTypes: subnetIPTypes(req.SubnetMappings), AvailabilityZones: zoneNames(req.AvailabilityZoneMappings), TransitGatewayID: req.TransitGatewayID, Description: req.Description, @@ -236,11 +226,6 @@ func withNextToken(resp map[string]any, next string) map[string]any { } func toFirewallJSON(f *nfdriver.Firewall) firewallJSON { - mappings := make([]subnetMapping, 0, len(f.SubnetIDs)) - for _, s := range f.SubnetIDs { - mappings = append(mappings, subnetMapping{SubnetID: s}) - } - zones := make([]zoneMapping, 0, len(f.AvailabilityZones)) for _, z := range f.AvailabilityZones { zones = append(zones, zoneMapping{AvailabilityZone: z}) @@ -248,7 +233,7 @@ func toFirewallJSON(f *nfdriver.Firewall) firewallJSON { return firewallJSON{ FirewallName: f.Name, FirewallArn: f.ARN, FirewallID: f.ID, FirewallPolicyArn: f.PolicyARN, - VpcID: f.VPCID, SubnetMappings: mappings, AvailabilityZoneMappings: zones, + VpcID: f.VPCID, SubnetMappings: subnetMappingsOf(f), AvailabilityZoneMappings: zones, TransitGatewayID: f.TransitGatewayID, Description: f.Description, DeleteProtection: f.DeleteProtection, SubnetChangeProtection: f.SubnetChangeProtection, FirewallPolicyChangeProtection: f.FirewallPolicyChangeProtection, @@ -273,6 +258,30 @@ func subnetIDs(mappings []subnetMapping) []string { return out } +// subnetIPTypes maps each mapping's subnet id to its IPAddressType, leaving out +// subnets that did not set one. +func subnetIPTypes(mappings []subnetMapping) map[string]string { + out := map[string]string{} + + for _, m := range mappings { + if m.IPAddressType != "" { + out[m.SubnetID] = m.IPAddressType + } + } + + return out +} + +// driverSubnets converts wire subnet mappings to driver ones. +func driverSubnets(mappings []subnetMapping) []nfdriver.SubnetMapping { + out := make([]nfdriver.SubnetMapping, 0, len(mappings)) + for _, m := range mappings { + out = append(out, nfdriver.SubnetMapping{SubnetID: m.SubnetID, IPAddressType: m.IPAddressType}) + } + + return out +} + func zoneNames(mappings []zoneMapping) []string { if len(mappings) == 0 { return nil diff --git a/server/aws/networkfirewall/sdk_parity_test.go b/server/aws/networkfirewall/sdk_parity_test.go index fbaf0e579..76ad94c40 100644 --- a/server/aws/networkfirewall/sdk_parity_test.go +++ b/server/aws/networkfirewall/sdk_parity_test.go @@ -461,7 +461,7 @@ func TestSDK_Metadata_Ops(t *testing.T) { require.NoError(t, err) assert.Equal(t, s.policyARN, aws.ToString(fm.FirewallPolicyArn)) assert.Equal(t, nftypes.FirewallStatusValueReady, fm.Status) - assert.Contains(t, fm.SupportedAvailabilityZones, "us-east-1a") + assert.Contains(t, fm.SupportedAvailabilityZones, "us-east-1c") rm, err := s.c.DescribeRuleGroupMetadata(bg, &networkfirewall.DescribeRuleGroupMetadataInput{RuleGroupArn: rg.RuleGroupResponse.RuleGroupArn}) require.NoError(t, err) @@ -483,29 +483,29 @@ func TestSDK_FlowAndAnalysis_Ops(t *testing.T) { }) require.NoError(t, err) - capture, err := s.c.StartFlowCapture(bg, &networkfirewall.StartFlowCaptureInput{FirewallArn: aws.String(s.fwARN), AvailabilityZone: aws.String("us-east-1a"), FlowFilters: []nftypes.FlowFilter{{SourcePort: aws.String("80")}}}) + capture, err := s.c.StartFlowCapture(bg, &networkfirewall.StartFlowCaptureInput{FirewallArn: aws.String(s.fwARN), AvailabilityZone: aws.String("us-east-1c"), FlowFilters: []nftypes.FlowFilter{{SourcePort: aws.String("80")}}}) require.NoError(t, err) assert.Equal(t, nftypes.FlowOperationStatusCompleted, capture.FlowOperationStatus) - flush, err := s.c.StartFlowFlush(bg, &networkfirewall.StartFlowFlushInput{FirewallArn: aws.String(s.fwARN), AvailabilityZone: aws.String("us-east-1a"), FlowFilters: []nftypes.FlowFilter{{SourcePort: aws.String("80")}}}) + flush, err := s.c.StartFlowFlush(bg, &networkfirewall.StartFlowFlushInput{FirewallArn: aws.String(s.fwARN), AvailabilityZone: aws.String("us-east-1c"), FlowFilters: []nftypes.FlowFilter{{SourcePort: aws.String("80")}}}) require.NoError(t, err) d, err := s.c.DescribeFlowOperation(bg, &networkfirewall.DescribeFlowOperationInput{ - FirewallArn: aws.String(s.fwARN), AvailabilityZone: aws.String("us-east-1a"), FlowOperationId: capture.FlowOperationId, + FirewallArn: aws.String(s.fwARN), AvailabilityZone: aws.String("us-east-1c"), FlowOperationId: capture.FlowOperationId, }) require.NoError(t, err) assert.Equal(t, nftypes.FlowOperationTypeFlowCapture, d.FlowOperationType) assert.NotNil(t, d.FlowRequestTimestamp) ops, err := s.c.ListFlowOperations(bg, &networkfirewall.ListFlowOperationsInput{ - FirewallArn: aws.String(s.fwARN), AvailabilityZone: aws.String("us-east-1a"), FlowOperationType: nftypes.FlowOperationTypeFlowFlush, + FirewallArn: aws.String(s.fwARN), AvailabilityZone: aws.String("us-east-1c"), FlowOperationType: nftypes.FlowOperationTypeFlowFlush, }) require.NoError(t, err) require.Len(t, ops.FlowOperations, 1) assert.Equal(t, aws.ToString(flush.FlowOperationId), aws.ToString(ops.FlowOperations[0].FlowOperationId)) res, err := s.c.ListFlowOperationResults(bg, &networkfirewall.ListFlowOperationResultsInput{ - FirewallArn: aws.String(s.fwARN), AvailabilityZone: aws.String("us-east-1a"), FlowOperationId: capture.FlowOperationId, + FirewallArn: aws.String(s.fwARN), AvailabilityZone: aws.String("us-east-1c"), FlowOperationId: capture.FlowOperationId, }) require.NoError(t, err) assert.Empty(t, res.Flows, "no data plane, no flows") @@ -706,3 +706,111 @@ func TestSDK_DescribeByARN_And_Deletes(t *testing.T) { _, err = s.c.CreateRuleGroup(bg, &networkfirewall.CreateRuleGroupInput{RuleGroupName: aws.String("dup"), Type: nftypes.RuleGroupTypeStateful, Capacity: aws.Int32(1)}) require.ErrorAs(t, err, &invalid, "a duplicate name is InvalidRequestException") } + +func TestSDK_SubnetMapping_IPAddressType_Echoed(t *testing.T) { + s := newStack(t) + + created, err := s.c.CreateFirewall(bg, &networkfirewall.CreateFirewallInput{ + FirewallName: aws.String("fw-ip"), FirewallPolicyArn: aws.String(s.policyARN), VpcId: aws.String("vpc-1a"), + SubnetMappings: []nftypes.SubnetMapping{{SubnetId: aws.String("subnet-9"), IPAddressType: nftypes.IPAddressTypeIpv4}}, + }) + require.NoError(t, err) + require.Len(t, created.Firewall.SubnetMappings, 1) + assert.Equal(t, nftypes.IPAddressTypeIpv4, created.Firewall.SubnetMappings[0].IPAddressType) + + assoc, err := s.c.AssociateSubnets(bg, &networkfirewall.AssociateSubnetsInput{ + FirewallName: aws.String("fw-ip"), + SubnetMappings: []nftypes.SubnetMapping{{SubnetId: aws.String("subnet-8"), IPAddressType: nftypes.IPAddressTypeDualstack}}, + }) + require.NoError(t, err) + + got := map[string]nftypes.IPAddressType{} + for _, m := range assoc.SubnetMappings { + got[aws.ToString(m.SubnetId)] = m.IPAddressType + } + + assert.Equal(t, nftypes.IPAddressTypeIpv4, got["subnet-9"]) + assert.Equal(t, nftypes.IPAddressTypeDualstack, got["subnet-8"]) + + d, err := s.c.DescribeFirewall(bg, &networkfirewall.DescribeFirewallInput{FirewallName: aws.String("fw-ip")}) + require.NoError(t, err) + assert.Len(t, d.Firewall.SubnetMappings, 2) +} + +func TestSDK_SyncStates_ZoneIsStable_FlowCaptureAcceptsIt(t *testing.T) { + s := newStack(t) + + _, err := s.c.CreateFirewall(bg, &networkfirewall.CreateFirewallInput{ + FirewallName: aws.String("fw-z"), FirewallPolicyArn: aws.String(s.policyARN), VpcId: aws.String("vpc-1a"), + SubnetMappings: []nftypes.SubnetMapping{{SubnetId: aws.String("subnet-a")}, {SubnetId: aws.String("subnet-b")}}, + }) + require.NoError(t, err) + + zoneOf := func(subnet string) (string, string) { + d, derr := s.c.DescribeFirewall(bg, &networkfirewall.DescribeFirewallInput{FirewallName: aws.String("fw-z")}) + require.NoError(t, derr) + + for az, st := range d.FirewallStatus.SyncStates { + if aws.ToString(st.Attachment.SubnetId) == subnet { + return az, aws.ToString(st.Attachment.EndpointId) + } + } + + return "", "" + } + + azA, epA := zoneOf("subnet-a") + azB, epB := zoneOf("subnet-b") + require.NotEmpty(t, azA) + require.NotEmpty(t, azB) + assert.NotEqual(t, azA, azB) + assert.NotEqual(t, epA, epB, "each zone has its own endpoint") + + _, err = s.c.DisassociateSubnets(bg, &networkfirewall.DisassociateSubnetsInput{ + FirewallName: aws.String("fw-z"), SubnetIds: []string{"subnet-a"}, + }) + require.NoError(t, err) + + azB2, epB2 := zoneOf("subnet-b") + assert.Equal(t, azB, azB2, "the remaining subnet keeps its zone") + assert.Equal(t, epB, epB2) + + _, err = s.c.StartFlowCapture(bg, &networkfirewall.StartFlowCaptureInput{ + FirewallArn: aws.String(arnOfFirewall(t, s, "fw-z")), AvailabilityZone: aws.String(azB), + FlowFilters: []nftypes.FlowFilter{{SourcePort: aws.String("80")}}, + }) + require.NoError(t, err) +} + +func arnOfFirewall(t *testing.T, s *stack, name string) string { + t.Helper() + + d, err := s.c.DescribeFirewall(bg, &networkfirewall.DescribeFirewallInput{FirewallName: aws.String(name)}) + require.NoError(t, err) + + return aws.ToString(d.Firewall.FirewallArn) +} + +func TestSDK_RuleGroup_DomainNameClash_And_MissingType(t *testing.T) { + s := newStack(t) + + _, err := s.c.CreateRuleGroup(bg, &networkfirewall.CreateRuleGroupInput{ + RuleGroupName: aws.String("dup"), Type: nftypes.RuleGroupTypeStateful, Capacity: aws.Int32(10), + }) + require.NoError(t, err) + + _, err = s.c.CreateRuleGroup(bg, &networkfirewall.CreateRuleGroupInput{ + RuleGroupName: aws.String("dup"), Type: nftypes.RuleGroupTypeStatefulDomain, Capacity: aws.Int32(10), + }) + + var invalid *nftypes.InvalidRequestException + require.ErrorAs(t, err, &invalid) + + _, err = s.c.CreateRuleGroup(bg, &networkfirewall.CreateRuleGroupInput{ + RuleGroupName: aws.String("dup"), Type: nftypes.RuleGroupTypeStateless, Capacity: aws.Int32(10), + }) + require.NoError(t, err) + + _, err = s.c.DescribeRuleGroup(bg, &networkfirewall.DescribeRuleGroupInput{RuleGroupName: aws.String("dup")}) + require.ErrorAs(t, err, &invalid) +} diff --git a/services/networkfirewall/driver/availability_zones.go b/services/networkfirewall/driver/availability_zones.go deleted file mode 100644 index 71870263e..000000000 --- a/services/networkfirewall/driver/availability_zones.go +++ /dev/null @@ -1,43 +0,0 @@ -package driver - -import "hash/fnv" - -// azLetters are the zone suffixes used to give a firewall's subnets stable, -// synthetic Availability Zone names (the emulator has no real subnet to AZ -// mapping). -const azLetters = "abcdef" - -// AvailabilityZoneFor returns the synthetic Availability Zone name for the -// index-th subnet of a firewall in region (index 0 -> "a"). -func AvailabilityZoneFor(region string, index int) string { - if index < 0 { - index = -index - } - - return region + string(azLetters[index%len(azLetters)]) -} - -// SyncZones returns the Availability Zones a firewall runs in: its explicit -// zones for a transit gateway-attached firewall, else one synthetic zone per -// subnet. -func SyncZones(f *Firewall, region string) []string { - if len(f.AvailabilityZones) > 0 { - return append([]string(nil), f.AvailabilityZones...) - } - - zones := make([]string, 0, len(f.SubnetIDs)) - for i := range f.SubnetIDs { - zones = append(zones, AvailabilityZoneFor(region, i)) - } - - return zones -} - -// ZoneForKey returns a stable synthetic Availability Zone name for an opaque key -// (a subnet id): the same key always maps to the same zone. -func ZoneForKey(region, key string) string { - h := fnv.New32a() - _, _ = h.Write([]byte(key)) - - return AvailabilityZoneFor(region, int(h.Sum32()%uint32(len(azLetters)))) -} diff --git a/services/networkfirewall/driver/driver.go b/services/networkfirewall/driver/driver.go index d95f9bf4e..373b21f21 100644 --- a/services/networkfirewall/driver/driver.go +++ b/services/networkfirewall/driver/driver.go @@ -22,6 +22,7 @@ type Firewall struct { PolicyARN string VPCID string SubnetIDs []string + SubnetDetails map[string]SubnetDetail AvailabilityZones []string TransitGatewayID string Description string @@ -36,12 +37,31 @@ type Firewall struct { Tags map[string]string } -// CreateFirewallConfig is the input to CreateFirewall. +// SubnetMapping names a subnet to attach a firewall to, with the optional IP +// address type AWS lets a caller pick per subnet. +type SubnetMapping struct { + SubnetID string + IPAddressType string +} + +// SubnetDetail is what the firewall records for each attached subnet: its IP +// address type, the Availability Zone it sits in and that zone's endpoint id. +// The zone and endpoint are assigned when the subnet is attached and never move +// while it stays attached. +type SubnetDetail struct { + IPAddressType string + AvailabilityZone string + EndpointID string +} + +// CreateFirewallConfig is the input to CreateFirewall. SubnetIPTypes optionally +// maps a subnet id in SubnetIDs to its IP address type. type CreateFirewallConfig struct { Name string PolicyARN string VPCID string SubnetIDs []string + SubnetIPTypes map[string]string AvailabilityZones []string TransitGatewayID string Description string @@ -233,7 +253,7 @@ type NetworkFirewall interface { ListRuleGroups(ctx context.Context, filter RuleGroupFilter, opts ListOptions) ([]RuleGroup, string, error) AssociateFirewallPolicy(ctx context.Context, firewallName, policyARN, updateToken string) (*Firewall, error) - AssociateSubnets(ctx context.Context, firewallName string, subnetIDs []string, updateToken string) (*Firewall, error) + AssociateSubnets(ctx context.Context, firewallName string, subnets []SubnetMapping, updateToken string) (*Firewall, error) DisassociateSubnets(ctx context.Context, firewallName string, subnetIDs []string, updateToken string) (*Firewall, error) UpdateFirewallDeleteProtection(ctx context.Context, firewallName string, enabled bool, updateToken string) (*Firewall, error) UpdateLoggingConfiguration(ctx context.Context, firewallName string, cfg *LoggingConfiguration) error