: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement the aws cloudtrail import source (#110792)
Tom Owersdf63e60f88ac
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 9bcd2b074869..ed65e52a6716 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -103,6 +103,7 @@ the row lists both.| aviator | HTTP | requests | ✅ || awin | HTTP | requests | ✅ || aws_budgets | HTTP | requests | ✅ |+| aws_cloudtrail | HTTP | requests | ✅ || aws_cost_anomaly_detection | HTTP | requests | ✅ || aws_cost_explorer | HTTP | requests | ✅ || aws_glue_data_catalog | HTTP | requests | ✅ |@@ -916,7 +917,6 @@ doesn't conflict with concurrent PRs.- aws_athena- aws_batch- aws_cloudformation-- aws_cloudtrail- aws_compute_optimizer- aws_config- aws_connectdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cloudtrail/aws_cloudtrail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cloudtrail/aws_cloudtrail.pynew file mode 100644index 000000000000..69206ca15dfd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cloudtrail/aws_cloudtrail.py@@ -0,0 +1,273 @@+import re+import json+import time+import datetime as dt+from collections.abc import Iterator+from typing import Any++import requests+from botocore.auth import SigV4Auth+from botocore.awsrequest import AWSRequest+from botocore.credentials import Credentials+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_cloudtrail.settings import (+ ACCESS_DENIED_CODES,+ AWS_CLOUDTRAIL_ENDPOINTS,+ CREDENTIAL_ERRORS,+ LOOKBACK_SECONDS,+ TARGET_PREFIXES,+ THROTTLE_CODES,+ CloudTrailEndpoint,+)+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.typings import SourceResponse++_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")+TRANSPORT_RETRY = BoundedRetry(+ total=3,+ backoff_factor=1,+ status_forcelist=(429, 500, 502, 503, 504),+ allowed_methods=frozenset(["POST"]),+ raise_on_status=False,+)+++@frozen+class AwsCloudTrailResumeConfig:+ next_token: str | None = None+ start_time: float | None = None+ end_time: float | None = None+ finished: bool = False+++class AwsCloudTrailError(Exception):+ def __init__(self, code: str) -> None:+ super().__init__(f"AWS CloudTrail request failed: {code}")+ self.code = code+++class AwsCloudTrailThrottled(AwsCloudTrailError):+ pass+++def error_for_response(response: requests.Response) -> AwsCloudTrailError:+ 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]+ # The transport retries HTTP statuses. Only body-level throttles need a separate retry.+ if response.status_code == 400 and code in THROTTLE_CODES:+ return AwsCloudTrailThrottled(code)+ return AwsCloudTrailError(code)+++class AwsCloudTrailClient:+ def __init__(+ self,+ access_key_id: str,+ secret_access_key: str,+ session_token: str | None,+ region: str,+ api_version: str,+ ) -> None:+ if not access_key_id or not secret_access_key:+ raise ValueError("Enter both an AWS access key ID and a secret access key.")+ if not re.fullmatch(r"(?:af|ap|ca|eu|il|me|mx|sa|us|cn)-(?:gov-)?[a-z]+-\d+", region):+ raise ValueError("Enter a valid AWS region, such as us-east-1.")+ if api_version not in TARGET_PREFIXES:+ raise ValueError(f"Unsupported AWS CloudTrail API version: {api_version}")+ self.region = region+ self.target_prefix = TARGET_PREFIXES[api_version]+ suffix = "amazonaws.com.cn" if region.startswith("cn-") else "amazonaws.com"+ self.url = f"https://cloudtrail.{region}.{suffix}/"+ self.signer = SigV4Auth(+ Credentials(access_key_id, secret_access_key, session_token or None), "cloudtrail", region+ )+ self.session = make_tracked_session(+ retry=TRANSPORT_RETRY,+ redact_values=tuple(value for value in (access_key_id, secret_access_key, session_token) if value),+ )+ self._last_lookup: float | None = None++ @retry(+ retry=retry_if_exception_type(AwsCloudTrailThrottled),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def request(self, operation: str, payload: dict[str, Any]) -> dict[str, Any]:+ if operation == "LookupEvents":+ if self._last_lookup is not None:+ time.sleep(max(0, 0.5 - (time.monotonic() - self._last_lookup)))+ self._last_lookup = time.monotonic()+ 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"{self.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 not 200 <= response.status_code < 300:+ raise error_for_response(response)+ parsed = response.json()+ if not isinstance(parsed, dict):+ raise ValueError("AWS CloudTrail returned an invalid response.")+ return parsed++ def close(self) -> None:+ self.session.close()+++def normalize_row(item: dict[str, Any], endpoint: CloudTrailEndpoint, region: str) -> dict[str, Any]:+ row = {_CAMEL_BOUNDARY.sub("_", key).lower(): value for key, value in item.items()}+ row["region"] = region+ for column in endpoint.timestamps:+ value = row.get(column)+ if isinstance(value, int | float) and not isinstance(value, bool):+ row[column] = dt.datetime.fromtimestamp(value, dt.UTC)+ return row+++def request_payload(endpoint: CloudTrailEndpoint, page_size: int | None = None) -> dict[str, Any]:+ payload: dict[str, Any] = {}+ if endpoint.page_size is not None:+ payload["MaxResults"] = page_size or endpoint.page_size+ if endpoint.event_category is not None:+ payload["EventCategory"] = endpoint.event_category+ if endpoint.operation == "DescribeTrails":+ payload["includeShadowTrails"] = True+ return payload+++def get_rows(+ client: AwsCloudTrailClient,+ endpoint: CloudTrailEndpoint,+ manager: ResumableSourceManager[AwsCloudTrailResumeConfig],+ last_value: dt.datetime | str | int | float | None,+) -> Iterator[list[dict[str, Any]]]:+ try:+ state = manager.load_state() or AwsCloudTrailResumeConfig()+ if state.finished:+ return+ start_time, end_time = state.start_time, state.end_time+ if endpoint.is_events and end_time is None:+ end_time = dt.datetime.now(dt.UTC).timestamp()+ if last_value is not None:+ if isinstance(last_value, str):+ last_value = dt.datetime.fromisoformat(last_value.replace("Z", "+00:00"))+ if isinstance(last_value, dt.datetime):+ if last_value.tzinfo is None:+ last_value = last_value.replace(tzinfo=dt.UTC)+ last_value = last_value.timestamp()+ start_time = max(float(last_value), end_time - LOOKBACK_SECONDS)+ payload = request_payload(endpoint)+ if endpoint.is_events:+ payload["EndTime"] = end_time+ if start_time is not None:+ payload["StartTime"] = start_time+ next_token = state.next_token+ restarted = False+ while True:+ params = dict(payload)+ if next_token:+ params["NextToken"] = next_token+ try:+ body = client.request(endpoint.operation, params)+ except AwsCloudTrailError as error:+ if error.code == "InvalidNextTokenException" and state.next_token and not restarted:+ next_token = None+ restarted = True+ continue+ raise+ next_token = body.get("NextToken") if endpoint.page_size is not None else None+ if next_token and next_token == params.get("NextToken"):+ raise ValueError("AWS CloudTrail returned a repeated page token.")+ rows = [normalize_row(item, endpoint, client.region) for item in body.get(endpoint.result_key, [])]+ manager.save_state(+ AwsCloudTrailResumeConfig(+ next_token=next_token, start_time=start_time, end_time=end_time, finished=not next_token+ )+ )+ if rows:+ yield rows+ manager.safe_point()+ if not next_token:+ break+ finally:+ client.close()+++def validate_credentials(+ access_key_id: str,+ secret_access_key: str,+ session_token: str | None,+ region: str,+ api_version: str,+ schema_name: str | None = None,+) -> tuple[bool, str | None]:+ endpoint = AWS_CLOUDTRAIL_ENDPOINTS.get(schema_name or "trails")+ if endpoint is None:+ return False, f"Unknown AWS CloudTrail table: {schema_name}"+ try:+ client = AwsCloudTrailClient(access_key_id, secret_access_key, session_token, region, api_version)+ except ValueError as error:+ return False, str(error)+ try:+ client.request(endpoint.operation, request_payload(endpoint, page_size=1))+ except AwsCloudTrailError as error:+ if error.code in ACCESS_DENIED_CODES:+ if schema_name is None:+ return True, None+ return False, f"Grant the cloudtrail:{endpoint.operation} IAM permission to read this table."+ return False, CREDENTIAL_ERRORS.get(error.code, "Could not read from AWS CloudTrail. Try again.")+ except (requests.RequestException, ValueError):+ return False, "Could not reach the AWS CloudTrail API. Check the selected region and try again."+ finally:+ client.close()+ return True, None+++def aws_cloudtrail_source(+ access_key_id: str,+ secret_access_key: str,+ session_token: str | None,+ region: str,+ api_version: str,+ endpoint_name: str,+ manager: ResumableSourceManager[AwsCloudTrailResumeConfig],+ last_value: dt.datetime | str | int | float | None,+) -> SourceResponse:+ endpoint = AWS_CLOUDTRAIL_ENDPOINTS.get(endpoint_name)+ if endpoint is None:+ raise ValueError(f"Unknown AWS CloudTrail table: {endpoint_name}")+ return SourceResponse(+ name=endpoint_name,+ items=lambda: get_rows(+ AwsCloudTrailClient(access_key_id, secret_access_key, session_token, region, api_version),+ endpoint,+ manager,+ last_value,+ ),+ primary_keys=list(endpoint.primary_key),+ sort_mode="desc" if endpoint.is_events else None,+ partition_keys=["event_time"] if endpoint.is_events else None,+ partition_mode="datetime" if endpoint.is_events else None,+ partition_format="month" if endpoint.is_events else None,+ on_complete=manager.clear_state,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cloudtrail/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cloudtrail/canonical_descriptions.pynew file mode 100644index 000000000000..449390304d21--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cloudtrail/canonical_descriptions.py@@ -0,0 +1,63 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_EVENT_COLUMNS = {+ "event_id": "The identifier that CloudTrail assigns to the event.",+ "event_name": "The AWS API action recorded by the event.",+ "event_source": "The AWS service that received the request.",+ "event_time": "The time of the event in UTC.",+ "username": "The user name associated with the event.",+ "access_key_id": "The access key ID used for the request.",+ "read_only": "Indicates whether the recorded operation only reads resources.",+ "resources": "The names and types of resources referenced by the event.",+ "cloud_trail_event": "The full CloudTrail event as a JSON string.",+ "region": "The AWS region selected for this import.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "events": {+ "description": "Management events returned by CloudTrail event history within the past 90 days.",+ "docs_url": "https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_LookupEvents.html",+ "columns": _EVENT_COLUMNS,+ },+ "insight_events": {+ "description": "Insights events from trails with Insights enabled, within the past 90 days.",+ "docs_url": "https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_LookupEvents.html",+ "columns": _EVENT_COLUMNS,+ },+ "trails": {+ "description": "Trail settings for the selected region, including shadow trails from other regions or organization accounts.",+ "docs_url": "https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_DescribeTrails.html",+ "columns": {+ "trail_arn": "The ARN that identifies the trail.",+ "name": "The trail name.",+ "home_region": "The AWS region where the trail was created.",+ "s3_bucket_name": "The S3 bucket that receives the trail logs.",+ "s3_key_prefix": "The prefix used for log objects in the S3 bucket.",+ "is_multi_region_trail": "Indicates whether the trail records events across AWS regions.",+ "is_organization_trail": "Indicates whether the trail applies to an AWS organization.",+ "log_file_validation_enabled": "Indicates whether CloudTrail creates digest files for log validation.",+ "include_global_service_events": "Indicates whether the trail records global service events.",+ "has_insight_selectors": "Indicates whether the trail has Insights selectors.",+ "region": "The AWS region selected for this import.",+ },+ },+ "event_data_stores": {+ "description": "CloudTrail Lake event store settings in the selected region. These rows do not contain stored events.",+ "docs_url": "https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_ListEventDataStores.html",+ "columns": {+ "event_data_store_arn": "The ARN that identifies the event store.",+ "name": "The event store name.",+ "status": "The event store status.",+ "created_timestamp": "The time when the event store was created.",+ "updated_timestamp": "The time when the event store was last changed.",+ "retention_period": "The number of days for which the event store retains events.",+ "advanced_event_selectors": "The rules that select events for this store.",+ "multi_region_enabled": "Indicates whether the store includes events from multiple AWS regions.",+ "organization_enabled": "Indicates whether the store includes events from an AWS organization.",+ "termination_protection_enabled": "Indicates whether deletion protection is enabled.",+ "region": "The AWS region selected for this import.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cloudtrail/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cloudtrail/settings.pynew file mode 100644index 000000000000..8eeecf6b02fb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cloudtrail/settings.py@@ -0,0 +1,78 @@+from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++CLOUDTRAIL_API_VERSION = "2013-11-01"+TARGET_PREFIXES = {CLOUDTRAIL_API_VERSION: "com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101"}+LOOKBACK_SECONDS = 90 * 24 * 60 * 60+++@frozen+class CloudTrailEndpoint:+ operation: str+ result_key: str+ primary_key: tuple[str, ...]+ page_size: int | None = None+ event_category: str | None = None+ timestamps: tuple[str, ...] = ()++ @property+ def is_events(self) -> bool:+ return self.operation == "LookupEvents"+++AWS_CLOUDTRAIL_ENDPOINTS: dict[str, CloudTrailEndpoint] = {+ "events": CloudTrailEndpoint(+ operation="LookupEvents",+ result_key="Events",+ primary_key=("region", "event_id"),+ page_size=50,+ timestamps=("event_time",),+ ),+ "insight_events": CloudTrailEndpoint(+ operation="LookupEvents",+ result_key="Events",+ primary_key=("region", "event_id"),+ page_size=50,+ event_category="insight",+ timestamps=("event_time",),+ ),+ "trails": CloudTrailEndpoint(+ operation="DescribeTrails",+ result_key="trailList",+ primary_key=("trail_arn",),+ ),+ "event_data_stores": CloudTrailEndpoint(+ operation="ListEventDataStores",+ result_key="EventDataStores",+ primary_key=("event_data_store_arn",),+ page_size=100,+ timestamps=("created_timestamp", "updated_timestamp"),+ ),+}+ENDPOINTS = tuple(AWS_CLOUDTRAIL_ENDPOINTS)+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: [incremental_field("event_time")] for name, endpoint in AWS_CLOUDTRAIL_ENDPOINTS.items() if endpoint.is_events+}+ENDPOINT_DESCRIPTIONS = {+ "events": "Management events from the past 90 days in the selected AWS region. Data events are excluded.",+ "insight_events": "Insights events from the past 90 days for trails with Insights enabled in the selected region.",+ "trails": "Trail settings in the selected region, including shadow trails.",+ "event_data_stores": "CloudTrail Lake event store settings in the selected region. Stored events are excluded.",+}++ACCESS_DENIED_CODES = frozenset({"AccessDenied", "AccessDeniedException"})+THROTTLE_CODES = frozenset({"Throttling", "ThrottlingException", "TooManyRequestsException", "RequestLimitExceeded"})+CREDENTIAL_ERRORS = {+ "UnrecognizedClientException": "AWS rejected the access key. Check the access key ID, secret access key, and session token.",+ "InvalidClientTokenId": "AWS rejected the access key. Check the access key ID and secret access key.",+ "InvalidSignatureException": "AWS rejected the signature. Check the secret access key and session token.",+ "SignatureDoesNotMatch": "AWS rejected the signature. Check the secret access key and selected region.",+ "ExpiredTokenException": "The AWS session token has expired. Reconnect with new credentials.",+ "ExpiredToken": "The AWS session token has expired. Reconnect with new credentials.",+ "SubscriptionRequiredException": "This AWS account needs access to the requested CloudTrail service. Check its service subscription.",+ "OptInRequired": "This AWS account needs access to the requested service or region. Enable access in AWS.",+ "OperationNotPermittedException": "AWS does not permit this operation. Check the account permissions and service availability.",+ "UnsupportedOperationException": "AWS does not support this operation in the selected region. Select a supported region.",+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cloudtrail/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cloudtrail/source.pyindex a73eeb7c2815..f47c2687eae8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cloudtrail/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cloudtrail/source.py@@ -1,8 +1,36 @@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_cloudtrail.aws_cloudtrail import (+ AwsCloudTrailResumeConfig,+ aws_cloudtrail_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cloudtrail.settings import (+ ACCESS_DENIED_CODES,+ CLOUDTRAIL_API_VERSION,+ CREDENTIAL_ERRORS,+ ENDPOINT_DESCRIPTIONS,+ ENDPOINTS,+ 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, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awscloudtrail import (AwsCloudTrailSourceConfig,)@@ -10,18 +38,137 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AwsCloudTrailSource(SimpleSource[AwsCloudTrailSourceConfig]):+class AwsCloudTrailSource(ResumableSource[AwsCloudTrailSourceConfig, AwsCloudTrailResumeConfig]):+ lists_tables_without_credentials = True+ supported_versions = (CLOUDTRAIL_API_VERSION,)+ default_version = CLOUDTRAIL_API_VERSION+ api_docs_url = "https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/Welcome.html"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.AWSCLOUDTRAIL+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ errors: dict[str, str | None] = {+ f"AWS CloudTrail request failed: {code}": message for code, message in CREDENTIAL_ERRORS.items()+ }+ errors.update(+ {+ f"AWS CloudTrail request failed: {code}": "Grant cloudtrail:LookupEvents, cloudtrail:DescribeTrails, or cloudtrail:ListEventDataStores for the tables you select."+ for code in ACCESS_DENIED_CODES+ }+ )+ return errors++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cloudtrail.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: AwsCloudTrailSourceConfig,+ 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: AwsCloudTrailSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_credentials(+ config.aws_access_key_id,+ config.aws_secret_access_key,+ config.aws_session_token,+ config.region,+ self.resolve_api_version(api_version),+ schema_name,+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AwsCloudTrailResumeConfig]:+ return ResumableSourceManager(inputs, AwsCloudTrailResumeConfig)++ def source_for_pipeline(+ self,+ config: AwsCloudTrailSourceConfig,+ resumable_source_manager: ResumableSourceManager[AwsCloudTrailResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return aws_cloudtrail_source(+ access_key_id=config.aws_access_key_id,+ secret_access_key=config.aws_secret_access_key,+ session_token=config.aws_session_token,+ region=config.region,+ api_version=self.resolve_api_version(inputs.api_version),+ endpoint_name=inputs.schema_name,+ manager=resumable_source_manager,+ last_value=inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.AWSCLOUDTRAIL,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="AWS CloudTrail",+ caption="""Sync CloudTrail events and settings from one AWS region.++Grant `cloudtrail:LookupEvents`, `cloudtrail:DescribeTrails`, and `cloudtrail:ListEventDataStores` for the tables you select.+Enter an access key ID and secret access key. Add a session token for temporary credentials.++Event imports cover the past 90 days. They include management events and trail Insights events, but exclude data events.+Insights must be enabled on a trail to return Insights events.+The event stores table imports CloudTrail Lake settings, not stored events.+CloudTrail Lake is available only to existing customers after May 31, 2026.""",iconPath="/static/services/aws_cloudtrail.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/aws-cloudtrail",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["aws", "cloudtrail", "audit", "events"],+ 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. Update them before scheduled imports run.",+ ),+ SourceFieldInputConfig(+ name="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_cloudtrail/tests/test_aws_cloudtrail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cloudtrail/tests/test_aws_cloudtrail.pynew file mode 100644index 000000000000..d837fcf30e17--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_cloudtrail/tests/test_aws_cloudtrail.py@@ -0,0 +1,402 @@+import json+import datetime as dt+from collections.abc import Iterable, Iterator+from typing import Any, cast++import pytest+import time_machine+from unittest.mock import Mock, patch++import requests+import structlog+from botocore.loaders import Loader++from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cloudtrail import aws_cloudtrail as transport+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cloudtrail.aws_cloudtrail import (+ AwsCloudTrailClient,+ AwsCloudTrailError,+ AwsCloudTrailResumeConfig,+ AwsCloudTrailThrottled,+ error_for_response,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cloudtrail.settings import (+ AWS_CLOUDTRAIL_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_cloudtrail.source import AwsCloudTrailSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awscloudtrail import (+ AwsCloudTrailSourceConfig,+)++NOW = dt.datetime(2026, 10, 1, tzinfo=dt.UTC)+++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[Mock]:+ with patch.object(transport, "make_tracked_session") as factory, patch.object(transport.time, "sleep"):+ factory.return_value.post.return_value = response({})+ yield factory.return_value+++def manager(state: AwsCloudTrailResumeConfig | None = None) -> Mock:+ result = Mock(spec=ResumableSourceManager)+ result.load_state.return_value = state+ return result+++def client(+ region: str = "eu-west-1", version: str = "2013-11-01", token: str | None = "fake-token"+) -> AwsCloudTrailClient:+ return AwsCloudTrailClient("AKIAEXAMPLE", "fake-secret", token, region, version)+++def payloads(session: Mock) -> list[dict[str, Any]]:+ return [json.loads(call.kwargs["data"]) for call in session.post.call_args_list]+++ "region,suffix",+ [("eu-west-1", "amazonaws.com"), ("cn-north-1", "amazonaws.com.cn"), ("us-gov-west-1", "amazonaws.com")],+)[email protected]("token", [None, "fake-session-token"])+def test_signed_json_request_matches_aws_service_model(+ session: Mock, region: str, suffix: str, token: str | None+) -> None:+ api = client(region, token=token)+ api.request("LookupEvents", {"MaxResults": 50})+ call = session.post.call_args+ headers = call.kwargs["headers"]+ metadata = Loader().load_service_model("cloudtrail", "service-2")["metadata"]+ assert call.args == (f"https://cloudtrail.{region}.{suffix}/",)+ assert headers["X-Amz-Target"] == f"{metadata['targetPrefix']}.LookupEvents"+ assert headers["Content-Type"] == f"application/x-amz-json-{metadata['jsonVersion']}"+ assert f"/{region}/cloudtrail/aws4_request" in headers["Authorization"]+ assert headers["Authorization"].startswith("AWS4-HMAC-SHA256 Credential=AKIAEXAMPLE/")+ assert headers.get("X-Amz-Security-Token") == token+ assert "X-Amz-Date" in headers+ assert call.kwargs["allow_redirects"] is False+ assert payloads(session) == [{"MaxResults": 50}]++[email protected]("region", ["https://example.com", "us-east-1.example.com", "us-east-1/", "us-east-1@evil", ""])+def test_invalid_region_never_sends_credentials(session: Mock, region: str) -> None:+ with pytest.raises(ValueError, match="valid AWS region"):+ client(region)+ session.post.assert_not_called()+++def test_unsupported_version_never_sends_request(session: Mock) -> None:+ with pytest.raises(ValueError, match="Unsupported AWS CloudTrail API version"):+ client(version="2099-01-01")+ session.post.assert_not_called()+++ "endpoint,key,id_key",+ [+ ("events", "Events", "EventId"),+ ("insight_events", "Events", "EventId"),+ ("event_data_stores", "EventDataStores", "EventDataStoreArn"),+ ],+)+def test_pagination_includes_empty_and_terminal_pages(session: Mock, endpoint: str, key: str, id_key: str) -> None:+ session.post.side_effect = [+ response({key: [{id_key: "one"}], "NextToken": "second"}),+ response({key: [], "NextToken": "third"}),+ response({key: [{id_key: "three"}]}),+ ]+ resume = manager()+ batches = list(get_rows(client(), AWS_CLOUDTRAIL_ENDPOINTS[endpoint], resume, None))+ assert len(batches) == 2+ assert [params.get("NextToken") for params in payloads(session)] == [None, "second", "third"]+ assert resume.save_state.call_count == 3+ assert resume.save_state.call_args.args[0].finished+ assert resume.safe_point.call_count == 3+ resume.clear_state.assert_not_called()+ session.close.assert_called_once()+ if endpoint == "insight_events":+ assert all(params["EventCategory"] == "insight" for params in payloads(session))+ elif endpoint == "events":+ assert all("EventCategory" not in params for params in payloads(session))+++ "last_value",+ [+ NOW - dt.timedelta(days=1),+ "2026-09-30T00:00:00Z",+ (NOW - dt.timedelta(days=1)).timestamp(),+ dt.datetime(2026, 9, 30),+ ],+)+@time_machine.travel(NOW, tick=False)+def test_incremental_filter_is_identical_on_each_page(session: Mock, last_value: dt.datetime | str | float) -> None:+ session.post.side_effect = [response({"Events": [], "NextToken": "next"}), response({"Events": []})]+ list(get_rows(client(), AWS_CLOUDTRAIL_ENDPOINTS["events"], manager(), last_value))+ expected = {"MaxResults": 50, "StartTime": (NOW - dt.timedelta(days=1)).timestamp(), "EndTime": NOW.timestamp()}+ assert payloads(session) == [expected, {**expected, "NextToken": "next"}]+++@time_machine.travel(NOW, tick=False)+def test_incremental_filter_respects_retention_limit(session: Mock) -> None:+ list(get_rows(client(), AWS_CLOUDTRAIL_ENDPOINTS["events"], manager(), NOW - dt.timedelta(days=365)))+ assert payloads(session)[0]["StartTime"] == (NOW - dt.timedelta(days=90)).timestamp()++[email protected]("endpoint", ["events", "insight_events", "trails", "event_data_stores"])+def test_full_refresh_omits_watermark_through_pipeline(session: Mock, endpoint: str) -> None:+ source = AwsCloudTrailSource()+ inputs = SourceInputs(+ schema_name=endpoint,+ schema_id="schema",+ source_id="source",+ team_id=1,+ should_use_incremental_field=False,+ db_incremental_field_last_value=NOW,+ db_incremental_field_earliest_value=None,+ incremental_field="event_time",+ incremental_field_type=None,+ job_id="job",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+ config = AwsCloudTrailSourceConfig(+ aws_access_key_id="AKIAEXAMPLE", aws_secret_access_key="fake-secret", region="eu-west-1"+ )+ resume = manager()+ result = source.source_for_pipeline(config, resume, inputs)+ list(cast(Iterable[Any], result.items()))+ assert "StartTime" not in payloads(session)[0]+ resume.clear_state.assert_not_called()+ assert result.on_complete is not None+ result.on_complete()+ resume.clear_state.assert_called_once()+++def test_trails_use_single_non_paginated_request(session: Mock) -> None:+ session.post.return_value = response(+ {"trailList": [{"TrailARN": "arn:aws:cloudtrail:eu-west-1:000000000000:trail/example", "Name": "example"}]}+ )+ batches = list(get_rows(client(), AWS_CLOUDTRAIL_ENDPOINTS["trails"], manager(), NOW))+ assert payloads(session) == [{"includeShadowTrails": True}]+ assert batches[0][0]["trail_arn"].endswith("trail/example")+ assert batches[0][0]["region"] == "eu-west-1"+++def test_event_rows_preserve_event_details_and_parse_time(session: Mock) -> None:+ raw = '{"eventSource":"example.amazonaws.com","requestParameters":{}}'+ session.post.return_value = response(+ {"Events": [{"EventId": "one", "EventTime": NOW.timestamp(), "CloudTrailEvent": raw}]}+ )+ resume = manager()+ rows = get_rows(client(), AWS_CLOUDTRAIL_ENDPOINTS["events"], resume, None)+ assert next(rows) == [{"event_id": "one", "event_time": NOW, "cloud_trail_event": raw, "region": "eu-west-1"}]+ assert resume.save_state.call_args.args[0].finished+ list(rows)+++def test_store_timestamps_are_normalized(session: Mock) -> None:+ session.post.return_value = response(+ {+ "EventDataStores": [+ {"EventDataStoreArn": "store", "CreatedTimestamp": NOW.timestamp(), "UpdatedTimestamp": NOW.timestamp()}+ ]+ }+ )+ batches = list(get_rows(client(), AWS_CLOUDTRAIL_ENDPOINTS["event_data_stores"], manager(), None))+ assert len(batches) == 1+ rows = batches[0]+ assert rows[0]["created_timestamp"] == NOW+ assert rows[0]["updated_timestamp"] == NOW+ assert rows[0]["event_data_store_arn"] == "store"+++@time_machine.travel(NOW, tick=False)+def test_resume_preserves_original_time_window(session: Mock) -> None:+ state = AwsCloudTrailResumeConfig(next_token="saved", start_time=100, end_time=200)+ list(get_rows(client(), AWS_CLOUDTRAIL_ENDPOINTS["events"], manager(state), NOW))+ assert payloads(session) == [{"MaxResults": 50, "StartTime": 100, "EndTime": 200, "NextToken": "saved"}]+++def test_completed_checkpoint_does_not_fetch_again(session: Mock) -> None:+ assert (+ list(+ get_rows(+ client(), AWS_CLOUDTRAIL_ENDPOINTS["events"], manager(AwsCloudTrailResumeConfig(finished=True)), None+ )+ )+ == []+ )+ session.post.assert_not_called()+ session.close.assert_called_once()+++def test_expired_resume_token_restarts_same_window(session: Mock) -> None:+ session.post.side_effect = [response({"__type": "InvalidNextTokenException"}, 400), response({"Events": []})]+ state = AwsCloudTrailResumeConfig(next_token="expired", start_time=100, end_time=200)+ list(get_rows(client(), AWS_CLOUDTRAIL_ENDPOINTS["events"], manager(state), None))+ assert payloads(session) == [+ {"MaxResults": 50, "StartTime": 100, "EndTime": 200, "NextToken": "expired"},+ {"MaxResults": 50, "StartTime": 100, "EndTime": 200},+ ]+++def test_fresh_invalid_token_is_not_silently_restarted(session: Mock) -> None:+ session.post.return_value = response({"__type": "InvalidNextTokenException"}, 400)+ with pytest.raises(AwsCloudTrailError, match="InvalidNextTokenException"):+ list(get_rows(client(), AWS_CLOUDTRAIL_ENDPOINTS["events"], manager(), None))+ assert session.post.call_count == 1+++def test_repeated_token_fails_without_infinite_loop(session: Mock) -> None:+ session.post.return_value = response({"Events": [], "NextToken": "same"})+ with pytest.raises(ValueError, match="repeated page token"):+ list(get_rows(client(), AWS_CLOUDTRAIL_ENDPOINTS["events"], manager(), None))+ assert session.post.call_count == 2+++ "code,status,retryable",+ [+ ("ThrottlingException", 400, True),+ ("Throttling", 400, True),+ ("ThrottlingException", 429, False),+ ("InternalError", 500, False),+ ("AccessDeniedException", 400, False),+ ("UnrecognizedClientException", 400, False),+ ],+)+def test_only_body_throttles_get_application_retries(code: str, status: int, retryable: bool) -> None:+ error = error_for_response(response({"__type": f"com.amazonaws.cloudtrail#{code}"}, status))+ assert error.code == code+ assert isinstance(error, AwsCloudTrailThrottled) is retryable+++def test_error_header_takes_precedence_and_handles_non_json() -> None:+ result = response({}, 403, {"x-amzn-ErrorType": "AccessDeniedException:http"})+ result._content = b"not JSON"+ assert error_for_response(result).code == "AccessDeniedException"+++def test_throttle_retries_then_succeeds(session: Mock) -> None:+ session.post.side_effect = [response({"__type": "ThrottlingException"}, 400), response({"Events": []})]+ with patch.object(cast(Any, AwsCloudTrailClient.request).retry, "sleep"):+ assert client().request("LookupEvents", {"MaxResults": 50}) == {"Events": []}+ assert session.post.call_count == 2+++def test_lookup_requests_are_spaced(session: Mock) -> None:+ with (+ patch.object(transport.time, "monotonic", return_value=10.0) as monotonic,+ patch.object(transport.time, "sleep") as sleep,+ ):+ api = client()+ api.request("LookupEvents", {})+ monotonic.return_value = 10.1+ api.request("LookupEvents", {})+ sleep.assert_called_once()+ assert sleep.call_args.args[0] == pytest.approx(0.4)++[email protected]("code", ["AccessDenied", "AccessDeniedException"])+ "schema_name,valid",+ [(None, True), ("events", False), ("insight_events", False), ("trails", False), ("event_data_stores", False)],+)+def test_access_denial_only_accepts_source_creation(+ session: Mock, code: str, schema_name: str | None, valid: bool+) -> None:+ session.post.return_value = response({"__type": code}, 400)+ ok, reason = validate_credentials("key", "secret", None, "eu-west-1", "2013-11-01", schema_name)+ assert ok is valid+ if schema_name is not None:+ assert reason is not None+ assert f"cloudtrail:{AWS_CLOUDTRAIL_ENDPOINTS[schema_name].operation}" in reason+ else:+ assert reason is None+ assert session.post.call_count == 1+ session.close.assert_called_once()+++ "code,message",+ [+ ("UnrecognizedClientException", "access key"),+ ("InvalidSignatureException", "signature"),+ ("ExpiredTokenException", "expired"),+ ("SubscriptionRequiredException", "subscription"),+ ("OptInRequired", "Enable access"),+ ("OperationNotPermittedException", "permissions"),+ ],+)+def test_credentials_errors_are_actionable_and_terminal(session: Mock, code: str, message: str) -> None:+ session.post.return_value = response({"__type": code}, 400)+ valid, reason = validate_credentials("key", "secret", None, "eu-west-1", "2013-11-01")+ assert not valid+ assert reason is not None and message in reason+ error = error_for_response(session.post.return_value)+ mapped = [+ value for pattern, value in AwsCloudTrailSource().get_non_retryable_errors().items() if pattern in str(error)+ ]+ assert mapped and all(mapped)+++ "schema_name,target,params",+ [+ (None, "DescribeTrails", {"includeShadowTrails": True}),+ ("events", "LookupEvents", {"MaxResults": 1}),+ ("insight_events", "LookupEvents", {"MaxResults": 1, "EventCategory": "insight"}),+ ("event_data_stores", "ListEventDataStores", {"MaxResults": 1}),+ ],+)+def test_validation_uses_one_cheap_probe(+ session: Mock, schema_name: str | None, target: str, params: dict[str, Any]+) -> None:+ assert validate_credentials("key", "secret", None, "eu-west-1", "2013-11-01", schema_name) == (True, None)+ assert session.post.call_count == 1+ assert session.post.call_args.kwargs["headers"]["X-Amz-Target"].endswith(f".{target}")+ assert payloads(session) == [params]+++ "key,secret,region,schema,message",+ [+ ("", "secret", "eu-west-1", None, "access key"),+ ("key", "", "eu-west-1", None, "access key"),+ ("key", "secret", "bad", None, "region"),+ ("key", "secret", "eu-west-1", "missing", "Unknown"),+ ],+)+def test_invalid_setup_fails_before_network(+ session: Mock, key: str, secret: str, region: str, schema: str | None, message: str+) -> None:+ valid, reason = validate_credentials(key, secret, None, region, "2013-11-01", schema)+ assert not valid+ assert reason is not None and message in reason+ session.post.assert_not_called()+++def test_connection_error_has_useful_message(session: Mock) -> None:+ session.post.side_effect = requests.ConnectionError("offline")+ valid, reason = validate_credentials("key", "secret", None, "eu-west-1", "2013-11-01")+ assert not valid+ assert reason is not None and "region" in reason+ session.close.assert_called_once()+++def test_unknown_pipeline_table_fails_before_network(session: Mock) -> None:+ with pytest.raises(ValueError, match="Unknown AWS CloudTrail table"):+ transport.aws_cloudtrail_source("key", "secret", None, "eu-west-1", "2013-11-01", "missing", manager(), None)+ session.post.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awscloudtrail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awscloudtrail.pyindex 3e2ad8390169..b93d0a3cbabb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awscloudtrail.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awscloudtrail.py@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass AwsCloudTrailSourceConfig(config.Config):- pass+ aws_access_key_id: str+ aws_secret_access_key: str+ region: str+ aws_session_token: str | None = None