Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement the aws waf import source (#110811)

Tom Owers33ddab80e59e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index ed65e52a6716..f0134539c223 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -110,6 +110,7 @@ the row lists both.
| aws_organizations | HTTP | requests | ✅ |
| aws_security_hub | HTTP | requests | ✅ |
| aws_ses | HTTP | requests | ✅ |
+| aws_waf | HTTP | requests | ✅ |
| azure_cost_management | HTTP | requests | ✅ |
| azure_devops | HTTP | requests | ✅ |
| babelforce | HTTP | requests | ✅ |
@@ -933,7 +934,6 @@ doesn't conflict with concurrent PRs.
- aws_support
- aws_systems_manager
- aws_trusted_advisor
-- aws_waf
- aws_xray
- axiom
- azure_activity_log
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_waf/aws_waf.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_waf/aws_waf.py
new file mode 100644
index 000000000000..1c44c1c25d98
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_waf/aws_waf.py
@@ -0,0 +1,222 @@
+import re
+import json
+from collections.abc import Iterator
+from typing import TYPE_CHECKING, Any
+
+import requests
+from botocore.auth import SigV4Auth
+from botocore.awsrequest import AWSRequest
+from botocore.credentials import Credentials
+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from urllib3.exceptions import InvalidHeader
+from urllib3.util.retry import Retry
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_waf.settings import (
+ ACCESS_DENIED_CODES,
+ AWS_WAF_ENDPOINTS,
+ ERROR_MESSAGES,
+ PAGE_SIZE,
+ TARGET_PREFIX,
+ WAF_API_VERSION,
+ WafEndpoint,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awswaf import AwsWafSourceConfig
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+
+@frozen
+class AwsWafResumeConfig:
+ next_marker: str | None = None
+
+
+class AwsWafError(Exception):
+ def __init__(self, code: str, message: str) -> None:
+ super().__init__(f"AWS WAF request failed: {code} - {message}")
+ self.code = code
+
+
+class AwsWafRetryableError(AwsWafError):
+ def __init__(self, code: str, message: str, retry_after: float = 0) -> None:
+ super().__init__(code, message)
+ self.retry_after = retry_after
+
+
+def error_for_response(response: requests.Response) -> AwsWafError:
+ try:
+ body = response.json()
+ except ValueError:
+ body = {}
+ if not isinstance(body, dict):
+ body = {}
+ raw_code = response.headers.get("x-amzn-ErrorType") or body.get("__type") or body.get("code")
+ code = str(raw_code or f"HTTP {response.status_code}").split(":")[0].rsplit("#", 1)[-1]
+ message = str(body.get("message") or body.get("Message") or "AWS could not complete the request.")[:500]
+ if (
+ response.status_code == 429
+ or response.status_code >= 500
+ or (response.status_code == 400 and code in {"ThrottlingException", "Throttling", "RequestLimitExceeded"})
+ ):
+ retry_after = 0.0
+ if header := response.headers.get("Retry-After"):
+ try:
+ retry_after = min(Retry().parse_retry_after(header), 60)
+ except InvalidHeader:
+ pass
+ return AwsWafRetryableError(code, message, retry_after)
+ return AwsWafError(code, message)
+
+
+def retry_wait(state: RetryCallState) -> float:
+ error = state.outcome.exception() if state.outcome else None
+ delay = wait_exponential_jitter(initial=1, max=60)(state)
+ return max(delay, error.retry_after) if isinstance(error, AwsWafRetryableError) else delay
+
+
+class AwsWafClient:
+ def __init__(self, config: AwsWafSourceConfig, api_version: str = WAF_API_VERSION) -> None:
+ if api_version != WAF_API_VERSION:
+ raise ValueError(f"Unsupported AWS WAF API version: {api_version}")
+ if not config.aws_access_key_id or not config.aws_secret_access_key:
+ raise ValueError("Enter both an AWS access key ID and a secret access key.")
+ if config.scope not in {"REGIONAL", "CLOUDFRONT"}:
+ raise ValueError("Select REGIONAL or CLOUDFRONT for the AWS WAF scope.")
+ if not re.fullmatch(r"[a-z]{2}(?:-[a-z]+)+-\d+", config.aws_region):
+ raise ValueError("Enter an AWS region name, such as us-east-1.")
+ self.scope = config.scope
+ self.region = "us-east-1" if self.scope == "CLOUDFRONT" else config.aws_region
+ suffix = "amazonaws.com.cn" if self.region.startswith("cn-") else "amazonaws.com"
+ self.url = f"https://wafv2.{self.region}.{suffix}/"
+ self.signer = SigV4Auth(
+ Credentials(config.aws_access_key_id, config.aws_secret_access_key, config.aws_session_token or None),
+ "wafv2",
+ self.region,
+ )
+ # WAF can throttle with HTTP 400, so one retry layer handles both HTTP statuses and AWS error codes.
+ self.session = make_tracked_session(
+ retry=Retry(total=0),
+ redact_values=tuple(value for value in (config.aws_secret_access_key, config.aws_session_token) if value),
+ )
+
+ def close(self) -> None:
+ self.session.close()
+
+ @retry(
+ retry=retry_if_exception_type((AwsWafRetryableError, requests.ConnectionError, requests.Timeout)),
+ stop=stop_after_attempt(5),
+ wait=retry_wait,
+ reraise=True,
+ )
+ def request(self, operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ body = json.dumps(payload).encode("utf-8")
+ request = AWSRequest(
+ method="POST",
+ url=self.url,
+ data=body,
+ headers={"Content-Type": "application/x-amz-json-1.1", "X-Amz-Target": f"{TARGET_PREFIX}.{operation}"},
+ )
+ self.signer.add_auth(request)
+ response = self.session.post(
+ self.url, data=body, headers=dict(request.headers), timeout=60, allow_redirects=False
+ )
+ if response.status_code != 200:
+ raise error_for_response(response)
+ return response.json()
+
+ def get_resource(self, endpoint: WafEndpoint, summary: dict[str, Any]) -> dict[str, Any]:
+ result = self.request(
+ endpoint.get_operation, {"Scope": self.scope, "Id": summary["Id"], "Name": summary["Name"]}
+ )
+ resource = result[endpoint.object_key]
+ row = {
+ re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "_", key).lower(): value
+ for key, value in resource.items()
+ }
+ row["region"] = self.region
+ row["scope"] = self.scope
+ return row
+
+
+def validate_credentials(
+ config: AwsWafSourceConfig, schema_name: str | None = None, api_version: str = WAF_API_VERSION
+) -> tuple[bool, str | None]:
+ endpoint = AWS_WAF_ENDPOINTS.get(schema_name or "web_acls")
+ if endpoint is None:
+ return False, f"Unknown AWS WAF table: {schema_name}"
+ try:
+ client = AwsWafClient(config, api_version)
+ except ValueError as error:
+ return False, str(error)
+ try:
+ result = client.request(endpoint.list_operation, {"Scope": client.scope, "Limit": 1})
+ if schema_name and result[endpoint.list_key]:
+ client.get_resource(endpoint, result[endpoint.list_key][0])
+ except AwsWafError as error:
+ if error.code in ACCESS_DENIED_CODES:
+ if schema_name is None:
+ return True, None
+ return False, f"Grant wafv2:{endpoint.list_operation} and wafv2:{endpoint.get_operation} for this table."
+ if error.code in ERROR_MESSAGES:
+ return False, ERROR_MESSAGES[error.code]
+ raise
+ finally:
+ client.close()
+ return True, None
+
+
+def get_rows(
+ config: AwsWafSourceConfig,
+ endpoint: WafEndpoint,
+ manager: "ResumableSourceManager[AwsWafResumeConfig]",
+ api_version: str,
+) -> Iterator[list[dict[str, Any]]]:
+ state = manager.load_state() or AwsWafResumeConfig()
+ client = AwsWafClient(config, api_version)
+ marker = state.next_marker
+ try:
+ while True:
+ payload: dict[str, Any] = {"Scope": client.scope, "Limit": PAGE_SIZE}
+ if marker:
+ payload["NextMarker"] = marker
+ result = client.request(endpoint.list_operation, payload)
+ rows = []
+ for summary in result[endpoint.list_key]:
+ try:
+ rows.append(client.get_resource(endpoint, summary))
+ except AwsWafError as error:
+ if error.code != "WAFNonexistentItemException":
+ raise
+ next_marker = result.get("NextMarker") or None
+ if next_marker and next_marker == marker:
+ raise ValueError("AWS WAF returned a repeated pagination marker.")
+ manager.save_state(AwsWafResumeConfig(next_marker=next_marker))
+ if rows:
+ yield rows
+ manager.safe_point()
+ if next_marker is None:
+ break
+ marker = next_marker
+ finally:
+ client.close()
+
+
+def aws_waf_source(
+ config: AwsWafSourceConfig,
+ endpoint: str,
+ manager: "ResumableSourceManager[AwsWafResumeConfig]",
+ api_version: str = WAF_API_VERSION,
+) -> SourceResponse:
+ if endpoint not in AWS_WAF_ENDPOINTS:
+ raise ValueError(f"Unknown AWS WAF table: {endpoint}")
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(config, AWS_WAF_ENDPOINTS[endpoint], manager, api_version),
+ primary_keys=["arn"],
+ sort_mode=None,
+ on_complete=manager.clear_state,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_waf/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_waf/canonical_descriptions.py
new file mode 100644
index 000000000000..83df2bfe9a72
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_waf/canonical_descriptions.py
@@ -0,0 +1,56 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+COMMON_COLUMNS = {
+ "arn": "Amazon Resource Name that uniquely identifies the resource.",
+ "id": "Identifier assigned by AWS WAF when the resource is created.",
+ "name": "Resource name assigned at creation.",
+ "description": "Description of the resource.",
+ "region": "AWS region used to read the resource. CloudFront resources use us-east-1.",
+ "scope": "Resource scope: REGIONAL or CLOUDFRONT.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "web_acls": {
+ "description": "Web access control lists that inspect requests to protected AWS resources.",
+ "docs_url": "https://docs.aws.amazon.com/waf/latest/APIReference/API_GetWebACL.html",
+ "columns": {
+ **COMMON_COLUMNS,
+ "rules": "Rules that inspect and control web requests.",
+ "default_action": "Action applied when no rule determines the request action.",
+ "capacity": "Web ACL capacity units used by the rules.",
+ "visibility_config": "Settings for CloudWatch metrics and request sampling.",
+ "managed_by_firewall_manager": "Whether AWS Firewall Manager manages the web ACL.",
+ },
+ },
+ "rule_groups": {
+ "description": "Reusable groups of rules that you manage for web request inspection.",
+ "docs_url": "https://docs.aws.amazon.com/waf/latest/APIReference/API_GetRuleGroup.html",
+ "columns": {
+ **COMMON_COLUMNS,
+ "rules": "Rules included in the group.",
+ "capacity": "Web ACL capacity units reserved for the rule group.",
+ "visibility_config": "Settings for CloudWatch metrics and request sampling.",
+ "available_labels": "Labels that rules in this group can add to matching requests.",
+ "consumed_labels": "Labels that rules in this group can match.",
+ },
+ },
+ "ip_sets": {
+ "description": "Reusable IP address sets referenced by web ACL rules and rule groups.",
+ "docs_url": "https://docs.aws.amazon.com/waf/latest/APIReference/API_GetIPSet.html",
+ "columns": {
+ **COMMON_COLUMNS,
+ "ip_address_version": "IP address family: IPV4 or IPV6.",
+ "addresses": "IP addresses and ranges in CIDR notation.",
+ },
+ },
+ "regex_pattern_sets": {
+ "description": "Reusable sets of regular expressions for web request inspection.",
+ "docs_url": "https://docs.aws.amazon.com/waf/latest/APIReference/API_GetRegexPatternSet.html",
+ "columns": {
+ **COMMON_COLUMNS,
+ "regular_expression_list": "Regular expressions used to match web request components.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_waf/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_waf/settings.py
new file mode 100644
index 000000000000..04f172afb14c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_waf/settings.py
@@ -0,0 +1,67 @@
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+WAF_API_VERSION = "2019-07-29"
+TARGET_PREFIX = "AWSWAF_20190729"
+PAGE_SIZE = 100
+
+
+@frozen
+class WafEndpoint:
+ list_operation: str
+ list_key: str
+ get_operation: str
+ object_key: str
+ description: str
+
+
+AWS_WAF_ENDPOINTS: dict[str, WafEndpoint] = {
+ "web_acls": WafEndpoint(
+ list_operation="ListWebACLs",
+ list_key="WebACLs",
+ get_operation="GetWebACL",
+ object_key="WebACL",
+ description="Web access control lists, with their rules, default actions, and visibility settings.",
+ ),
+ "rule_groups": WafEndpoint(
+ list_operation="ListRuleGroups",
+ list_key="RuleGroups",
+ get_operation="GetRuleGroup",
+ object_key="RuleGroup",
+ description="Rule groups that you manage, with their rules and capacity settings.",
+ ),
+ "ip_sets": WafEndpoint(
+ list_operation="ListIPSets",
+ list_key="IPSets",
+ get_operation="GetIPSet",
+ object_key="IPSet",
+ description="IP sets with their IP version and address ranges in CIDR notation.",
+ ),
+ "regex_pattern_sets": WafEndpoint(
+ list_operation="ListRegexPatternSets",
+ list_key="RegexPatternSets",
+ get_operation="GetRegexPatternSet",
+ object_key="RegexPatternSet",
+ description="Sets of regular expressions that rules use to inspect web requests.",
+ ),
+}
+
+ENDPOINTS = tuple(AWS_WAF_ENDPOINTS)
+ENDPOINT_DESCRIPTIONS = {name: endpoint.description for name, endpoint in AWS_WAF_ENDPOINTS.items()}
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
+
+ACCESS_DENIED_CODES = frozenset({"AccessDenied", "AccessDeniedException", "WAFUnauthorizedOperationException"})
+ERROR_MESSAGES = {
+ "UnrecognizedClientException": "AWS rejected the access key. Check the access key ID and secret access key.",
+ "InvalidClientTokenId": "AWS rejected the access key. Check the access key ID and session token.",
+ "InvalidSignatureException": "AWS rejected the signature. Check the secret access key and session token.",
+ "SignatureDoesNotMatch": "AWS rejected the signature. Check the secret access key.",
+ "ExpiredTokenException": "The AWS session token has expired. Connect again with new credentials.",
+ "ExpiredToken": "The AWS session token has expired. Connect again with new credentials.",
+ "OptInRequired": "Enable AWS WAF for this account before you connect this source.",
+ "SubscriptionRequiredException": "Enable the required AWS subscription before you connect this source.",
+ **dict.fromkeys(
+ ACCESS_DENIED_CODES, "These credentials lack AWS WAF read permissions. Grant the listed wafv2 permissions."
+ ),
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_waf/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_waf/source.py
index fccb3f25c589..4777cf2a46ba 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_waf/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_waf/source.py
@@ -1,25 +1,160 @@
from typing import cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_waf.aws_waf import (
+ AwsWafResumeConfig,
+ aws_waf_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_waf.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_waf.settings import (
+ ENDPOINT_DESCRIPTIONS,
+ ENDPOINTS,
+ ERROR_MESSAGES,
+ INCREMENTAL_FIELDS,
+ WAF_API_VERSION,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awswaf import AwsWafSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AwsWafSource(SimpleSource[AwsWafSourceConfig]):
+class AwsWafSource(ResumableSource[AwsWafSourceConfig, AwsWafResumeConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = (WAF_API_VERSION,)
+ default_version = WAF_API_VERSION
+ api_docs_url = "https://docs.aws.amazon.com/waf/latest/APIReference/Welcome.html"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AWSWAF
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {f"AWS WAF request failed: {code}": message for code, message in ERROR_MESSAGES.items()}
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AwsWafSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, descriptions=ENDPOINT_DESCRIPTIONS)
+
+ def validate_credentials(
+ self,
+ config: AwsWafSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_credentials(config, schema_name, self.resolve_api_version(api_version))
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AwsWafResumeConfig]:
+ return ResumableSourceManager(inputs, AwsWafResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AwsWafSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AwsWafResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return aws_waf_source(
+ config, inputs.schema_name, resumable_source_manager, self.resolve_api_version(inputs.api_version)
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.AWSWAF,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="Amazon Web Services (AWS WAF)",
+ label="AWS WAF",
+ caption="""Sync AWS WAF configurations into the PostHog Data warehouse.
+
+Grant `wafv2:ListWebACLs` and `wafv2:GetWebACL` to sync web ACLs.
+Grant `wafv2:ListRuleGroups` and `wafv2:GetRuleGroup` to sync rule groups.
+Grant `wafv2:ListIPSets` and `wafv2:GetIPSet` to sync IP sets.
+Grant `wafv2:ListRegexPatternSets` and `wafv2:GetRegexPatternSet` to sync regex pattern sets.
+
+Select a region for regional resources. CloudFront resources use us-east-1.
+All tables use full refresh. This source imports configuration data only, without request samples or traffic logs.""",
iconPath="/static/services/aws_waf.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://docs.aws.amazon.com/waf/latest/APIReference/Welcome.html",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["aws", "waf", "firewall", "security"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="aws_access_key_id",
+ label="AWS access key ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="AKIA...",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="aws_secret_access_key",
+ label="AWS secret access key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="aws_session_token",
+ label="AWS session token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="Only needed for temporary credentials",
+ secret=True,
+ caption="Temporary credentials expire. Scheduled syncs fail after the session token expires.",
+ ),
+ SourceFieldInputConfig(
+ name="aws_region",
+ label="AWS region",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="us-east-1",
+ secret=False,
+ ),
+ SourceFieldSelectConfig(
+ name="scope",
+ label="Resource scope",
+ required=True,
+ defaultValue="REGIONAL",
+ options=[
+ SourceFieldSelectConfigOption(label="Regional", value="REGIONAL"),
+ SourceFieldSelectConfigOption(label="CloudFront", value="CLOUDFRONT"),
+ ],
+ caption="CloudFront resources always use us-east-1.",
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_waf/tests/test_aws_waf.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_waf/tests/test_aws_waf.py
new file mode 100644
index 000000000000..55ba2029fb75
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_waf/tests/test_aws_waf.py
@@ -0,0 +1,361 @@
+import json
+from collections.abc import Generator, Iterable, Iterator
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from tenacity import wait_none
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_waf.aws_waf import (
+ AwsWafClient,
+ AwsWafError,
+ AwsWafResumeConfig,
+ AwsWafRetryableError,
+ aws_waf_source,
+ error_for_response,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_waf.source import AwsWafSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awswaf import AwsWafSourceConfig
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.aws_waf.aws_waf"
+
+
+def config(**overrides: Any) -> AwsWafSourceConfig:
+ return AwsWafSourceConfig.from_dict(
+ {
+ "aws_access_key_id": "AKIAEXAMPLE",
+ "aws_secret_access_key": "example-secret",
+ "aws_session_token": "example-token",
+ "aws_region": "eu-west-1",
+ "scope": "REGIONAL",
+ **overrides,
+ }
+ )
+
+
+def response(body: object, status: int = 200, headers: dict[str, str] | None = None) -> requests.Response:
+ result = requests.Response()
+ result.status_code = status
+ result._content = json.dumps(body).encode()
+ result.headers.update(headers or {})
+ return result
+
+
+def session() -> Iterator[MagicMock]:
+ with patch(f"{MODULE}.make_tracked_session") as factory:
+ factory.return_value.post.return_value = response({"WebACLs": []})
+ yield factory.return_value
+
+
+def manager(state: AwsWafResumeConfig | None = None) -> MagicMock:
+ result = MagicMock(spec=ResumableSourceManager)
+ result.load_state.return_value = state
+ return result
+
+
+ "scope,region,host,signing_region",
+ [
+ ("REGIONAL", "eu-west-1", "wafv2.eu-west-1.amazonaws.com", "eu-west-1"),
+ ("CLOUDFRONT", "eu-west-1", "wafv2.us-east-1.amazonaws.com", "us-east-1"),
+ ("REGIONAL", "cn-north-1", "wafv2.cn-north-1.amazonaws.com.cn", "cn-north-1"),
+ ("REGIONAL", "us-gov-west-1", "wafv2.us-gov-west-1.amazonaws.com", "us-gov-west-1"),
+ ],
+)
[email protected]("token", [None, "example-token"])
+def test_signed_requests(
+ session: MagicMock, scope: str, region: str, host: str, signing_region: str, token: str | None
+) -> None:
+ assert validate_credentials(config(scope=scope, aws_region=region, aws_session_token=token)) == (True, None)
+ args, kwargs = session.post.call_args
+ assert args == (f"https://{host}/",)
+ assert json.loads(kwargs["data"]) == {"Scope": scope, "Limit": 1}
+ headers = kwargs["headers"]
+ assert headers["X-Amz-Target"] == "AWSWAF_20190729.ListWebACLs"
+ assert headers["Content-Type"] == "application/x-amz-json-1.1"
+ assert f"/{signing_region}/wafv2/aws4_request" in headers["Authorization"]
+ assert "x-amz-target" in headers["Authorization"]
+ assert headers["X-Amz-Date"]
+ assert headers.get("X-Amz-Security-Token") == token
+ assert kwargs["allow_redirects"] is False
+ assert kwargs["timeout"] == 60
+ session.close.assert_called_once()
+
+
+ "table,list_operation,list_key,get_operation,object_key,detail",
+ [
+ (
+ "web_acls",
+ "ListWebACLs",
+ "WebACLs",
+ "GetWebACL",
+ "WebACL",
+ {"Rules": [{"Name": "rule"}], "DefaultAction": {"Block": {}}},
+ ),
+ ("rule_groups", "ListRuleGroups", "RuleGroups", "GetRuleGroup", "RuleGroup", {"Capacity": 10, "Rules": []}),
+ (
+ "ip_sets",
+ "ListIPSets",
+ "IPSets",
+ "GetIPSet",
+ "IPSet",
+ {"IPAddressVersion": "IPV4", "Addresses": ["192.0.2.0/24"]},
+ ),
+ (
+ "regex_pattern_sets",
+ "ListRegexPatternSets",
+ "RegexPatternSets",
+ "GetRegexPatternSet",
+ "RegexPatternSet",
+ {"RegularExpressionList": [{"RegexString": "example"}]},
+ ),
+ ],
+)
+def test_full_refresh_pagination_and_details(
+ session: MagicMock,
+ table: str,
+ list_operation: str,
+ list_key: str,
+ get_operation: str,
+ object_key: str,
+ detail: dict[str, Any],
+) -> None:
+ summary = {"Id": "00000000-0000-0000-0000-000000000001", "Name": "example"}
+ resource = {**summary, "ARN": f"arn:aws:wafv2:eu-west-1:123456789012:regional/{table}/example/id", **detail}
+ session.post.side_effect = [
+ response({list_key: [], "NextMarker": "page-2"}),
+ response({list_key: [summary], "NextMarker": "page-3"}),
+ response({object_key: resource, "LockToken": "unused"}),
+ response({list_key: [{**summary, "Name": "terminal"}]}),
+ response({object_key: {**resource, "ARN": resource["ARN"] + "2", "Name": "terminal"}}),
+ ]
+ resume = manager()
+ stream = aws_waf_source(config(), table, resume)
+ batches = list(cast(Iterable[list[dict[str, Any]]], stream.items()))
+ assert [row["name"] for batch in batches for row in batch] == ["example", "terminal"]
+ row = batches[0][0]
+ assert row["arn"] == resource["ARN"]
+ assert row["region"] == "eu-west-1"
+ assert row["scope"] == "REGIONAL"
+ assert "lock_token" not in row
+ if table == "web_acls":
+ assert row["default_action"] == {"Block": {}}
+ assert row["rules"] == [{"Name": "rule"}]
+ elif table == "ip_sets":
+ assert row["ip_address_version"] == "IPV4"
+ assert row["addresses"] == ["192.0.2.0/24"]
+ elif table == "regex_pattern_sets":
+ assert row["regular_expression_list"] == [{"RegexString": "example"}]
+ else:
+ assert row["capacity"] == 10
+ requests_sent = [call.kwargs for call in session.post.call_args_list]
+ assert [request["headers"]["X-Amz-Target"] for request in requests_sent] == [
+ f"AWSWAF_20190729.{operation}"
+ for operation in [list_operation, list_operation, get_operation, list_operation, get_operation]
+ ]
+ assert [json.loads(request["data"]) for request in requests_sent] == [
+ {"Scope": "REGIONAL", "Limit": 100},
+ {"Scope": "REGIONAL", "Limit": 100, "NextMarker": "page-2"},
+ {"Scope": "REGIONAL", **summary},
+ {"Scope": "REGIONAL", "Limit": 100, "NextMarker": "page-3"},
+ {"Scope": "REGIONAL", **summary, "Name": "terminal"},
+ ]
+ assert [call.args[0] for call in resume.save_state.call_args_list] == [
+ AwsWafResumeConfig(next_marker="page-2"),
+ AwsWafResumeConfig(next_marker="page-3"),
+ AwsWafResumeConfig(),
+ ]
+ assert resume.safe_point.call_count == 3
+ resume.clear_state.assert_not_called()
+ assert stream.on_complete is not None
+ stream.on_complete()
+ resume.clear_state.assert_called_once()
+
+
[email protected]("marker", ["saved-page", None])
+def test_resume_from_checkpoint(session: MagicMock, marker: str | None) -> None:
+ resume = manager(AwsWafResumeConfig(next_marker=marker))
+ assert list(cast(Iterable[Any], aws_waf_source(config(), "web_acls", resume).items())) == []
+ payload = json.loads(session.post.call_args.kwargs["data"])
+ if marker:
+ assert payload["NextMarker"] == marker
+ else:
+ assert "NextMarker" not in payload
+ resume.save_state.assert_called_once_with(AwsWafResumeConfig())
+ resume.safe_point.assert_called_once()
+
+
+def test_checkpoint_is_staged_before_yield(session: MagicMock) -> None:
+ session.post.side_effect = [
+ response({"WebACLs": [{"Name": "example", "Id": "id"}], "NextMarker": "next"}),
+ response({"WebACL": {"ARN": "arn:example", "Name": "example", "Id": "id"}}),
+ ]
+ resume = manager()
+ rows = cast(Generator[list[dict[str, Any]]], aws_waf_source(config(), "web_acls", resume).items())
+ assert next(rows)[0]["arn"] == "arn:example"
+ resume.save_state.assert_called_once_with(AwsWafResumeConfig(next_marker="next"))
+ rows.close()
+ resume.clear_state.assert_not_called()
+ session.close.assert_called_once()
+
+
[email protected]("error_code", ["WAFNonexistentItemException", "AccessDeniedException"])
+def test_resource_deleted_or_denied_during_sync(session: MagicMock, error_code: str) -> None:
+ session.post.side_effect = [
+ response({"IPSets": [{"Name": "example", "Id": "id"}]}),
+ response({"__type": error_code}, 400),
+ ]
+ resume = manager()
+ stream = aws_waf_source(config(), "ip_sets", resume)
+ if error_code == "WAFNonexistentItemException":
+ assert list(cast(Iterable[Any], stream.items())) == []
+ resume.save_state.assert_called_once_with(AwsWafResumeConfig())
+ resume.safe_point.assert_called_once()
+ else:
+ with pytest.raises(AwsWafError, match=error_code):
+ list(cast(Iterable[Any], stream.items()))
+ resume.save_state.assert_not_called()
+ session.close.assert_called_once()
+
+
+def test_repeated_marker_fails_without_advancing_checkpoint(session: MagicMock) -> None:
+ session.post.return_value = response({"WebACLs": [], "NextMarker": "saved"})
+ resume = manager(AwsWafResumeConfig(next_marker="saved"))
+ with pytest.raises(ValueError, match="repeated pagination marker"):
+ list(cast(Iterable[Any], aws_waf_source(config(), "web_acls", resume).items()))
+ resume.save_state.assert_not_called()
+
+
[email protected]("schema", [None, "ip_sets"])
[email protected]("code", ["AccessDenied", "AccessDeniedException", "WAFUnauthorizedOperationException"])
+def test_missing_permissions_at_creation_or_schema_probe(session: MagicMock, schema: str | None, code: str) -> None:
+ session.post.return_value = response({"__type": f"com.amazonaws.wafv2#{code}"}, 400)
+ valid, reason = validate_credentials(config(), schema)
+ assert valid is (schema is None)
+ if schema:
+ assert reason == "Grant wafv2:ListIPSets and wafv2:GetIPSet for this table."
+ else:
+ assert reason is None
+ assert session.post.call_count == 1
+
+
+def test_schema_probe_checks_detail_permission(session: MagicMock) -> None:
+ session.post.side_effect = [
+ response({"IPSets": [{"Id": "id", "Name": "example"}]}),
+ response({"__type": "AccessDeniedException"}, 400),
+ ]
+ valid, reason = validate_credentials(config(), "ip_sets")
+ assert not valid
+ assert reason and "wafv2:GetIPSet" in reason
+ assert json.loads(session.post.call_args.kwargs["data"]) == {"Scope": "REGIONAL", "Id": "id", "Name": "example"}
+
+
+ "code,expected",
+ [
+ ("UnrecognizedClientException", "access key"),
+ ("InvalidClientTokenId", "access key"),
+ ("InvalidSignatureException", "signature"),
+ ("SignatureDoesNotMatch", "signature"),
+ ("ExpiredTokenException", "expired"),
+ ("ExpiredToken", "expired"),
+ ("OptInRequired", "Enable AWS WAF"),
+ ("SubscriptionRequiredException", "subscription"),
+ ],
+)
+def test_credential_errors_are_actionable_and_non_retryable(session: MagicMock, code: str, expected: str) -> None:
+ error_response = response({"__type": code, "Message": "AWS rejected this request."}, 400)
+ session.post.return_value = error_response
+ valid, reason = validate_credentials(config())
+ assert not valid and reason and expected in reason
+ error = error_for_response(error_response)
+ mapped = [
+ message for pattern, message in AwsWafSource().get_non_retryable_errors().items() if pattern in str(error)
+ ]
+ assert mapped and all(message and expected in message for message in mapped)
+ assert session.post.call_count == 1
+
+
+ "status,body,headers,code,retryable",
+ [
+ (400, {"__type": "aws#ThrottlingException"}, {}, "ThrottlingException", True),
+ (429, {}, {"Retry-After": "3"}, "HTTP 429", True),
+ (500, {"__type": "WAFInternalErrorException"}, {}, "WAFInternalErrorException", True),
+ (503, "unavailable", {}, "HTTP 503", True),
+ (400, {"__type": "WAFInvalidParameterException"}, {}, "WAFInvalidParameterException", False),
+ (403, {}, {"x-amzn-ErrorType": "AccessDeniedException:http"}, "AccessDeniedException", False),
+ (302, {}, {}, "HTTP 302", False),
+ ],
+)
+def test_error_classification(status: int, body: object, headers: dict[str, str], code: str, retryable: bool) -> None:
+ error = error_for_response(response(body, status, headers))
+ assert error.code == code
+ assert isinstance(error, AwsWafRetryableError) is retryable
+ if status == 429:
+ assert isinstance(error, AwsWafRetryableError) and error.retry_after == 3
+
+
[email protected]("status,code", [(400, "ThrottlingException"), (429, "TooManyRequests"), (503, "Unavailable")])
+def test_transient_errors_retry_without_transport_retry(session: MagicMock, status: int, code: str) -> None:
+ session.post.side_effect = [response({"__type": code}, status), response({"WebACLs": []})]
+ client = AwsWafClient(config())
+ request = client.request.retry_with(wait=wait_none()) # type: ignore[attr-defined]
+ assert request(client, "ListWebACLs", {"Scope": "REGIONAL", "Limit": 1}) == {"WebACLs": []}
+ assert session.post.call_count == 2
+
+
+def test_retries_stop_after_five_attempts(session: MagicMock) -> None:
+ session.post.return_value = response({"__type": "ThrottlingException"}, 400)
+ client = AwsWafClient(config())
+ request = client.request.retry_with(wait=wait_none()) # type: ignore[attr-defined]
+ with pytest.raises(AwsWafRetryableError, match="ThrottlingException"):
+ request(client, "ListWebACLs", {"Scope": "REGIONAL", "Limit": 1})
+ assert session.post.call_count == 5
+
+
+def test_tracked_transport_redacts_secrets_and_disables_nested_retries() -> None:
+ with patch(f"{MODULE}.make_tracked_session") as factory:
+ AwsWafClient(config())
+ assert factory.call_args.kwargs["retry"].total == 0
+ assert set(factory.call_args.kwargs["redact_values"]) == {"example-secret", "example-token"}
+
+
+def test_service_errors_do_not_become_credential_failures(session: MagicMock) -> None:
+ session.post.return_value = response({"__type": "WAFInvalidParameterException"}, 400)
+ with pytest.raises(AwsWafError, match="WAFInvalidParameterException"):
+ validate_credentials(config())
+ session.close.assert_called_once()
+
+
+ "overrides,expected",
+ [
+ ({"aws_access_key_id": ""}, "access key ID"),
+ ({"aws_secret_access_key": ""}, "secret access key"),
+ ({"scope": "invalid"}, "scope"),
+ ({"aws_region": "us-east-1.example.com"}, "region"),
+ ({"aws_region": "https://example.com"}, "region"),
+ ],
+)
+def test_invalid_configuration_does_not_send_credentials(
+ session: MagicMock, overrides: dict[str, str], expected: str
+) -> None:
+ valid, reason = validate_credentials(config(**overrides))
+ assert not valid and reason and expected in reason
+ session.post.assert_not_called()
+
+
+def test_unknown_schema_and_api_version_fail_before_requests(session: MagicMock) -> None:
+ assert validate_credentials(config(), "unknown") == (False, "Unknown AWS WAF table: unknown")
+ valid, reason = validate_credentials(config(), api_version="2015-08-24")
+ assert not valid and reason and "Unsupported AWS WAF API version" in reason
+ with pytest.raises(ValueError, match="Unknown AWS WAF table"):
+ aws_waf_source(config(), "unknown", manager())
+ session.post.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awswaf.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awswaf.py
index ef5de2a11873..568fd8a7d55c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awswaf.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awswaf.py
@@ -1,9 +1,15 @@
# This file is automatically generated from `SourceRegistry.get_all_sources()`
# Do not edit manually - run `pnpm generate:source-configs` to regenerate.
+from typing import Literal
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
@config.config
class AwsWafSourceConfig(config.Config):
- pass
+ aws_access_key_id: str
+ aws_secret_access_key: str
+ aws_region: str
+ aws_session_token: str | None = None
+ scope: Literal["REGIONAL", "CLOUDFRONT"] = config.value(default="REGIONAL")