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 guardduty import source (#110799)

Tom Owers4e533890a771
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 488d25d0587e..21f317db309a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -109,6 +109,7 @@ the row lists both.
| aws_cost_anomaly_detection | HTTP | requests | ✅ |
| aws_cost_explorer | HTTP | requests | ✅ |
| aws_glue_data_catalog | HTTP | requests | ✅ |
+| aws_guardduty | HTTP | requests | ✅ |
| aws_iam_access_analyzer | HTTP | requests | ✅ |
| aws_inspector | HTTP | requests | ✅ |
| aws_macie | HTTP | requests | ✅ |
@@ -929,7 +930,6 @@ doesn't conflict with concurrent PRs.
- aws_config
- aws_connect
- aws_cost_and_usage_report
-- aws_guardduty
- aws_health
- aws_rds_performance_insights
- aws_support
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_guardduty/aws_guardduty.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_guardduty/aws_guardduty.py
new file mode 100644
index 000000000000..d7709a57e0fc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_guardduty/aws_guardduty.py
@@ -0,0 +1,320 @@
+import re
+import datetime as dt
+from collections.abc import Iterator
+from dataclasses import field, replace
+from typing import Any
+from urllib.parse import urlencode
+
+import requests
+from botocore.auth import SigV4Auth
+from botocore.awsrequest import AWSRequest
+from botocore.credentials import Credentials
+from botocore.serialize import create_serializer
+from botocore.session import get_session
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_guardduty.settings import (
+ ENDPOINTS,
+ ERROR_MESSAGES,
+ GUARDDUTY_API_VERSION,
+ MAX_RESULTS,
+)
+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.http.transport import BoundedRetry
+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 schema_for_resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsguardduty import (
+ AwsGuarddutySourceConfig,
+)
+
+TRANSPORT_RETRY = BoundedRetry(
+ total=3,
+ backoff_factor=1,
+ status_forcelist=(429, 500, 502, 503, 504),
+ allowed_methods=frozenset({"GET", "POST"}),
+ raise_on_status=False,
+)
+_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
+_REGION = re.compile(r"(?:us|eu|ap|sa|ca|me|af|il|mx|cn)-(?:gov-)?[a-z]+-\d+")
+_SORT_CRITERIA = {"AttributeName": "updatedAt", "OrderBy": "ASC"}
+
+
+@frozen
+class AwsGuarddutyResumeConfig:
+ detector_ids: list[str] = field(default_factory=list)
+ next_token: str | None = None
+ updated_since_ms: int | None = None
+
+
+class AwsGuarddutyError(Exception):
+ def __init__(self, code: str, message: str) -> None:
+ self.code = code
+ self.message = message
+ super().__init__(f"AWS GuardDuty request failed: {code} - {message}")
+
+
+class AwsGuarddutyThrottledError(AwsGuarddutyError):
+ pass
+
+
+def error_for_response(response: requests.Response) -> AwsGuarddutyError:
+ 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 ("AccessDenied" if response.status_code == 403 else f"HTTP {response.status_code}"))
+ code = code.split(":")[0].split("#")[-1]
+ message = str(body.get("message") or body.get("Message") or response.reason or "AWS request failed")[:500]
+ lower_message = message.lower()
+ if "not subscribed" in lower_message or (
+ "subscription" in lower_message and any(word in lower_message for word in ("required", "subscribe", "not"))
+ ):
+ code = "SubscriptionRequiredException"
+ # HTTP status retries belong to the tracked session; only body-level throttles need this retry.
+ error_class = (
+ AwsGuarddutyThrottledError
+ if response.status_code == 400 and code in {"ThrottlingException", "TooManyRequestsException"}
+ else AwsGuarddutyError
+ )
+ return error_class(code, message)
+
+
+class AwsGuarddutyClient:
+ def __init__(self, config: AwsGuarddutySourceConfig, api_version: str) -> None:
+ 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 not _REGION.fullmatch(config.aws_region):
+ raise ValueError("Enter a valid AWS region, such as us-east-1.")
+ if api_version != GUARDDUTY_API_VERSION:
+ raise ValueError(f"Unsupported AWS GuardDuty API version: {api_version}")
+ self.region = config.aws_region
+ suffix = "amazonaws.com.cn" if self.region.startswith("cn-") else "amazonaws.com"
+ self.base_url = f"https://guardduty.{self.region}.{suffix}"
+ # Pin the REST serializer to the service model because GuardDuty has no versioned URL or target header.
+ self._model = get_session().get_service_model("guardduty", api_version=api_version)
+ self._serializer = create_serializer(self._model.metadata["protocol"])
+ self._signer = SigV4Auth(
+ Credentials(config.aws_access_key_id, config.aws_secret_access_key, config.aws_session_token or None),
+ "guardduty",
+ self.region,
+ )
+ self._session = make_tracked_session(
+ retry=TRANSPORT_RETRY,
+ redact_values=tuple(
+ value
+ for value in (config.aws_access_key_id, config.aws_secret_access_key, config.aws_session_token)
+ if value
+ ),
+ )
+
+ def close(self) -> None:
+ self._session.close()
+
+ @retry(
+ retry=retry_if_exception_type(AwsGuarddutyThrottledError),
+ stop=stop_after_attempt(4),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def request(self, operation: str, payload: dict[str, Any]) -> dict[str, Any]:
+ serialized = self._serializer.serialize_to_request(payload, self._model.operation_model(operation))
+ url = self.base_url + serialized["url_path"]
+ if serialized["query_string"]:
+ url += "?" + urlencode(serialized["query_string"])
+ request = AWSRequest(
+ method=serialized["method"], url=url, data=serialized["body"], headers=serialized["headers"]
+ )
+ self._signer.add_auth(request)
+ response = self._session.request(
+ serialized["method"],
+ url,
+ data=serialized["body"],
+ headers=dict(request.headers),
+ timeout=60,
+ allow_redirects=False,
+ )
+ if response.status_code >= 300:
+ raise error_for_response(response)
+ body = response.json()
+ if not isinstance(body, dict):
+ raise ValueError("AWS GuardDuty returned an invalid response.")
+ return body
+
+ def detector_ids(self) -> Iterator[str]:
+ token: str | None = None
+ seen_tokens: set[str] = set()
+ while True:
+ payload: dict[str, Any] = {"MaxResults": MAX_RESULTS}
+ if token:
+ payload["NextToken"] = token
+ body = self.request("ListDetectors", payload)
+ yield from body.get("detectorIds", [])
+ next_token = body.get("nextToken")
+ if not next_token:
+ return
+ if next_token in seen_tokens:
+ raise ValueError("AWS GuardDuty repeated a page token.")
+ seen_tokens.add(next_token)
+ token = next_token
+
+
+def normalize_row(item: dict[str, Any], detector_id: str, region: str) -> dict[str, Any]:
+ row = {_CAMEL_BOUNDARY.sub("_", key).lower(): value for key, value in item.items()}
+ row["source_detector_id"] = detector_id
+ row["region"] = region
+ for column in ("created_at", "updated_at", "invited_at"):
+ value = row.get(column)
+ if isinstance(value, str) and value:
+ parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
+ row[column] = parsed if parsed.tzinfo else parsed.replace(tzinfo=dt.UTC)
+ return row
+
+
+def watermark_milliseconds(value: dt.datetime | str | None) -> int | None:
+ if value is None:
+ return None
+ parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00")) if isinstance(value, str) else value
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=dt.UTC)
+ return int(parsed.timestamp() * 1000)
+
+
+def get_rows(
+ config: AwsGuarddutySourceConfig,
+ endpoint: str,
+ api_version: str,
+ manager: ResumableSourceManager[AwsGuarddutyResumeConfig],
+ updated_since: dt.datetime | str | None,
+) -> Iterator[list[dict[str, Any]]]:
+ endpoint_config = schema_for_resource(ENDPOINTS, endpoint)
+ client = AwsGuarddutyClient(config, api_version)
+ try:
+ state = manager.load_state() if manager.can_resume() else None
+ if state is None:
+ state = AwsGuarddutyResumeConfig(
+ detector_ids=list(client.detector_ids()),
+ updated_since_ms=watermark_milliseconds(updated_since) if endpoint == "findings" else None,
+ )
+ seen_tokens = {state.next_token} if state.next_token else set()
+ while state.detector_ids:
+ detector_id = state.detector_ids[0]
+ payload: dict[str, Any] = {"DetectorId": detector_id}
+ if endpoint_config.result_key:
+ payload["MaxResults"] = MAX_RESULTS
+ if state.next_token:
+ payload["NextToken"] = state.next_token
+ if endpoint == "findings":
+ payload["SortCriteria"] = _SORT_CRITERIA
+ if state.updated_since_ms is not None:
+ payload["FindingCriteria"] = {
+ "Criterion": {"updatedAt": {"GreaterThanOrEqual": state.updated_since_ms}}
+ }
+ elif endpoint == "members":
+ payload["OnlyAssociated"] = "false"
+ body = client.request(endpoint_config.operation, payload)
+ next_token = body.get("nextToken")
+ if next_token and next_token in seen_tokens:
+ raise ValueError("AWS GuardDuty repeated a page token.")
+ if next_token:
+ seen_tokens.add(next_token)
+ else:
+ seen_tokens.clear()
+ if endpoint == "findings":
+ finding_ids = body.get("findingIds", [])
+ items = []
+ if finding_ids:
+ findings = client.request(
+ "GetFindings",
+ {"DetectorId": detector_id, "FindingIds": finding_ids, "SortCriteria": _SORT_CRITERIA},
+ )
+ items = findings.get("findings", [])
+ elif endpoint_config.result_key:
+ items = body.get(endpoint_config.result_key, [])
+ else:
+ items = [body]
+ rows = [normalize_row(item, detector_id, client.region) for item in items]
+ if rows:
+ yield rows
+ state = replace(
+ state,
+ detector_ids=state.detector_ids if next_token else state.detector_ids[1:],
+ next_token=next_token or None,
+ )
+ manager.save_state(state)
+ manager.safe_point()
+ finally:
+ client.close()
+
+
+def permission_message(error: AwsGuarddutyError, schema_name: str | None) -> str | None:
+ if error.code in {"AccessDenied", "AccessDeniedException", "ForbiddenException"}:
+ actions = ENDPOINTS[schema_name].iam_actions if schema_name else ("guardduty:ListDetectors",)
+ return "AWS denied access. Required IAM permissions: " + ", ".join(actions) + "."
+ for code, message in ERROR_MESSAGES.items():
+ if error.code.startswith(code):
+ return message
+ return None
+
+
+def validate_credentials(
+ config: AwsGuarddutySourceConfig, api_version: str, schema_name: str | None = None
+) -> tuple[bool, str | None]:
+ if schema_name is not None and schema_name not in ENDPOINTS:
+ return False, f"Unknown GuardDuty table: {schema_name}"
+ try:
+ client = AwsGuarddutyClient(config, api_version)
+ except ValueError as error:
+ return False, str(error)
+ try:
+ body = client.request("ListDetectors", {"MaxResults": 1})
+ if schema_name:
+ detector_id = next(iter(body.get("detectorIds", [])), None)
+ if detector_id is None:
+ return False, "Enable GuardDuty in the selected AWS region, then reconnect."
+ endpoint = ENDPOINTS[schema_name]
+ payload: dict[str, Any] = {"DetectorId": detector_id}
+ if endpoint.result_key:
+ payload["MaxResults"] = 1
+ if schema_name == "members":
+ payload["OnlyAssociated"] = "false"
+ body = client.request(endpoint.operation, payload)
+ if schema_name == "findings" and body.get("findingIds"):
+ client.request("GetFindings", {"DetectorId": detector_id, "FindingIds": body["findingIds"]})
+ return True, None
+ except AwsGuarddutyError as error:
+ if schema_name is None and error.code in {"AccessDenied", "AccessDeniedException", "ForbiddenException"}:
+ return True, None
+ message = permission_message(error, schema_name)
+ if message:
+ return False, message
+ raise
+ finally:
+ client.close()
+
+
+def aws_guardduty_source(
+ config: AwsGuarddutySourceConfig,
+ endpoint: str,
+ api_version: str,
+ manager: ResumableSourceManager[AwsGuarddutyResumeConfig],
+ updated_since: dt.datetime | str | None,
+) -> SourceResponse:
+ endpoint_config = schema_for_resource(ENDPOINTS, endpoint)
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(config, endpoint, api_version, manager, updated_since),
+ primary_keys=list(endpoint_config.primary_keys),
+ # Findings can change between listing IDs and retrieving details, so global ordering is not guaranteed.
+ # "desc" saves the watermark once at job end, so unordered rows cannot strand older ones.
+ sort_mode="desc",
+ partition_keys=["created_at"] if endpoint == "findings" else None,
+ partition_mode="datetime" if endpoint == "findings" else None,
+ partition_format="month" if endpoint == "findings" else None,
+ on_complete=manager.clear_state,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_guardduty/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_guardduty/canonical_descriptions.py
new file mode 100644
index 000000000000..1d145df4193e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_guardduty/canonical_descriptions.py
@@ -0,0 +1,56 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "findings": {
+ "description": "Security findings detected by GuardDuty in the selected region.",
+ "docs_url": "https://docs.aws.amazon.com/guardduty/latest/APIReference/API_Finding.html",
+ "columns": {
+ "arn": "Amazon Resource Name that uniquely identifies the finding.",
+ "id": "Identifier assigned to the finding by GuardDuty.",
+ "account_id": "AWS account where GuardDuty detected the finding.",
+ "region": "AWS region where GuardDuty detected the finding.",
+ "source_detector_id": "Detector used to retrieve this finding.",
+ "created_at": "Time when GuardDuty created the finding.",
+ "updated_at": "Time when GuardDuty last updated the finding.",
+ "severity": "Severity assigned to the finding.",
+ "type": "Type of threat reported by the finding.",
+ "title": "Short summary of the finding.",
+ "description": "Description of the finding.",
+ "resource": "AWS resource associated with the finding.",
+ "service": "Detection details, including the action and archive status.",
+ },
+ },
+ "detectors": {
+ "description": "GuardDuty detector configuration in the selected region.",
+ "docs_url": "https://docs.aws.amazon.com/guardduty/latest/APIReference/API_GetDetector.html",
+ "columns": {
+ "source_detector_id": "Identifier of the detector whose configuration was retrieved.",
+ "region": "AWS region that contains the detector.",
+ "status": "Status of the GuardDuty detector.",
+ "created_at": "Time when the detector was created.",
+ "updated_at": "Time when the detector configuration was last updated.",
+ "features": "Protection features and their status for this detector.",
+ "data_sources": "Data sources configured for this detector.",
+ "finding_publishing_frequency": "Frequency at which GuardDuty publishes updated findings.",
+ "service_role": "IAM role that gives GuardDuty access to AWS resources.",
+ "tags": "Tags attached to the detector.",
+ },
+ },
+ "members": {
+ "description": "Accounts managed by the GuardDuty administrator, including accounts that are no longer associated.",
+ "docs_url": "https://docs.aws.amazon.com/guardduty/latest/APIReference/API_ListMembers.html",
+ "columns": {
+ "source_detector_id": "Administrator detector used to list this member.",
+ "region": "AWS region where the member relationship is configured.",
+ "account_id": "AWS account ID of the member.",
+ "administrator_id": "AWS account ID of the GuardDuty administrator.",
+ "detector_id": "Identifier of the member account's detector.",
+ "email": "Email address associated with an invited member account.",
+ "invited_at": "Time when the administrator invited the member account.",
+ "updated_at": "Time when the member relationship was last updated.",
+ "relationship_status": "Status of the relationship between the member and administrator accounts.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_guardduty/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_guardduty/settings.py
new file mode 100644
index 000000000000..55d94f0adf83
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_guardduty/settings.py
@@ -0,0 +1,54 @@
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+
+GUARDDUTY_API_VERSION = "2017-11-28"
+MAX_RESULTS = 50
+
+
+@frozen
+class GuarddutyEndpoint:
+ operation: str
+ result_key: str | None
+ primary_keys: tuple[str, ...]
+ iam_actions: tuple[str, ...]
+
+
+ENDPOINTS = {
+ "findings": GuarddutyEndpoint(
+ operation="ListFindings",
+ result_key="findingIds",
+ primary_keys=("arn",),
+ iam_actions=("guardduty:ListDetectors", "guardduty:ListFindings", "guardduty:GetFindings"),
+ ),
+ "detectors": GuarddutyEndpoint(
+ operation="GetDetector",
+ result_key=None,
+ primary_keys=("region", "source_detector_id"),
+ iam_actions=("guardduty:ListDetectors", "guardduty:GetDetector"),
+ ),
+ "members": GuarddutyEndpoint(
+ operation="ListMembers",
+ result_key="members",
+ primary_keys=("region", "source_detector_id", "account_id"),
+ iam_actions=("guardduty:ListDetectors", "guardduty:ListMembers"),
+ ),
+}
+
+INCREMENTAL_FIELDS = {"findings": [incremental_field("updated_at")]}
+ENDPOINT_DESCRIPTIONS = {
+ "findings": "Threat findings, including severity, affected resources, and detection details.",
+ "detectors": "Detector status, enabled features, and configuration in the selected region.",
+ "members": "Member accounts and their relationship with the GuardDuty administrator account.",
+}
+
+ERROR_MESSAGES = {
+ "AccessDenied": "AWS denied access. Grant the GuardDuty read permissions listed in the source setup.",
+ "ForbiddenException": "AWS denied access. Grant the GuardDuty read permissions listed in the source setup.",
+ "UnrecognizedClientException": "AWS rejected the credentials. Check the access key ID, secret access key, and session token.",
+ "InvalidClientTokenId": "AWS rejected the access key ID. Check that the key is active.",
+ "InvalidSignatureException": "AWS rejected the signature. Check the secret access key and session token.",
+ "SignatureDoesNotMatch": "AWS rejected the signature. Check the secret access key.",
+ "ExpiredToken": "The AWS session token expired. Reconnect with current credentials.",
+ "SubscriptionRequiredException": "Enable GuardDuty in the selected AWS region, then reconnect.",
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_guardduty/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_guardduty/source.py
index 6018902b4874..c010bfad5c6f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_guardduty/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_guardduty/source.py
@@ -1,8 +1,38 @@
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,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_guardduty.aws_guardduty import (
+ AwsGuarddutyResumeConfig,
+ aws_guardduty_source,
+ validate_credentials as validate_aws_guardduty_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_guardduty.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_guardduty.settings import (
+ ENDPOINT_DESCRIPTIONS,
+ ENDPOINTS,
+ ERROR_MESSAGES,
+ GUARDDUTY_API_VERSION,
+ INCREMENTAL_FIELDS,
+)
+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.awsguardduty import (
AwsGuarddutySourceConfig,
)
@@ -10,18 +40,114 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AwsGuarddutySource(SimpleSource[AwsGuarddutySourceConfig]):
+class AwsGuarddutySource(ResumableSource[AwsGuarddutySourceConfig, AwsGuarddutyResumeConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = (GUARDDUTY_API_VERSION,)
+ default_version = GUARDDUTY_API_VERSION
+ api_docs_url = "https://docs.aws.amazon.com/guardduty/latest/APIReference/Welcome.html"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AWSGUARDDUTY
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {f"AWS GuardDuty 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: AwsGuarddutySourceConfig,
+ 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, merge_only={"findings"}, descriptions=ENDPOINT_DESCRIPTIONS
+ )
+
+ def validate_credentials(
+ self,
+ config: AwsGuarddutySourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_aws_guardduty_credentials(config, self.resolve_api_version(api_version), schema_name)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AwsGuarddutyResumeConfig]:
+ return ResumableSourceManager(inputs, AwsGuarddutyResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AwsGuarddutySourceConfig,
+ resumable_source_manager: ResumableSourceManager[AwsGuarddutyResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return aws_guardduty_source(
+ config,
+ inputs.schema_name,
+ self.resolve_api_version(inputs.api_version),
+ resumable_source_manager,
+ inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.AWSGUARDDUTY,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="Amazon Web Services (Amazon GuardDuty)",
+ label="AWS GuardDuty",
iconPath="/static/services/aws_guardduty.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ caption=(
+ "Sync GuardDuty findings, detectors, and member accounts from one AWS region. "
+ "Enable GuardDuty in that region before syncing. "
+ "Grant `guardduty:ListDetectors`, `guardduty:GetDetector`, `guardduty:ListFindings`, "
+ "`guardduty:GetFindings`, and `guardduty:ListMembers` for all tables. "
+ "The members table requires a GuardDuty administrator account. "
+ "Findings use incremental sync through their update time. Other tables use full refresh."
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["aws", "guardduty", "security", "threat detection"],
+ 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",
+ caption="Temporary credentials expire. Reconnect with current credentials when the session token expires.",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="aws_region",
+ label="AWS region",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="us-east-1",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_guardduty/tests/test_aws_guardduty.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_guardduty/tests/test_aws_guardduty.py
new file mode 100644
index 000000000000..c0ec19ccc0d8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_guardduty/tests/test_aws_guardduty.py
@@ -0,0 +1,556 @@
+import json
+import datetime as dt
+from collections.abc import Iterable, Iterator
+from typing import Any, cast
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+from unittest import mock
+
+import requests
+from tenacity import wait_none
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_guardduty import aws_guardduty
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_guardduty.aws_guardduty import (
+ AwsGuarddutyClient,
+ AwsGuarddutyError,
+ AwsGuarddutyResumeConfig,
+ AwsGuarddutyThrottledError,
+ aws_guardduty_source,
+ error_for_response,
+ get_rows,
+ validate_credentials,
+ watermark_milliseconds,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_guardduty.source import AwsGuarddutySource
+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 UnknownResourceError
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsguardduty import (
+ AwsGuarddutySourceConfig,
+)
+
+VERSION = "2017-11-28"
+UPDATED_AT = dt.datetime(2025, 1, 1, tzinfo=dt.UTC)
+
+
+class FakeResumeManager(ResumableSourceManager[AwsGuarddutyResumeConfig]):
+ def __init__(self, state: AwsGuarddutyResumeConfig | None = None) -> None:
+ self.state = state
+ self.saved: list[AwsGuarddutyResumeConfig] = []
+ self.cleared: bool = False
+ self.safe_points = 0
+
+ def can_resume(self) -> bool:
+ return self.state is not None
+
+ def load_state(self) -> AwsGuarddutyResumeConfig | None:
+ return self.state
+
+ def save_state(self, data: AwsGuarddutyResumeConfig) -> None:
+ self.saved.append(data)
+
+ def clear_state(self) -> None:
+ self.cleared = True
+
+ def safe_point(self) -> None:
+ self.safe_points += 1
+
+
+def response(
+ payload: dict[str, Any] | None = None, status: int = 200, headers: dict[str, str] | None = None
+) -> requests.Response:
+ result = requests.Response()
+ result.status_code = status
+ result._content = json.dumps(payload or {}).encode()
+ result.headers.update(headers or {})
+ return result
+
+
+def config() -> AwsGuarddutySourceConfig:
+ return AwsGuarddutySourceConfig(
+ aws_access_key_id="AKIAEXAMPLE",
+ aws_secret_access_key="example-secret",
+ aws_session_token="example-session-token",
+ aws_region="us-east-1",
+ )
+
+
+def session() -> Iterator[mock.MagicMock]:
+ with mock.patch.object(aws_guardduty, "make_tracked_session") as factory:
+ factory.return_value.request.return_value = response()
+ yield factory.return_value
+
+
+ "operation,payload,method,path,query,body",
+ [
+ ("ListDetectors", {"MaxResults": 1}, "GET", "/detector", {"maxResults": ["1"]}, None),
+ ("GetDetector", {"DetectorId": "detector-example"}, "GET", "/detector/detector-example", {}, None),
+ (
+ "ListMembers",
+ {"DetectorId": "detector-example", "MaxResults": 50, "NextToken": "a+b/=", "OnlyAssociated": "false"},
+ "GET",
+ "/detector/detector-example/member",
+ {"maxResults": ["50"], "nextToken": ["a+b/="], "onlyAssociated": ["false"]},
+ None,
+ ),
+ (
+ "ListFindings",
+ {"DetectorId": "detector-example", "MaxResults": 50, "NextToken": "next-page"},
+ "POST",
+ "/detector/detector-example/findings",
+ {},
+ {"maxResults": 50, "nextToken": "next-page"},
+ ),
+ (
+ "GetFindings",
+ {"DetectorId": "detector-example", "FindingIds": ["finding-example"]},
+ "POST",
+ "/detector/detector-example/findings/get",
+ {},
+ {"findingIds": ["finding-example"]},
+ ),
+ ],
+)
+def test_signed_rest_requests(
+ config: AwsGuarddutySourceConfig,
+ session: mock.MagicMock,
+ operation: str,
+ payload: dict[str, Any],
+ method: str,
+ path: str,
+ query: dict[str, list[str]],
+ body: dict[str, Any] | None,
+) -> None:
+ client = AwsGuarddutyClient(config, VERSION)
+ client.request(operation, payload)
+ call = session.request.call_args
+ assert call.args[0] == method
+ url = urlsplit(call.args[1])
+ assert url.netloc == "guardduty.us-east-1.amazonaws.com"
+ assert url.path == path
+ assert parse_qs(url.query) == query
+ assert (json.loads(call.kwargs["data"]) if body is not None else call.kwargs["data"]) == (body or b"")
+ headers = call.kwargs["headers"]
+ assert headers["Authorization"].startswith("AWS4-HMAC-SHA256 Credential=AKIAEXAMPLE/")
+ assert "/us-east-1/guardduty/aws4_request" in headers["Authorization"]
+ assert "X-Amz-Date" in headers
+ assert headers["X-Amz-Security-Token"] == "example-session-token"
+ assert "X-Amz-Target" not in headers
+ if body is not None:
+ assert headers["Content-Type"] == "application/json"
+ assert call.kwargs["timeout"] == 60
+ assert call.kwargs["allow_redirects"] is False
+ factory = aws_guardduty.make_tracked_session
+ assert isinstance(factory, mock.Mock)
+ assert "example-secret" in factory.call_args.kwargs["redact_values"]
+ assert "example-session-token" in factory.call_args.kwargs["redact_values"]
+
+
[email protected]("region,suffix", [("eu-west-1", "amazonaws.com"), ("cn-north-1", "amazonaws.com.cn")])
+def test_region_and_credentials_without_session_token(
+ config: AwsGuarddutySourceConfig, session: mock.MagicMock, region: str, suffix: str
+) -> None:
+ config.aws_region = region
+ config.aws_session_token = None
+ AwsGuarddutyClient(config, VERSION).request("ListDetectors", {})
+ call = session.request.call_args
+ assert call.args[1] == f"https://guardduty.{region}.{suffix}/detector"
+ assert f"/{region}/guardduty/aws4_request" in call.kwargs["headers"]["Authorization"]
+ assert "X-Amz-Security-Token" not in call.kwargs["headers"]
+
+
[email protected]("incremental", [True, False])
[email protected]("terminal", [{}, {"nextToken": None}, {"nextToken": ""}])
+def test_findings_pages_hydration_and_time_filter(
+ config: AwsGuarddutySourceConfig, session: mock.MagicMock, incremental: bool, terminal: dict[str, Any]
+) -> None:
+ session.request.side_effect = [
+ response({"detectorIds": [], "nextToken": "detectors-next"}),
+ response({"detectorIds": ["detector-example"]}),
+ response({"findingIds": [], "nextToken": "findings-next"}),
+ response({"findingIds": ["finding-example"], **terminal}),
+ response(
+ {
+ "findings": [
+ {
+ "id": "finding-example",
+ "arn": "arn:aws:guardduty:us-east-1:111111111111:detector/example/finding/example",
+ "createdAt": "2024-12-01T00:00:00Z",
+ "updatedAt": "2025-01-01T00:00:00Z",
+ "resource": {"resourceType": "Instance", "instanceDetails": {"instanceId": "i-example"}},
+ }
+ ]
+ }
+ ),
+ ]
+ manager = FakeResumeManager()
+ inputs = mock.Mock(
+ spec=SourceInputs,
+ schema_name="findings",
+ api_version=VERSION,
+ should_use_incremental_field=incremental,
+ db_incremental_field_last_value=UPDATED_AT,
+ )
+ resource = AwsGuarddutySource().source_for_pipeline(config, manager, inputs)
+ batches = list(cast(Iterable[Any], resource.items()))
+ assert len(batches) == 1
+ row = batches[0][0]
+ assert row["updated_at"] == UPDATED_AT
+ assert row["created_at"] == dt.datetime(2024, 12, 1, tzinfo=dt.UTC)
+ assert row["source_detector_id"] == "detector-example"
+ assert row["resource"]["instanceDetails"]["instanceId"] == "i-example"
+ calls = session.request.call_args_list
+ assert parse_qs(urlsplit(calls[1].args[1]).query)["nextToken"] == ["detectors-next"]
+ for call in calls[2:4]:
+ payload = json.loads(call.kwargs["data"])
+ assert payload["maxResults"] == 50
+ assert payload["sortCriteria"] == {"attributeName": "updatedAt", "orderBy": "ASC"}
+ if incremental:
+ assert payload["findingCriteria"] == {"criterion": {"updatedAt": {"greaterThanOrEqual": 1735689600000}}}
+ else:
+ assert "findingCriteria" not in payload
+ assert json.loads(calls[3].kwargs["data"])["nextToken"] == "findings-next"
+ assert json.loads(calls[4].kwargs["data"]) == {
+ "findingIds": ["finding-example"],
+ "sortCriteria": {"attributeName": "updatedAt", "orderBy": "ASC"},
+ }
+ assert manager.safe_points == 2
+ assert manager.saved[-1].detector_ids == []
+ assert not manager.cleared
+ assert resource.on_complete is not None
+ resource.on_complete()
+ assert resource.partition_keys == ["created_at"]
+ assert resource.sort_mode == "desc"
+ session.close.assert_called_once()
+ assert manager.cleared
+
+
+def test_resume_preserves_filter_and_advances_after_yield(
+ config: AwsGuarddutySourceConfig, session: mock.MagicMock
+) -> None:
+ manager = FakeResumeManager(
+ AwsGuarddutyResumeConfig(
+ detector_ids=["detector-example"], next_token="saved-page", updated_since_ms=1735689600000
+ )
+ )
+ session.request.side_effect = [
+ response({"findingIds": ["finding-example"]}),
+ response({"findings": [{"id": "finding-example", "arn": "arn:example", "updatedAt": "2025-01-01T00:00:00Z"}]}),
+ ]
+ rows = get_rows(config, "findings", VERSION, manager, "2025-02-01T00:00:00Z")
+ assert next(rows)[0]["id"] == "finding-example"
+ assert manager.saved == []
+ assert list(rows) == []
+ payload = json.loads(session.request.call_args_list[0].kwargs["data"])
+ assert payload["nextToken"] == "saved-page"
+ assert payload["findingCriteria"]["criterion"]["updatedAt"]["greaterThanOrEqual"] == 1735689600000
+ assert manager.saved[-1].detector_ids == []
+
+
[email protected]("endpoint", ["findings", "members", "detectors"])
+def test_completed_resume_does_not_repeat_requests(
+ config: AwsGuarddutySourceConfig, session: mock.MagicMock, endpoint: str
+) -> None:
+ manager = FakeResumeManager(AwsGuarddutyResumeConfig(detector_ids=[]))
+ assert list(get_rows(config, endpoint, VERSION, manager, None)) == []
+ session.request.assert_not_called()
+ session.close.assert_called_once()
+
+
+def test_members_pagination_and_parent_keys(config: AwsGuarddutySourceConfig, session: mock.MagicMock) -> None:
+ member = {"accountId": "111111111111", "detectorId": "member-detector", "relationshipStatus": "Enabled"}
+ session.request.side_effect = [
+ response({"detectorIds": ["administrator-a", "administrator-b"]}),
+ response({"members": [member], "nextToken": "next-page"}),
+ response({"members": []}),
+ response({"members": [member]}),
+ ]
+ manager = FakeResumeManager()
+ resource = aws_guardduty_source(config, "members", VERSION, manager, UPDATED_AT)
+ rows = [row for batch in cast(Iterable[Any], resource.items()) for row in batch]
+ assert len({tuple(row[key] for key in resource.primary_keys or []) for row in rows}) == 2
+ assert rows[0]["detector_id"] == "member-detector"
+ for call in session.request.call_args_list[1:]:
+ query = parse_qs(urlsplit(call.args[1]).query)
+ assert query["onlyAssociated"] == ["false"]
+ assert query["maxResults"] == ["50"]
+ assert call.kwargs["data"] == b""
+ assert manager.saved[1].detector_ids == ["administrator-b"]
+ assert manager.saved[1].next_token is None
+ assert "nextToken" not in parse_qs(urlsplit(session.request.call_args_list[3].args[1]).query)
+
+
+def test_detector_details(config: AwsGuarddutySourceConfig, session: mock.MagicMock) -> None:
+ session.request.side_effect = [
+ response({"detectorIds": ["detector-example"]}),
+ response({"status": "ENABLED", "createdAt": "2025-01-01T00:00:00Z", "tags": {"purpose": "example"}}),
+ ]
+ rows = list(get_rows(config, "detectors", VERSION, FakeResumeManager(), None))
+ assert rows == [
+ [
+ {
+ "status": "ENABLED",
+ "created_at": UPDATED_AT,
+ "tags": {"purpose": "example"},
+ "region": "us-east-1",
+ "source_detector_id": "detector-example",
+ }
+ ]
+ ]
+ assert session.request.call_args.args[1].endswith("/detector/detector-example")
+
+
+def test_empty_region_does_not_request_children(config: AwsGuarddutySourceConfig, session: mock.MagicMock) -> None:
+ session.request.return_value = response({"detectorIds": []})
+ assert list(get_rows(config, "findings", VERSION, FakeResumeManager(), None)) == []
+ session.request.assert_called_once()
+
+
+ "value,expected",
+ [
+ (None, None),
+ (UPDATED_AT, 1735689600000),
+ ("2025-01-01T01:00:00.123+01:00", 1735689600123),
+ ("2025-01-01T00:00:00", 1735689600000),
+ ],
+)
+def test_watermark_conversion(value: dt.datetime | str | None, expected: int | None) -> None:
+ assert watermark_milliseconds(value) == expected
+
+
+ "status,payload,headers,code,retryable",
+ [
+ (403, {"message": "Access denied"}, {}, "AccessDenied", False),
+ (403, {"__type": "com.amazonaws#AccessDeniedException"}, {}, "AccessDeniedException", False),
+ (
+ 400,
+ {"message": "Invalid key"},
+ {"x-amzn-ErrorType": "UnrecognizedClientException:example"},
+ "UnrecognizedClientException",
+ False,
+ ),
+ (400, {"code": "InvalidSignatureException"}, {}, "InvalidSignatureException", False),
+ (400, {"code": "ExpiredTokenException"}, {}, "ExpiredTokenException", False),
+ (400, {"message": "AWS subscription is required"}, {}, "SubscriptionRequiredException", False),
+ (400, {"message": "The account is not subscribed to the service."}, {}, "SubscriptionRequiredException", False),
+ (400, {"__type": "ThrottlingException"}, {}, "ThrottlingException", True),
+ (429, {"__type": "ThrottlingException"}, {}, "ThrottlingException", False),
+ (500, {"__type": "InternalServerErrorException"}, {}, "InternalServerErrorException", False),
+ ],
+)
+def test_error_mapping(
+ status: int, payload: dict[str, Any], headers: dict[str, str], code: str, retryable: bool
+) -> None:
+ error = error_for_response(response(payload, status, headers))
+ assert error.code == code
+ assert isinstance(error, AwsGuarddutyThrottledError) == retryable
+ if code not in {"ThrottlingException", "InternalServerErrorException"}:
+ messages = AwsGuarddutySource().get_non_retryable_errors()
+ assert any(pattern in str(error) and message for pattern, message in messages.items())
+
+
[email protected]("status", [403, 502])
+def test_non_json_errors(status: int) -> None:
+ result = response(status=status)
+ result._content = b"upstream error"
+ assert error_for_response(result).code == ("AccessDenied" if status == 403 else "HTTP 502")
+
+
+ "status,code,attempts",
+ [(400, "ThrottlingException", 2), (429, "ThrottlingException", 1), (500, "InternalServerErrorException", 1)],
+)
+def test_only_body_throttles_get_application_retries(
+ config: AwsGuarddutySourceConfig, session: mock.MagicMock, status: int, code: str, attempts: int
+) -> None:
+ session.request.side_effect = [response({"code": code}, status), response({"detectorIds": []})]
+ client = AwsGuarddutyClient(config, VERSION)
+ with mock.patch.object(AwsGuarddutyClient.request.retry, "wait", wait_none()): # type: ignore[attr-defined]
+ if attempts == 1:
+ with pytest.raises(AwsGuarddutyError):
+ client.request("ListDetectors", {})
+ else:
+ assert client.request("ListDetectors", {}) == {"detectorIds": []}
+ assert session.request.call_count == attempts
+
+
[email protected]("schema_name", [None, "findings", "detectors", "members"])
+def test_permission_denial_only_accepted_at_create(
+ config: AwsGuarddutySourceConfig, session: mock.MagicMock, schema_name: str | None
+) -> None:
+ session.request.return_value = response({"__type": "AccessDeniedException", "message": "Access denied"}, 403)
+ valid, message = validate_credentials(config, VERSION, schema_name)
+ assert valid is (schema_name is None)
+ if schema_name:
+ assert message and "guardduty:ListDetectors" in message
+ else:
+ assert message is None
+ session.request.assert_called_once()
+ session.close.assert_called_once()
+
+
+ "code",
+ [
+ "UnrecognizedClientException",
+ "InvalidSignatureException",
+ "ExpiredTokenException",
+ "SubscriptionRequiredException",
+ ],
+)
+def test_invalid_credentials_rejected(config: AwsGuarddutySourceConfig, session: mock.MagicMock, code: str) -> None:
+ session.request.return_value = response({"__type": code}, 400)
+ valid, message = validate_credentials(config, VERSION)
+ assert not valid and message
+ assert "AWS GuardDuty request failed" not in message
+
+
[email protected]("schema_name", [None, "findings", "detectors", "members"])
+def test_no_detector_validation(
+ config: AwsGuarddutySourceConfig, session: mock.MagicMock, schema_name: str | None
+) -> None:
+ session.request.return_value = response({"detectorIds": []})
+ valid, message = validate_credentials(config, VERSION, schema_name)
+ assert valid is (schema_name is None)
+ assert (
+ message is None
+ if schema_name is None
+ else message == "Enable GuardDuty in the selected AWS region, then reconnect."
+ )
+
+
+ "schema_name,path", [("findings", "/findings"), ("members", "/member"), ("detectors", "/detector/detector-example")]
+)
+def test_endpoint_validation_calls_its_read_operation(
+ config: AwsGuarddutySourceConfig, session: mock.MagicMock, schema_name: str, path: str
+) -> None:
+ session.request.side_effect = [response({"detectorIds": ["detector-example"]}), response()]
+ assert validate_credentials(config, VERSION, schema_name) == (True, None)
+ assert urlsplit(session.request.call_args.args[1]).path.endswith(path)
+
+
+def test_findings_validation_checks_hydration_permission(
+ config: AwsGuarddutySourceConfig, session: mock.MagicMock
+) -> None:
+ session.request.side_effect = [
+ response({"detectorIds": ["detector-example"]}),
+ response({"findingIds": ["finding-example"]}),
+ response({"code": "AccessDeniedException"}, 403),
+ ]
+ valid, message = validate_credentials(config, VERSION, "findings")
+ assert not valid and message and "guardduty:GetFindings" in message
+ assert session.request.call_args.args[1].endswith("/findings/get")
+
+
+def test_server_errors_propagate_from_validation(config: AwsGuarddutySourceConfig, session: mock.MagicMock) -> None:
+ session.request.return_value = response({"__type": "InternalServerErrorException"}, 500)
+ with pytest.raises(AwsGuarddutyError, match="InternalServerErrorException"):
+ validate_credentials(config, VERSION)
+ session.close.assert_called_once()
+
+
+ "field_name,value,message",
+ [
+ ("aws_region", "us-east-1.example.com/", "valid AWS region"),
+ ("aws_region", "us-east-1\n", "valid AWS region"),
+ ("aws_access_key_id", "", "Enter both"),
+ ("aws_secret_access_key", "", "Enter both"),
+ ],
+)
+def test_invalid_configuration_never_sends_request(
+ config: AwsGuarddutySourceConfig, session: mock.MagicMock, field_name: str, value: str, message: str
+) -> None:
+ setattr(config, field_name, value)
+ valid, error = validate_credentials(config, VERSION)
+ assert not valid and error and message in error
+ session.request.assert_not_called()
+
+
+def test_unknown_version_and_table(config: AwsGuarddutySourceConfig, session: mock.MagicMock) -> None:
+ assert validate_credentials(config, "2099-01-01")[0] is False
+ assert validate_credentials(config, VERSION, "unknown") == (False, "Unknown GuardDuty table: unknown")
+ with pytest.raises(UnknownResourceError):
+ aws_guardduty_source(config, "unknown", VERSION, FakeResumeManager(), None)
+ session.request.assert_not_called()
+
+
+def test_hydration_failure_keeps_checkpoint(config: AwsGuarddutySourceConfig, session: mock.MagicMock) -> None:
+ session.request.side_effect = [
+ response({"detectorIds": ["detector-example"]}),
+ response({"findingIds": ["finding-example"], "nextToken": "next-page"}),
+ response({"code": "InternalServerErrorException"}, 500),
+ ]
+ manager = FakeResumeManager()
+ with pytest.raises(AwsGuarddutyError):
+ list(get_rows(config, "findings", VERSION, manager, None))
+ assert manager.saved == []
+ assert not manager.cleared
+ session.close.assert_called_once()
+
+
[email protected]("endpoint", ["findings", "members"])
+def test_repeated_token_fails_without_looping(
+ config: AwsGuarddutySourceConfig, session: mock.MagicMock, endpoint: str
+) -> None:
+ manager = FakeResumeManager(AwsGuarddutyResumeConfig(detector_ids=["detector-example"], next_token="same-token"))
+ session.request.return_value = response({"nextToken": "same-token"})
+ with pytest.raises(ValueError, match="repeated a page token"):
+ list(get_rows(config, endpoint, VERSION, manager, None))
+ session.request.assert_called_once()
+
+
+def test_repeated_detector_token_fails_without_looping(
+ config: AwsGuarddutySourceConfig, session: mock.MagicMock
+) -> None:
+ session.request.return_value = response({"detectorIds": [], "nextToken": "same-token"})
+ with pytest.raises(ValueError, match="repeated a page token"):
+ list(get_rows(config, "detectors", VERSION, FakeResumeManager(), None))
+ assert session.request.call_count == 2
+ session.close.assert_called_once()
+
+
[email protected]("endpoint", ["findings", "members"])
+def test_cyclic_token_fails_without_looping(
+ config: AwsGuarddutySourceConfig, session: mock.MagicMock, endpoint: str
+) -> None:
+ manager = FakeResumeManager(AwsGuarddutyResumeConfig(detector_ids=["detector-example"]))
+ session.request.side_effect = [
+ response({"nextToken": "token-a"}),
+ response({"nextToken": "token-b"}),
+ response({"nextToken": "token-a"}),
+ ]
+ with pytest.raises(ValueError, match="repeated a page token"):
+ list(get_rows(config, endpoint, VERSION, manager, None))
+ assert manager.saved[-1].next_token == "token-b"
+ assert session.request.call_count == 3
+
+
+def test_cyclic_detector_token_fails_without_looping(config: AwsGuarddutySourceConfig, session: mock.MagicMock) -> None:
+ session.request.side_effect = [
+ response({"detectorIds": [], "nextToken": "token-a"}),
+ response({"detectorIds": [], "nextToken": "token-b"}),
+ response({"detectorIds": [], "nextToken": "token-a"}),
+ ]
+ with pytest.raises(ValueError, match="repeated a page token"):
+ list(get_rows(config, "detectors", VERSION, FakeResumeManager(), None))
+ assert session.request.call_count == 3
+ session.close.assert_called_once()
+
+
+def test_invalid_response_fails_instead_of_silently_finishing(
+ config: AwsGuarddutySourceConfig, session: mock.MagicMock
+) -> None:
+ result = response()
+ result._content = b"[]"
+ session.request.return_value = result
+ with pytest.raises(ValueError, match="invalid response"):
+ list(get_rows(config, "findings", VERSION, FakeResumeManager(), None))
+ session.close.assert_called_once()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsguardduty.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsguardduty.py
index 17bc79930524..c412a29f5002 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsguardduty.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsguardduty.py
@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class AwsGuarddutySourceConfig(config.Config):
- pass
+ aws_access_key_id: str
+ aws_secret_access_key: str
+ aws_region: str
+ aws_session_token: str | None = None