: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(warehouse-sources): implement aws_ses source (#79766)
jake sciotto46c9cd917e09
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 59bf878cf572..7cd02819089d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -93,6 +93,7 @@ the row lists both.| aviator | HTTP | requests | ✅ || awin | HTTP | requests | ✅ || aws_cost_explorer | HTTP | requests | ✅ |+| aws_ses | HTTP | requests | ✅ || azure_devops | HTTP | requests | ✅ || babelforce | HTTP | requests | ✅ || bamboohr | HTTP | requests | ✅ |@@ -807,7 +808,6 @@ doesn't conflict with concurrent PRs.- aws_sagemaker- aws_savings_plans- aws_security_hub-- aws_ses- aws_step_functions- aws_support- aws_systems_managerdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/aws_ses.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/aws_ses.pynew file mode 100644index 000000000000..9e073d68e3ac--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/aws_ses.py@@ -0,0 +1,451 @@+import re+import datetime as dt+import dataclasses+from collections.abc import Callable, Iterator+from typing import Any, Optional+from urllib.parse import quote, urlencode++import requests+from botocore.auth import SigV4Auth+from botocore.awsrequest import AWSRequest+from botocore.credentials import Credentials+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.sources.aws_ses.settings import (+ AWS_SES_ENDPOINTS,+ REGION_PATTERN,+ REQUEST_TIMEOUT_SECONDS,+ SES_ENDPOINT_TEMPLATE,+ SES_SIGNING_NAME,+ AwsSesEndpointConfig,+)+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++# SESv2 returns TooManyRequestsException as HTTP 429 and its read APIs throttle at roughly one+# request per second, so 429 gets more headroom than the tracked session's default policy.+TRANSPORT_RETRY = BoundedRetry(+ total=5,+ backoff_factor=1,+ status_forcelist=(429, 500, 502, 503, 504),+ allowed_methods=frozenset(["GET"]),+ raise_on_status=False,+)++# Rewind applied to the stored watermark before it becomes `StartDate`: the filter's boundary+# semantics are undocumented, and merge on the primary key absorbs the re-read rows.+INCREMENTAL_OVERLAP = dt.timedelta(days=1)++_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")++_IAM_ACTION_PATTERN = re.compile(r"ses:[A-Za-z0-9]+")++# Codes that mean the key itself is bad, as opposed to a valid key missing an IAM permission.+_CREDENTIAL_ERROR_CODES = (+ "UnrecognizedClientException",+ "InvalidClientTokenId",+ "SignatureDoesNotMatch",+ "InvalidSignatureException",+ "ExpiredTokenException",+)+++class AwsSesError(Exception):+ pass++[email protected](frozen=True)+class AwsSesResumeConfig:+ """Pagination token for the next page to request; `None` once a walk completed."""++ next_token: Optional[str] = None+++def validate_region(region: str) -> str:+ """Return the region if it is a well-formed AWS region code, else raise.++ The region is interpolated into the request host, so anything outside the region alphabet+ could point the signed request at a host we don't control.+ """+ normalized = (region or "").strip()+ if not REGION_PATTERN.match(normalized):+ raise ValueError(f"Invalid AWS region: {region!r}")+ return normalized+++def _snake(name: str) -> str:+ """`IdentityName` -> `identity_name`, `SOARecord` -> `soa_record`."""+ return _CAMEL_BOUNDARY.sub("_", name).lower()+++def _parse_timestamp(value: Any) -> Any:+ """SESv2 serializes timestamps as epoch seconds; keep anything unrecognized untouched."""+ if isinstance(value, int | float) and not isinstance(value, bool):+ return dt.datetime.fromtimestamp(value, tz=dt.UTC)+ if isinstance(value, str) and value:+ try:+ parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return value+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=dt.UTC)+ return value+++def coerce_datetime(value: Any) -> Optional[dt.datetime]:+ if isinstance(value, dt.datetime):+ return value if value.tzinfo is not None else value.replace(tzinfo=dt.UTC)+ if isinstance(value, dt.date):+ return dt.datetime(value.year, value.month, value.day, tzinfo=dt.UTC)+ if isinstance(value, int | float) and not isinstance(value, bool):+ return dt.datetime.fromtimestamp(value, tz=dt.UTC)+ if isinstance(value, str) and value:+ try:+ parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=dt.UTC)+ return None+++def _flatten(prefix: str, obj: dict[str, Any], raw_keys: frozenset[str]) -> dict[str, Any]:+ flattened: dict[str, Any] = {}+ for key, value in obj.items():+ column = f"{prefix}_{_snake(key)}" if prefix else _snake(key)+ if isinstance(value, dict) and key not in raw_keys:+ flattened.update(_flatten(column, value, raw_keys))+ else:+ flattened[column] = value+ return flattened+++def normalize_row(endpoint_config: AwsSesEndpointConfig, obj: dict[str, Any]) -> dict[str, Any]:+ """Flatten nested structures into snake_case columns and parse epoch timestamps."""+ row = _flatten("", obj, endpoint_config.raw_keys)+ for column in endpoint_config.timestamp_columns:+ if column in row:+ row[column] = _parse_timestamp(row[column])+ return row+++def _error_code(response: requests.Response) -> str:+ header = response.headers.get("x-amzn-ErrorType") or ""+ if header:+ return header.split(":")[0].split("#")[-1]+ try:+ body = response.json()+ except ValueError:+ return f"HTTP {response.status_code}"+ raw = body.get("__type") or body.get("code") or f"HTTP {response.status_code}"+ return str(raw).split("#")[-1]+++def _error_message(response: requests.Response) -> str:+ try:+ body = response.json()+ except ValueError:+ return response.text[:500]+ message = body.get("message") or body.get("Message") or ""+ return str(message)[:500]+++def error_for_response(response: requests.Response) -> AwsSesError:+ return AwsSesError(f"Amazon SES request failed: {_error_code(response)} - {_error_message(response)}")+++def make_session(secret_access_key: str, session_token: Optional[str]) -> requests.Session:+ redact = tuple(value for value in (secret_access_key, session_token) if value)+ return make_tracked_session(retry=TRANSPORT_RETRY, redact_values=redact)+++def send_request(+ session: requests.Session,+ credentials: Credentials,+ region: str,+ path: str,+ params: Optional[dict[str, Any]] = None,+) -> dict[str, Any]:+ """Sign one SESv2 GET with SigV4 and send it over the tracked session."""+ url = SES_ENDPOINT_TEMPLATE.format(region=region) + path+ if params:+ # Encoded exactly like the SigV4 canonical query string (RFC 3986, sorted keys), so the+ # URL that is signed is byte-identical to the one that is sent.+ url = f"{url}?{urlencode(sorted(params.items()), quote_via=quote, safe='-_.~')}"++ aws_request = AWSRequest(method="GET", url=url)+ SigV4Auth(credentials, SES_SIGNING_NAME, region).add_auth(aws_request)++ response = session.get(url, headers=dict(aws_request.headers.items()), timeout=REQUEST_TIMEOUT_SECONDS)+ if response.status_code >= 400:+ raise error_for_response(response)+ return response.json()+++def resolve_start_date(+ should_use_incremental_field: bool, db_incremental_field_last_value: Any+) -> Optional[dt.datetime]:+ if not should_use_incremental_field:+ return None+ watermark = coerce_datetime(db_incremental_field_last_value)+ if watermark is None:+ return None+ return watermark - INCREMENTAL_OVERLAP+++def _fanout_page_rows(+ session: requests.Session,+ credentials: Credentials,+ region: str,+ endpoint_config: AwsSesEndpointConfig,+ body: dict[str, Any],+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ """One full row per listed item, fetched via the endpoint's detail operation."""+ assert endpoint_config.detail_path is not None and endpoint_config.name_column is not None++ rows: list[dict[str, Any]] = []+ for item in body.get(endpoint_config.result_key or "") or []:+ name = item.get(endpoint_config.item_name_key) if isinstance(item, dict) else item+ if not isinstance(name, str) or not name:+ continue++ try:+ detail = send_request(+ session, credentials, region, endpoint_config.detail_path.format(name=quote(name, safe=""))+ )+ except AwsSesError as error:+ if "NotFoundException" in str(error):+ logger.debug(f"Skipping {endpoint_config.name} item deleted mid-sync. name={name}")+ continue+ raise++ row = normalize_row(endpoint_config, item) if isinstance(item, dict) else {}+ row.update(normalize_row(endpoint_config, detail))+ # Detail responses (GetEmailIdentity) do not echo the item name back.+ row[endpoint_config.name_column] = name+ rows.append(row)+ return rows+++def _walk_pages(+ session: requests.Session,+ credentials: Credentials,+ region: str,+ endpoint_config: AwsSesEndpointConfig,+ params: dict[str, Any],+ rows_for_body: Callable[[dict[str, Any]], list[dict[str, Any]]],+ resumable_source_manager: ResumableSourceManager[AwsSesResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ next_token = resume.next_token if resume is not None else None+ resumed_token = next_token is not None+ if resumed_token:+ logger.debug(f"Resuming Amazon SES sync from a saved page token. endpoint={endpoint_config.name}")++ while True:+ page_params = dict(params)+ if next_token:+ page_params["NextToken"] = next_token++ try:+ body = send_request(session, credentials, region, endpoint_config.path, page_params)+ except AwsSesError as error:+ # A token saved by a previous attempt can expire; restart the walk instead of+ # failing the job. Merge on the primary key absorbs the re-read rows.+ if resumed_token and "InvalidNextTokenException" in str(error):+ logger.debug(f"Saved page token no longer valid; restarting. endpoint={endpoint_config.name}")+ next_token = None+ resumed_token = False+ resumable_source_manager.clear_state()+ continue+ raise+ resumed_token = False++ rows = rows_for_body(body)+ if rows:+ yield rows++ next_token = body.get("NextToken")+ # Saved after yielding: a crash re-yields the last page, which merges away on the+ # primary key, rather than skipping it.+ resumable_source_manager.save_state(AwsSesResumeConfig(next_token=next_token))+ if not next_token:+ break++ resumable_source_manager.clear_state()+++def get_rows(+ aws_access_key_id: str,+ aws_secret_access_key: str,+ aws_session_token: Optional[str],+ aws_region: str,+ endpoint: str,+ resumable_source_manager: ResumableSourceManager[AwsSesResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ endpoint_config = AWS_SES_ENDPOINTS[endpoint]+ region = validate_region(aws_region)+ session = make_session(aws_secret_access_key, aws_session_token)+ credentials = Credentials(aws_access_key_id, aws_secret_access_key, aws_session_token or None)++ if endpoint_config.page_size is None:+ yield [normalize_row(endpoint_config, send_request(session, credentials, region, endpoint_config.path))]+ return++ params: dict[str, Any] = {"PageSize": endpoint_config.page_size}+ if endpoint_config.supports_start_date:+ start_date = resolve_start_date(should_use_incremental_field, db_incremental_field_last_value)+ if start_date is not None:+ params["StartDate"] = start_date.astimezone(dt.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")++ def rows_for_body(body: dict[str, Any]) -> list[dict[str, Any]]:+ if endpoint_config.detail_path:+ return _fanout_page_rows(session, credentials, region, endpoint_config, body, logger)+ return [normalize_row(endpoint_config, item) for item in body.get(endpoint_config.result_key or "") or []]++ yield from _walk_pages(+ session, credentials, region, endpoint_config, params, rows_for_body, resumable_source_manager, logger+ )+++def _permission_reason(error: AwsSesError) -> Optional[str]:+ text = str(error)+ if "AccessDeniedException" in text:+ match = _IAM_ACTION_PATTERN.search(text)+ if match:+ return f"Missing IAM permission {match.group(0)}"+ return "The connected IAM user or role is not allowed to read this table"+ if any(code in text for code in _CREDENTIAL_ERROR_CODES):+ return "AWS rejected the access key. Please check the access key ID and secret access key."+ return None+++def endpoint_permission_reason(+ session: requests.Session,+ credentials: Credentials,+ region: str,+ endpoint_config: AwsSesEndpointConfig,+) -> Optional[str]:+ """Probe the calls a sync of this endpoint issues. `None` when reachable.++ Only a real denial counts as unreachable: throttles, 5xx and network errors leave the+ endpoint reported as reachable, so a blip can't hide tables from the schema picker.+ """+ try:+ if endpoint_config.page_size is None:+ send_request(session, credentials, region, endpoint_config.path)+ return None++ body = send_request(session, credentials, region, endpoint_config.path, {"PageSize": 1})+ if endpoint_config.detail_path:+ for item in (body.get(endpoint_config.result_key or "") or [])[:1]:+ name = item.get(endpoint_config.item_name_key) if isinstance(item, dict) else item+ if isinstance(name, str) and name:+ send_request(+ session, credentials, region, endpoint_config.detail_path.format(name=quote(name, safe=""))+ )+ except AwsSesError as error:+ return _permission_reason(error)+ except Exception:+ return None+ return None+++def probe_endpoint_permissions(+ aws_access_key_id: str,+ aws_secret_access_key: str,+ aws_session_token: Optional[str],+ aws_region: str,+ endpoints: list[str],+) -> dict[str, str | None]:+ try:+ region = validate_region(aws_region)+ except ValueError:+ return dict.fromkeys(endpoints)++ session = make_session(aws_secret_access_key, aws_session_token)+ credentials = Credentials(aws_access_key_id, aws_secret_access_key, aws_session_token or None)++ reasons: dict[str, str | None] = {}+ for endpoint in endpoints:+ endpoint_config = AWS_SES_ENDPOINTS.get(endpoint)+ reasons[endpoint] = (+ endpoint_permission_reason(session, credentials, region, endpoint_config)+ if endpoint_config is not None+ else None+ )+ return reasons+++def validate_credentials(+ aws_access_key_id: str,+ aws_secret_access_key: str,+ aws_session_token: Optional[str],+ aws_region: str,+ schema_name: Optional[str] = None,+) -> tuple[bool, Optional[str]]:+ if not aws_access_key_id or not aws_secret_access_key:+ return False, "AWS access key ID and secret access key are required"++ try:+ region = validate_region(aws_region)+ except ValueError:+ return False, f"'{aws_region}' isn't a valid AWS region. Use a region code like us-east-1."++ session = make_session(aws_secret_access_key, aws_session_token)+ credentials = Credentials(aws_access_key_id, aws_secret_access_key, aws_session_token or None)++ if schema_name is not None and schema_name in AWS_SES_ENDPOINTS:+ reason = endpoint_permission_reason(session, credentials, region, AWS_SES_ENDPOINTS[schema_name])+ return reason is None, reason++ try:+ send_request(session, credentials, region, AWS_SES_ENDPOINTS["account"].path)+ except AwsSesError as error:+ # A denied GetAccount still proves the key is genuine; per-table access is reported in+ # the schema picker instead of blocking source creation.+ if "AccessDeniedException" in str(error):+ return True, None+ return False, str(error)+ except Exception:+ return False, "Could not reach the Amazon SES API. Check the AWS region and try again."++ return True, None+++def aws_ses_source(+ aws_access_key_id: str,+ aws_secret_access_key: str,+ aws_session_token: Optional[str],+ aws_region: str,+ endpoint: str,+ resumable_source_manager: ResumableSourceManager[AwsSesResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ logger: FilteringBoundLogger,+) -> SourceResponse:+ endpoint_config = AWS_SES_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ aws_access_key_id=aws_access_key_id,+ aws_secret_access_key=aws_secret_access_key,+ aws_session_token=aws_session_token,+ aws_region=aws_region,+ endpoint=endpoint,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ logger=logger,+ ),+ primary_keys=endpoint_config.primary_key,+ # AWS documents no ordering for these list APIs, so the incremental watermark must only+ # commit once a walk completes; "desc" gives exactly that single end-of-run commit.+ sort_mode="desc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/canonical_descriptions.pynew file mode 100644index 000000000000..5442692ab7f8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/canonical_descriptions.py@@ -0,0 +1,90 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "account": {+ "description": "A snapshot of the SES account's sending status, quota, and reputation enforcement in the connected AWS Region. One row per sync.",+ "docs_url": "https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetAccount.html",+ "columns": {+ "dedicated_ip_auto_warmup_enabled": "Whether the automatic warm-up feature is enabled for dedicated IP addresses associated with the account.",+ "enforcement_status": "The reputation status of the account: HEALTHY, PROBATION, or SHUTDOWN.",+ "production_access_enabled": "Whether the account has production access in the Region. False means the account is still in the sandbox.",+ "sending_enabled": "Whether email sending is enabled for the account in the Region.",+ "send_quota_max24_hour_send": "The maximum number of emails that can be sent in the Region over a 24-hour period. -1 means an unlimited quota.",+ "send_quota_max_send_rate": "The maximum number of emails that can be sent per second in the Region.",+ "send_quota_sent_last24_hours": "The number of emails sent from the account in the Region over the past 24 hours.",+ "suppression_attributes_suppressed_reasons": "The reasons (BOUNCE, COMPLAINT) that cause email addresses to be automatically added to the account's suppression list.",+ "details_mail_type": "The type of email the account sends: MARKETING or TRANSACTIONAL.",+ "details_website_url": "The URL of the sender's website, as submitted in the account details.",+ "details_contact_language": "The preferred language for support cases: ENGLISH or JAPANESE.",+ "details_use_case_description": "A description of the types of email the account plans to send.",+ "details_additional_contact_email_addresses": "Additional email addresses where updates about the account review process are sent.",+ "details_review_details_status": "The status of the latest account review: PENDING, GRANTED, DENIED, or FAILED.",+ "details_review_details_case_id": "The support center case ID associated with the account review, if any.",+ "vdm_attributes_vdm_enabled": "Whether Virtual Deliverability Manager is enabled for the account.",+ "vdm_attributes_dashboard_attributes_engagement_metrics": "Whether VDM engagement metrics collection is enabled for the account.",+ "vdm_attributes_guardian_attributes_optimized_shared_delivery": "Whether VDM optimized shared delivery is enabled for the account.",+ },+ },+ "configuration_sets": {+ "description": "Configuration sets, the groups of rules applied to the emails sent through them, with their tracking, delivery, reputation, sending, and suppression options.",+ "docs_url": "https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetConfigurationSet.html",+ "columns": {+ "configuration_set_name": "The name of the configuration set.",+ "tracking_options_custom_redirect_domain": "The custom domain used for tracking open and click events.",+ "tracking_options_https_policy": "The https policy used for tracking open and click events.",+ "delivery_options_tls_policy": "Whether messages that use the configuration set require a TLS connection: REQUIRE or OPTIONAL.",+ "delivery_options_sending_pool_name": "The dedicated IP pool associated with the configuration set.",+ "delivery_options_max_delivery_seconds": "The maximum amount of time, in seconds, that SES attempts delivery of email.",+ "reputation_options_reputation_metrics_enabled": "Whether tracking of reputation metrics is enabled for the configuration set.",+ "reputation_options_last_fresh_start": "When the configuration set's reputation metrics were last given a fresh start.",+ "sending_options_sending_enabled": "Whether email sending is enabled for the configuration set.",+ "suppression_options_suppressed_reasons": "The reasons (BOUNCE, COMPLAINT) that cause addresses to be automatically suppressed for this configuration set.",+ "vdm_options_dashboard_options_engagement_metrics": "Whether VDM engagement metrics collection is enabled for the configuration set.",+ "vdm_options_guardian_options_optimized_shared_delivery": "Whether VDM optimized shared delivery is enabled for the configuration set.",+ "archiving_options_archive_arn": "The ARN of the MailManager archive where sent emails are archived.",+ "tags": "The tags (keys and values) associated with the configuration set, as JSON.",+ },+ },+ "email_identities": {+ "description": "The email identities (domains and addresses) registered with the account, with their DKIM, MAIL FROM, and verification details.",+ "docs_url": "https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_GetEmailIdentity.html",+ "columns": {+ "identity_name": "The address or domain of the identity.",+ "identity_type": "The identity type: EMAIL_ADDRESS or DOMAIN.",+ "sending_enabled": "Whether email can currently be sent from the identity.",+ "verification_status": "The verification status of the identity: PENDING, SUCCESS, FAILED, TEMPORARY_FAILURE, or NOT_STARTED.",+ "verified_for_sending_status": "Whether the identity is verified. Email can only be sent from verified addresses or domains.",+ "feedback_forwarding_status": "Whether bounce and complaint notifications are forwarded by email for this identity.",+ "configuration_set_name": "The configuration set used by default when sending from this identity.",+ "dkim_attributes_signing_enabled": "Whether messages sent from the identity are signed using DKIM.",+ "dkim_attributes_status": "Whether SES has located the DKIM records in the domain's DNS: PENDING, SUCCESS, FAILED, TEMPORARY_FAILURE, or NOT_STARTED.",+ "dkim_attributes_tokens": "The Easy DKIM tokens used to create the CNAME records for the domain, as JSON.",+ "dkim_attributes_signing_attributes_origin": "How DKIM was configured for the identity: AWS_SES (Easy DKIM) or EXTERNAL (BYODKIM).",+ "dkim_attributes_current_signing_key_length": "The key length of the DKIM key pair in use.",+ "dkim_attributes_next_signing_key_length": "The key length of the future DKIM key pair to be generated.",+ "dkim_attributes_last_key_generation_timestamp": "The last time an Easy DKIM key pair was generated for the identity.",+ "mail_from_attributes_mail_from_domain": "The custom MAIL FROM domain used by the identity.",+ "mail_from_attributes_mail_from_domain_status": "The status of the MAIL FROM domain: PENDING, SUCCESS, FAILED, or TEMPORARY_FAILURE.",+ "mail_from_attributes_behavior_on_mx_failure": "The action taken when the MAIL FROM domain's MX record can't be found: USE_DEFAULT_VALUE or REJECT_MESSAGE.",+ "policies": "The sending authorization policies attached to the identity, as a JSON map of policy names to policy documents.",+ "tags": "The tags (keys and values) associated with the identity, as JSON.",+ "verification_info_last_checked_timestamp": "The last time a verification attempt was made for the identity.",+ "verification_info_last_success_timestamp": "The last time the identity was successfully verified.",+ "verification_info_error_type": "The reason the latest verification attempt failed, if any.",+ "verification_info_soa_record_primary_name_server": "The primary name server from the domain's SOA record.",+ "verification_info_soa_record_admin_email": "The administrative contact email from the domain's SOA record.",+ "verification_info_soa_record_serial_number": "The serial number from the domain's SOA record.",+ },+ },+ "suppressed_destinations": {+ "description": "Email addresses on the account-level suppression list. SES does not attempt delivery to these addresses. Addresses removed from the list upstream are not deleted from this table.",+ "docs_url": "https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_ListSuppressedDestinations.html",+ "columns": {+ "email_address": "The email address that is on the suppression list for the account.",+ "reason": "The reason the address was added to the suppression list: BOUNCE or COMPLAINT.",+ "last_update_time": "When the suppressed destination was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/settings.pynew file mode 100644index 000000000000..4a9a0894a70d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/settings.py@@ -0,0 +1,109 @@+import re+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# SES is a regional service: the user-configured region is interpolated into both the request+# host and the SigV4 signing scope.+SES_ENDPOINT_TEMPLATE = "https://email.{region}.amazonaws.com"+SES_SIGNING_NAME = "ses"+REGION_PATTERN = re.compile(r"^[a-z0-9-]+$")++REQUEST_TIMEOUT_SECONDS = 60+++@dataclass(frozen=True)+class AwsSesEndpointConfig:+ name: str+ # Path of the operation that produces this table's rows (a list path, or the object path+ # for single-row endpoints).+ path: str+ primary_key: list[str] | None+ # Response key holding the list of items. `None` for single-object endpoints, where the+ # whole response body is the row.+ result_key: str | None = None+ # `PageSize` per request. `None` for unpaginated single-object endpoints.+ page_size: int | None = None+ # Fan-out: per-item GET path with a `{name}` placeholder. The list call only returns+ # summaries (or bare names), so each item is fetched individually for the full row.+ detail_path: str | None = None+ # Fan-out: key of the item's name in the list response. `None` when list items are plain+ # name strings (ListConfigurationSets).+ item_name_key: str | None = None+ # Fan-out: column carrying the item name. Set explicitly on every row because detail+ # responses (GetEmailIdentity) do not echo the name back.+ name_column: str | None = None+ # ListSuppressedDestinations accepts a server-side `StartDate` filter, which is what makes+ # that endpoint genuinely incremental.+ supports_start_date: bool = False+ # Flattened columns holding epoch-seconds timestamps, parsed into datetimes.+ timestamp_columns: tuple[str, ...] = ()+ # Response members that are maps with caller-defined keys (e.g. `Policies`). Flattening+ # them would mint one column per map entry, so they are kept whole and stored as JSON.+ raw_keys: frozenset[str] = field(default_factory=frozenset)+++AWS_SES_ENDPOINTS: dict[str, AwsSesEndpointConfig] = {+ "account": AwsSesEndpointConfig(+ name="account",+ path="/v2/email/account",+ primary_key=None,+ ),+ "configuration_sets": AwsSesEndpointConfig(+ name="configuration_sets",+ path="/v2/email/configuration-sets",+ primary_key=["configuration_set_name"],+ result_key="ConfigurationSets",+ page_size=100,+ detail_path="/v2/email/configuration-sets/{name}",+ name_column="configuration_set_name",+ timestamp_columns=("reputation_options_last_fresh_start",),+ ),+ "email_identities": AwsSesEndpointConfig(+ name="email_identities",+ path="/v2/email/identities",+ primary_key=["identity_name"],+ result_key="EmailIdentities",+ page_size=100,+ detail_path="/v2/email/identities/{name}",+ item_name_key="IdentityName",+ name_column="identity_name",+ timestamp_columns=(+ "dkim_attributes_last_key_generation_timestamp",+ "verification_info_last_checked_timestamp",+ "verification_info_last_success_timestamp",+ ),+ raw_keys=frozenset({"Policies"}),+ ),+ "suppressed_destinations": AwsSesEndpointConfig(+ name="suppressed_destinations",+ path="/v2/email/suppression/addresses",+ primary_key=["email_address"],+ result_key="SuppressedDestinationSummaries",+ page_size=1000,+ supports_start_date=True,+ timestamp_columns=("last_update_time",),+ ),+}++ENDPOINTS = tuple(AWS_SES_ENDPOINTS.keys())++# Only the suppression list has a server-side time filter (`StartDate` on `LastUpdateTime`).+# The other endpoints have no filter at all, so they stay full refresh.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ "suppressed_destinations": [+ {+ "label": "last_update_time",+ "type": IncrementalFieldType.DateTime,+ "field": "last_update_time",+ "field_type": IncrementalFieldType.DateTime,+ }+ ],+}++ENDPOINT_DESCRIPTIONS: dict[str, str] = {+ "account": "Sending status, quota, and reputation enforcement for the connected AWS Region. One row per sync.",+ "configuration_sets": "Configuration sets with their tracking, delivery, reputation, sending, and suppression options.",+ "email_identities": "Verified email identities (domains and addresses) with DKIM, MAIL FROM, and verification details.",+ "suppressed_destinations": "Email addresses on the account-level suppression list, with the reason and time they were added.",+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/source.pyindex fed3e5e1c491..6d4f7fc7a01d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/source.py@@ -1,30 +1,186 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_ses.aws_ses import (+ AwsSesResumeConfig,+ aws_ses_source,+ probe_endpoint_permissions,+ validate_credentials as validate_aws_ses_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_ses.settings import (+ 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.awsses import AwsSesSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AwsSesSource(SimpleSource[AwsSesSourceConfig]):+class AwsSesSource(ResumableSource[AwsSesSourceConfig, AwsSesResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog, safe for public docs+ supported_versions = ("v2",)+ default_version = "v2"+ api_docs_url = "https://docs.aws.amazon.com/ses/latest/APIReference-V2/Welcome.html"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.AWSSES+ @property+ def connection_host_fields(self) -> list[str]:+ # The region picks the endpoint the signed request, and so the customer's key, is sent to.+ return ["aws_region"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "Amazon SES request failed: UnrecognizedClientException": "AWS rejected the access key. Please check the access key ID and secret access key, and that the key is still active.",+ "Amazon SES request failed: InvalidClientTokenId": "AWS rejected the access key. Please check the access key ID and secret access key, and that the key is still active.",+ "Amazon SES request failed: SignatureDoesNotMatch": "AWS rejected the request signature. Please re-enter the secret access key.",+ "Amazon SES request failed: InvalidSignatureException": "AWS rejected the request signature. If you are using temporary credentials, the session token has expired.",+ "Amazon SES request failed: ExpiredTokenException": "The AWS session token has expired. Please reconnect with fresh credentials.",+ "Amazon SES request failed: AccessDeniedException": "These AWS credentials are missing SES read permissions. Grant ses:GetAccount, ses:ListConfigurationSets, ses:GetConfigurationSet, ses:ListEmailIdentities, ses:GetEmailIdentity and ses:ListSuppressedDestinations to the IAM user or role.",+ "Invalid AWS region": "Enter a valid AWS region code like us-east-1.",+ "AWS access key ID and secret access key are required": "Enter both an AWS access key ID and a secret access key.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.aws_ses.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: AwsSesSourceConfig,+ 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: AwsSesSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_aws_ses_credentials(+ config.aws_access_key_id,+ config.aws_secret_access_key,+ config.aws_session_token,+ config.aws_region,+ schema_name=schema_name,+ )++ def get_endpoint_permissions(+ self, config: AwsSesSourceConfig, team_id: int, endpoints: list[str], api_version: str | None = None+ ) -> dict[str, str | None]:+ return probe_endpoint_permissions(+ config.aws_access_key_id,+ config.aws_secret_access_key,+ config.aws_session_token,+ config.aws_region,+ endpoints,+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AwsSesResumeConfig]:+ return ResumableSourceManager[AwsSesResumeConfig](inputs, AwsSesResumeConfig)++ def source_for_pipeline(+ self,+ config: AwsSesSourceConfig,+ resumable_source_manager: ResumableSourceManager[AwsSesResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return aws_ses_source(+ aws_access_key_id=config.aws_access_key_id,+ aws_secret_access_key=config.aws_secret_access_key,+ aws_session_token=config.aws_session_token,+ aws_region=config.aws_region,+ endpoint=inputs.schema_name,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ logger=inputs.logger,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.AWS_SES,category=DataWarehouseSourceCategory.MARKETING___EMAIL,- label="Amazon Web Services (Amazon SES)",+ label="Amazon SES",+ caption="""Sync your Amazon SES account data into the PostHog Data warehouse.++Create an IAM user or role with the `ses:GetAccount`, `ses:ListConfigurationSets`, `ses:GetConfigurationSet`, `ses:ListEmailIdentities`, `ses:GetEmailIdentity` and `ses:ListSuppressedDestinations` permissions, then paste its access key ID and secret access key. Add a session token too if you are using temporary credentials.++SES data is regional, so connect one source per AWS Region you send email from. This source syncs account-level data. Per-message send, bounce, and complaint events are only available through SES event destinations, not the SES API.""",iconPath="/static/services/aws_ses.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/aws-ses",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["aws", "ses", "simple email service", "email"],+ 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_region",+ label="AWS region",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="us-east-1",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="aws_session_token",+ label="AWS session token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="Only needed for temporary credentials",+ caption="Only for temporary credentials. Session tokens expire after a few hours, so scheduled syncs will fail once the token expires. Use a permanent access key (starts with AKIA) for recurring imports.",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses.pynew file mode 100644index 000000000000..7f0b2dda9eb2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses.py@@ -0,0 +1,512 @@+import json+import datetime as dt+from typing import Any, Optional++import pytest+from freezegun import freeze_time+from unittest import mock++import requests+import structlog++from products.warehouse_sources.backend.temporal.data_imports.sources.aws_ses import aws_ses+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_ses.aws_ses import (+ AwsSesError,+ AwsSesResumeConfig,+ Credentials,+ error_for_response,+ get_rows,+ normalize_row,+ probe_endpoint_permissions,+ resolve_start_date,+ send_request,+ validate_credentials,+ validate_region,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_ses.settings import AWS_SES_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++LOGGER = structlog.get_logger()++EMAIL_IDENTITIES = AWS_SES_ENDPOINTS["email_identities"]++JAN_2025 = 1735689600.0 # 2025-01-01T00:00:00Z+++class FakeResumeManager(ResumableSourceManager[AwsSesResumeConfig]):+ def __init__(self, state: Optional[AwsSesResumeConfig] = None) -> None:+ self.state = state+ self.saved: list[AwsSesResumeConfig] = []+ self.cleared = False++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> Optional[AwsSesResumeConfig]:+ return self.state++ def save_state(self, data: AwsSesResumeConfig) -> None:+ self.saved.append(data)++ def clear_state(self) -> None:+ self.cleared = True+++def make_response(+ status_code: int, payload: Optional[dict[str, Any]] = None, headers: Optional[dict[str, str]] = None+) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ response.headers.update(headers or {})+ response._content = json.dumps(payload if payload is not None else {}).encode()+ return response+++def suppression_page(emails: list[str], next_token: Optional[str] = None) -> dict[str, Any]:+ body: dict[str, Any] = {+ "SuppressedDestinationSummaries": [+ {"EmailAddress": email, "Reason": "BOUNCE", "LastUpdateTime": JAN_2025} for email in emails+ ]+ }+ if next_token is not None:+ body["NextToken"] = next_token+ return body+++class TestRegionValidation:+ @pytest.mark.parametrize("region", ["us-east-1", "eu-central-1", "ap-southeast-2", "us-gov-west-1"])+ def test_well_formed_regions_pass(self, region: str) -> None:+ assert validate_region(region) == region++ @pytest.mark.parametrize(+ "region",+ ["", "US-EAST-1", "us east 1", "email.evil.example/", "us-east-1/path", "us-east-1?x=1", "evil.example#"],+ )+ def test_anything_outside_the_region_alphabet_is_rejected_before_it_reaches_the_host(self, region: str) -> None:+ # The region is interpolated into the signed request's host.+ with pytest.raises(ValueError, match="Invalid AWS region"):+ validate_region(region)+++class TestNormalizeRow:+ def test_account_response_flattens_into_prefixed_snake_case_columns(self) -> None:+ row = normalize_row(+ AWS_SES_ENDPOINTS["account"],+ {+ "SendingEnabled": True,+ "EnforcementStatus": "HEALTHY",+ "ProductionAccessEnabled": True,+ "SendQuota": {"Max24HourSend": 50000.0, "MaxSendRate": 14.0, "SentLast24Hours": 12.5},+ "SuppressionAttributes": {"SuppressedReasons": ["BOUNCE", "COMPLAINT"]},+ },+ )++ assert row == {+ "sending_enabled": True,+ "enforcement_status": "HEALTHY",+ "production_access_enabled": True,+ "send_quota_max24_hour_send": 50000.0,+ "send_quota_max_send_rate": 14.0,+ "send_quota_sent_last24_hours": 12.5,+ "suppression_attributes_suppressed_reasons": ["BOUNCE", "COMPLAINT"],+ }++ def test_identity_detail_keeps_policy_maps_whole_and_parses_epoch_timestamps(self) -> None:+ row = normalize_row(+ EMAIL_IDENTITIES,+ {+ "IdentityType": "DOMAIN",+ "DkimAttributes": {+ "SigningEnabled": True,+ "Status": "SUCCESS",+ "Tokens": ["token-1", "token-2"],+ "LastKeyGenerationTimestamp": JAN_2025,+ },+ "MailFromAttributes": {"MailFromDomain": "mail.example.com"},+ "Policies": {"MyPolicy": '{"Version":"2012-10-17"}'},+ "Tags": [{"Key": "env", "Value": "prod"}],+ "VerificationInfo": {+ "LastCheckedTimestamp": JAN_2025,+ "SOARecord": {"PrimaryNameServer": "ns1.example.com", "SerialNumber": 7},+ },+ },+ )++ assert row["identity_type"] == "DOMAIN"+ assert row["dkim_attributes_signing_enabled"] is True+ assert row["dkim_attributes_status"] == "SUCCESS"+ assert row["dkim_attributes_tokens"] == ["token-1", "token-2"]+ assert row["dkim_attributes_last_key_generation_timestamp"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)+ assert row["mail_from_attributes_mail_from_domain"] == "mail.example.com"+ # A policy map has caller-defined keys; flattening it would mint one column per policy.+ assert row["policies"] == {"MyPolicy": '{"Version":"2012-10-17"}'}+ assert row["tags"] == [{"Key": "env", "Value": "prod"}]+ assert row["verification_info_last_checked_timestamp"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)+ assert row["verification_info_soa_record_primary_name_server"] == "ns1.example.com"+ assert row["verification_info_soa_record_serial_number"] == 7+++class TestSendRequest:+ def test_requests_are_sigv4_signed_with_the_regional_ses_scope(self) -> None:+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = make_response(200, {})+ credentials = Credentials("AKIAEXAMPLE", "secret")++ with freeze_time("2026-08-07T10:00:00Z"):+ send_request(session, credentials, "eu-west-1", "/v2/email/account")++ assert session.get.call_args[0][0] == "https://email.eu-west-1.amazonaws.com/v2/email/account"+ headers = session.get.call_args[1]["headers"]+ assert headers["X-Amz-Date"] == "20260807T100000Z"+ assert headers["Authorization"].startswith(+ "AWS4-HMAC-SHA256 Credential=AKIAEXAMPLE/20260807/eu-west-1/ses/aws4_request"+ )++ def test_query_params_are_sorted_and_rfc3986_encoded_to_match_the_signed_string(self) -> None:+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = make_response(200, {})++ send_request(+ session,+ Credentials("key", "secret"),+ "us-east-1",+ "/v2/email/suppression/addresses",+ {"StartDate": "2026-08-01T00:00:00Z", "PageSize": 1000},+ )++ assert session.get.call_args[0][0].endswith(+ "/v2/email/suppression/addresses?PageSize=1000&StartDate=2026-08-01T00%3A00%3A00Z"+ )++ def test_temporary_credentials_carry_the_session_token(self) -> None:+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = make_response(200, {})++ send_request(session, Credentials("key", "secret", "session-token"), "us-east-1", "/v2/email/account")++ assert session.get.call_args[1]["headers"]["X-Amz-Security-Token"] == "session-token"+++class TestErrorClassification:+ def test_the_error_type_header_wins_over_the_body(self) -> None:+ response = make_response(+ 400,+ {"message": "denied"},+ headers={"x-amzn-ErrorType": "AccessDeniedException:http://internal.amazon.example/coral/"},+ )++ assert str(error_for_response(response)) == "Amazon SES request failed: AccessDeniedException - denied"++ def test_the_namespaced_body_type_is_stripped_to_the_bare_code(self) -> None:+ response = make_response(400, {"__type": "com.amazonaws.ses#BadRequestException", "message": "bad"})++ assert str(error_for_response(response)) == "Amazon SES request failed: BadRequestException - bad"++ def test_a_non_json_error_body_still_produces_a_usable_message(self) -> None:+ response = requests.Response()+ response.status_code = 503+ response._content = b"<html>gateway</html>"++ assert "HTTP 503" in str(error_for_response(response))+++class TestResolveStartDate:+ WATERMARK = dt.datetime(2026, 8, 7, 12, 0, tzinfo=dt.UTC)++ @pytest.mark.parametrize(+ "watermark",+ ["2026-08-07T12:00:00Z", dt.datetime(2026, 8, 7, 12, 0, tzinfo=dt.UTC)],+ )+ def test_incremental_rewinds_a_day_behind_the_watermark(self, watermark: Any) -> None:+ assert resolve_start_date(True, watermark) == dt.datetime(2026, 8, 6, 12, 0, tzinfo=dt.UTC)++ @pytest.mark.parametrize(+ "should_use_incremental_field,watermark",+ [(False, dt.datetime(2026, 8, 7, tzinfo=dt.UTC)), (True, None), (True, "not-a-date")],+ )+ def test_no_usable_watermark_means_a_full_unbounded_walk(+ self, should_use_incremental_field: bool, watermark: Any+ ) -> None:+ assert resolve_start_date(should_use_incremental_field, watermark) is None+++class TestGetRows:+ def _run(+ self,+ responses: list[Any],+ manager: Optional[FakeResumeManager] = None,+ endpoint: str = "suppressed_destinations",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[list[dict[str, Any]]], mock.MagicMock, FakeResumeManager]:+ manager = manager if manager is not None else FakeResumeManager()+ with mock.patch.object(aws_ses, "send_request", side_effect=responses) as send:+ batches = list(+ get_rows(+ aws_access_key_id="key",+ aws_secret_access_key="secret",+ aws_session_token=None,+ aws_region="us-east-1",+ endpoint=endpoint,+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ logger=LOGGER,+ )+ )+ return batches, send, manager++ def test_the_account_endpoint_yields_its_single_snapshot_row(self) -> None:+ batches, send, _ = self._run([{"SendingEnabled": True, "EnforcementStatus": "HEALTHY"}], endpoint="account")++ assert batches == [[{"sending_enabled": True, "enforcement_status": "HEALTHY"}]]+ assert send.call_count == 1+ assert send.call_args[0][3] == "/v2/email/account"++ def test_pagination_follows_next_token_until_aws_stops_returning_one(self) -> None:+ batches, send, _ = self._run(+ [+ suppression_page(["[email protected]"], next_token="page-2"),+ suppression_page(["[email protected]"]),+ ]+ )++ assert [row["email_address"] for batch in batches for row in batch] == ["[email protected]", "[email protected]"]+ assert batches[0][0]["last_update_time"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)+ assert "NextToken" not in send.call_args_list[0][0][4]+ assert send.call_args_list[1][0][4]["NextToken"] == "page-2"++ def test_state_is_saved_after_each_page_and_cleared_once_the_walk_completes(self) -> None:+ _, _, manager = self._run(+ [+ suppression_page(["[email protected]"], next_token="page-2"),+ suppression_page(["[email protected]"]),+ ]+ )++ assert manager.saved == [AwsSesResumeConfig(next_token="page-2"), AwsSesResumeConfig(next_token=None)]+ assert manager.cleared is True++ def test_a_saved_token_resumes_the_walk_at_the_saved_page(self) -> None:+ _, send, _ = self._run(+ [suppression_page(["[email protected]"])],+ manager=FakeResumeManager(AwsSesResumeConfig(next_token="page-7")),+ )++ assert send.call_count == 1+ assert send.call_args[0][4]["NextToken"] == "page-7"++ def test_an_expired_saved_token_restarts_the_walk_instead_of_failing_the_job(self) -> None:+ batches, send, manager = self._run(+ [+ AwsSesError("Amazon SES request failed: InvalidNextTokenException - expired"),+ suppression_page(["[email protected]"]),+ ],+ manager=FakeResumeManager(AwsSesResumeConfig(next_token="stale")),+ )++ assert [row["email_address"] for batch in batches for row in batch] == ["[email protected]"]+ assert send.call_args_list[0][0][4].get("NextToken") == "stale"+ assert "NextToken" not in send.call_args_list[1][0][4]+ assert manager.cleared is True++ def test_an_invalid_token_from_aws_itself_is_not_swallowed(self) -> None:+ # Restarting is only safe for a token we saved; a fresh token AWS just returned failing+ # means something else is wrong.+ with pytest.raises(AwsSesError, match="InvalidNextTokenException"):+ self._run(+ [+ AwsSesError("Amazon SES request failed: InvalidNextTokenException - expired"),+ AwsSesError("Amazon SES request failed: InvalidNextTokenException - expired"),+ ],+ manager=FakeResumeManager(AwsSesResumeConfig(next_token="stale")),+ )++ def test_an_incremental_run_asks_aws_only_for_updates_since_the_watermark(self) -> None:+ _, send, _ = self._run(+ [suppression_page([])],+ should_use_incremental_field=True,+ db_incremental_field_last_value=dt.datetime(2026, 8, 7, 12, 0, tzinfo=dt.UTC),+ )++ assert send.call_args[0][4]["StartDate"] == "2026-08-06T12:00:00Z"++ def test_a_full_refresh_walks_the_list_unbounded(self) -> None:+ _, send, _ = self._run([suppression_page([])])++ assert "StartDate" not in send.call_args[0][4]++ def test_configuration_sets_fan_out_from_bare_names_to_full_rows(self) -> None:+ batches, send, _ = self._run(+ [+ {"ConfigurationSets": ["transactional"], "NextToken": "page-2"},+ {+ "ConfigurationSetName": "transactional",+ "SendingOptions": {"SendingEnabled": True},+ "ReputationOptions": {"LastFreshStart": JAN_2025},+ },+ {"ConfigurationSets": ["marketing"]},+ {"TrackingOptions": {"CustomRedirectDomain": "links.example.com"}},+ ],+ endpoint="configuration_sets",+ )++ assert send.call_args_list[1][0][3] == "/v2/email/configuration-sets/transactional"+ first, second = batches[0][0], batches[1][0]+ assert first["configuration_set_name"] == "transactional"+ assert first["sending_options_sending_enabled"] is True+ assert first["reputation_options_last_fresh_start"] == dt.datetime(2025, 1, 1, tzinfo=dt.UTC)+ assert second["configuration_set_name"] == "marketing"+ assert second["tracking_options_custom_redirect_domain"] == "links.example.com"++ def test_identity_rows_merge_the_list_summary_with_the_detail_and_keep_the_name(self) -> None:+ # GetEmailIdentity does not echo the identity name back, so the row must carry it from+ # the list response or the primary key column would be empty.+ batches, send, _ = self._run(+ [+ {+ "EmailIdentities": [+ {+ "IdentityName": "[email protected]",+ "IdentityType": "EMAIL_ADDRESS",+ "SendingEnabled": True,+ "VerificationStatus": "SUCCESS",+ }+ ]+ },+ {"IdentityType": "EMAIL_ADDRESS", "VerifiedForSendingStatus": True},+ ],+ endpoint="email_identities",+ )++ assert send.call_args_list[1][0][3] == "/v2/email/identities/user%40example.com"+ row = batches[0][0]+ assert row["identity_name"] == "[email protected]"+ assert row["sending_enabled"] is True+ assert row["verification_status"] == "SUCCESS"+ assert row["verified_for_sending_status"] is True++ def test_an_item_deleted_between_list_and_detail_is_skipped_not_fatal(self) -> None:+ batches, _, _ = self._run(+ [+ {"EmailIdentities": [{"IdentityName": "gone.example.com"}, {"IdentityName": "kept.example.com"}]},+ AwsSesError("Amazon SES request failed: NotFoundException - not found"),+ {"IdentityType": "DOMAIN"},+ ],+ endpoint="email_identities",+ )++ assert [row["identity_name"] for batch in batches for row in batch] == ["kept.example.com"]++ def test_an_empty_page_yields_no_batch_but_still_completes_the_walk(self) -> None:+ batches, _, manager = self._run([suppression_page([])])++ assert batches == []+ assert manager.cleared is True+++class TestValidateCredentials:+ def test_missing_credentials_short_circuit_without_a_request(self) -> None:+ with mock.patch.object(aws_ses, "send_request") as send:+ assert validate_credentials("", "secret", None, "us-east-1") == (+ False,+ "AWS access key ID and secret access key are required",+ )++ send.assert_not_called()++ def test_a_malformed_region_short_circuits_without_a_request(self) -> None:+ with mock.patch.object(aws_ses, "send_request") as send:+ assert validate_credentials("key", "secret", None, "not a region") == (+ False,+ "'not a region' isn't a valid AWS region. Use a region code like us-east-1.",+ )++ send.assert_not_called()++ def test_a_successful_account_probe_validates(self) -> None:+ with mock.patch.object(aws_ses, "send_request", return_value={"SendingEnabled": True}) as send:+ assert validate_credentials("key", "secret", None, "us-east-1") == (True, None)++ assert send.call_args[0][3] == "/v2/email/account"++ def test_a_genuine_key_missing_the_account_permission_still_validates_at_create(self) -> None:+ # Scope for each table is reported per endpoint in the schema picker instead.+ error = AwsSesError("Amazon SES request failed: AccessDeniedException - not authorized")++ with mock.patch.object(aws_ses, "send_request", side_effect=error):+ assert validate_credentials("key", "secret", None, "us-east-1") == (True, None)++ def test_a_rejected_key_is_surfaced_to_the_user(self) -> None:+ error = AwsSesError("Amazon SES request failed: UnrecognizedClientException - invalid token")++ with mock.patch.object(aws_ses, "send_request", side_effect=error):+ assert validate_credentials("key", "secret", None, "us-east-1") == (False, str(error))++ def test_a_transport_failure_does_not_leak_internals(self) -> None:+ with mock.patch.object(aws_ses, "send_request", side_effect=requests.ConnectionError("boom")):+ assert validate_credentials("key", "secret", None, "us-east-1") == (+ False,+ "Could not reach the Amazon SES API. Check the AWS region and try again.",+ )++ def test_validating_a_schema_probes_that_endpoint_and_names_the_missing_permission(self) -> None:+ error = AwsSesError(+ "Amazon SES request failed: AccessDeniedException - User: arn:aws:iam::123456789012:user/etl "+ "is not authorized to perform: ses:ListSuppressedDestinations on resource: arn:aws:ses:us-east-1:123456789012:suppression-list"+ )++ with mock.patch.object(aws_ses, "send_request", side_effect=error):+ assert validate_credentials("key", "secret", None, "us-east-1", schema_name="suppressed_destinations") == (+ False,+ "Missing IAM permission ses:ListSuppressedDestinations",+ )++ def test_validating_a_schema_passes_when_the_endpoint_is_reachable(self) -> None:+ with mock.patch.object(aws_ses, "send_request", return_value=suppression_page([])):+ assert validate_credentials("key", "secret", None, "us-east-1", schema_name="suppressed_destinations") == (+ True,+ None,+ )+++class TestEndpointPermissions:+ def test_only_the_denied_endpoint_is_reported_unreachable(self) -> None:+ def respond(session: Any, credentials: Any, region: str, path: str, params: Any = None) -> dict[str, Any]:+ if path == "/v2/email/account":+ raise AwsSesError(+ "Amazon SES request failed: AccessDeniedException - not authorized to perform: ses:GetAccount"+ )+ return {}++ with mock.patch.object(aws_ses, "send_request", side_effect=respond):+ reasons = probe_endpoint_permissions(+ "key", "secret", None, "us-east-1", ["account", "suppressed_destinations"]+ )++ assert reasons == {+ "account": "Missing IAM permission ses:GetAccount",+ "suppressed_destinations": None,+ }++ def test_a_denied_detail_call_marks_the_fan_out_endpoint_unreachable(self) -> None:+ # Probing only the list would hide a missing Get* permission until the sync fails.+ responses = [+ {"EmailIdentities": [{"IdentityName": "example.com"}]},+ AwsSesError(+ "Amazon SES request failed: AccessDeniedException - not authorized to perform: ses:GetEmailIdentity"+ ),+ ]++ with mock.patch.object(aws_ses, "send_request", side_effect=responses):+ reasons = probe_endpoint_permissions("key", "secret", None, "us-east-1", ["email_identities"])++ assert reasons == {"email_identities": "Missing IAM permission ses:GetEmailIdentity"}++ def test_transient_failures_do_not_hide_tables_from_the_schema_picker(self) -> None:+ with mock.patch.object(+ aws_ses, "send_request", side_effect=AwsSesError("Amazon SES request failed: HTTP 503 - gateway")+ ):+ reasons = probe_endpoint_permissions("key", "secret", None, "us-east-1", ["suppressed_destinations"])++ assert reasons == {"suppressed_destinations": None}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses_source.pynew file mode 100644index 000000000000..5ce17f53641f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_ses/tests/test_aws_ses_source.py@@ -0,0 +1,231 @@+import datetime as dt+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest import mock++import structlog++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.aws_ses import (+ aws_ses as transport_module,+ source as source_module,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_ses.aws_ses import AwsSesResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_ses.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_ses.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.aws_ses.source import AwsSesSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.awsses import AwsSesSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def make_inputs(+ schema_name: str,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=1,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ db_incremental_field_earliest_value=None,+ incremental_field="last_update_time",+ incremental_field_type=None,+ job_id="job-id",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+++class TestAwsSesSource:+ def setup_method(self) -> None:+ self.source = AwsSesSource()+ self.config = AwsSesSourceConfig(+ aws_access_key_id="AKIAEXAMPLE",+ aws_secret_access_key="secret",+ aws_region="us-east-1",+ aws_session_token=None,+ )++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.AWSSES++ def test_source_is_released_and_labelled_alpha(self) -> None:+ config = self.source.get_source_config++ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.category == DataWarehouseSourceCategory.MARKETING___EMAIL+ assert config.label == "Amazon SES"+ assert config.iconPath == "/static/services/aws_ses.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/aws-ses"++ def test_source_config_fields(self) -> None:+ fields = self.source.get_source_config.fields++ assert [field.name for field in fields] == [+ "aws_access_key_id",+ "aws_secret_access_key",+ "aws_region",+ "aws_session_token",+ ]++ @pytest.mark.parametrize(+ "field_name,required,secret",+ [+ ("aws_access_key_id", True, False),+ ("aws_secret_access_key", True, True),+ ("aws_region", True, False),+ ("aws_session_token", False, True),+ ],+ )+ def test_credential_fields_are_marked_secret_so_they_are_not_echoed_back(+ self, field_name: str, required: bool, secret: bool+ ) -> None:+ field = next(+ f+ for f in self.source.get_source_config.fields+ if isinstance(f, SourceFieldInputConfig) and f.name == field_name+ )++ assert field.required is required+ assert field.secret is secret+ assert (field.type == SourceFieldInputConfigType.PASSWORD) is secret++ def test_changing_the_region_requires_reentering_the_secrets(self) -> None:+ # The region picks the host the signed request is sent to, so retargeting it must not+ # reuse a preserved secret.+ assert self.source.connection_host_fields == ["aws_region"]++ def test_get_schemas_marks_only_the_suppression_list_incremental(self) -> None:+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, team_id=1)}++ assert list(schemas) == list(ENDPOINTS)+ for schema in schemas.values():+ assert schema.description+ suppressed = schemas["suppressed_destinations"]+ assert suppressed.supports_incremental is True+ assert [field["field"] for field in suppressed.incremental_fields] == ["last_update_time"]+ for name in ("account", "configuration_sets", "email_identities"):+ assert schemas[name].supports_incremental is False+ assert schemas[name].supports_append is False++ def test_get_schemas_honors_the_schema_picker_filter(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=["email_identities"])++ assert [schema.name for schema in schemas] == ["email_identities"]++ def test_table_catalog_is_listable_without_credentials_for_public_docs(self) -> None:+ assert self.source.lists_tables_without_credentials is True+ assert self.source.get_schemas(+ AwsSesSourceConfig(aws_access_key_id="", aws_secret_access_key="", aws_region=""), 1+ )++ def test_canonical_descriptions_are_keyed_by_the_schema_names(self) -> None:+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)+ assert set(self.source.get_canonical_descriptions()) == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "observed_error",+ [+ "Amazon SES request failed: UnrecognizedClientException - The security token included in the request is invalid",+ "Amazon SES request failed: SignatureDoesNotMatch - Signature expired",+ "Amazon SES request failed: ExpiredTokenException - The security token included in the request is expired",+ "Amazon SES request failed: AccessDeniedException - not authorized to perform: ses:GetAccount",+ "Invalid AWS region: 'email.evil.example/'",+ ],+ )+ def test_permanent_aws_failures_stop_the_sync_instead_of_retrying(self, observed_error: str) -> None:+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "observed_error",+ [+ "Amazon SES request failed: TooManyRequestsException - Rate exceeded",+ "Amazon SES request failed: HTTP 503 - ",+ ],+ )+ def test_transient_aws_failures_keep_retrying(self, observed_error: str) -> None:+ assert not any(key in observed_error for key in self.source.get_non_retryable_errors())++ def test_validate_credentials_passes_the_configured_credentials_through(self) -> None:+ with mock.patch.object(source_module, "validate_aws_ses_credentials", return_value=(True, None)) as validate:+ assert self.source.validate_credentials(self.config, team_id=1) == (True, None)+ assert self.source.validate_credentials(self.config, team_id=1, schema_name="account") == (True, None)++ assert validate.call_args_list[0] == mock.call("AKIAEXAMPLE", "secret", None, "us-east-1", schema_name=None)+ assert validate.call_args_list[1] == mock.call(+ "AKIAEXAMPLE", "secret", None, "us-east-1", schema_name="account"+ )++ def test_endpoint_permissions_pass_the_configured_credentials_through(self) -> None:+ with mock.patch.object(source_module, "probe_endpoint_permissions", return_value={"account": None}) as probe:+ assert self.source.get_endpoint_permissions(self.config, team_id=1, endpoints=["account"]) == {+ "account": None+ }++ assert probe.call_args[0] == ("AKIAEXAMPLE", "secret", None, "us-east-1", ["account"])++ def test_resumable_manager_is_bound_to_the_sources_resume_dataclass(self) -> None:+ manager = self.source.get_resumable_source_manager(make_inputs("suppressed_destinations"))++ assert manager._data_class is AwsSesResumeConfig++ @pytest.mark.parametrize(+ "endpoint,primary_keys",+ [+ ("account", None),+ ("configuration_sets", ["configuration_set_name"]),+ ("email_identities", ["identity_name"]),+ ("suppressed_destinations", ["email_address"]),+ ],+ )+ def test_source_for_pipeline_declares_the_endpoints_primary_key_and_a_final_commit_watermark(+ self, endpoint: str, primary_keys: list[str] | None+ ) -> None:+ inputs = make_inputs(endpoint)+ manager = self.source.get_resumable_source_manager(inputs)++ response = self.source.source_for_pipeline(self.config, manager, inputs)++ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ # SES documents no response ordering, so the watermark must only commit when a walk+ # completes; "asc" would checkpoint it after every batch.+ assert response.sort_mode == "desc"++ def test_source_for_pipeline_forwards_the_watermark_only_on_an_incremental_run(self) -> None:+ watermark = dt.datetime(2026, 8, 1, tzinfo=dt.UTC)++ with mock.patch.object(source_module, "aws_ses_source") as build:+ inputs = make_inputs("suppressed_destinations", True, watermark)+ self.source.source_for_pipeline(self.config, self.source.get_resumable_source_manager(inputs), inputs)+ assert build.call_args[1]["db_incremental_field_last_value"] == watermark++ inputs = make_inputs("suppressed_destinations", False, watermark)+ self.source.source_for_pipeline(self.config, self.source.get_resumable_source_manager(inputs), inputs)+ assert build.call_args[1]["db_incremental_field_last_value"] is None++ def test_items_are_lazy_so_building_the_response_sends_no_request(self) -> None:+ inputs = make_inputs("suppressed_destinations")+ manager = self.source.get_resumable_source_manager(inputs)++ with mock.patch.object(transport_module, "send_request") as send:+ response = self.source.source_for_pipeline(self.config, manager, inputs)+ items = cast("Iterable[Any]", response.items())++ assert iter(items) is not None+ send.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsses.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsses.pyindex 58cdee913087..22536c465c75 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsses.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/awsses.py@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass AwsSesSourceConfig(config.Config):- pass+ aws_access_key_id: str+ aws_secret_access_key: str+ aws_region: str+ aws_session_token: str | None = None