: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): add Mailgun webhook ingestion (#77489)
Tom Owersdc9bd609b091
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 3e2748c5b963..a3b6ca48c23d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -399,7 +399,7 @@ the row lists both.| mem0 | HTTP | requests | ✅ || mailerlite | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || mailersend | HTTP | requests | ✅ |-| mailgun | HTTP | requests | ✅ |+| mailgun | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (API) / ➖ (webhook) || mailjet | HTTP + Webhook | `rest_source.RESTClient` + requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || mailosaur | HTTP | requests | ✅ || mailtrap | HTTP | requests | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/canonical_descriptions.pyindex d5bbdbd7704d..51e39755105f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/canonical_descriptions.py@@ -28,6 +28,33 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"skip_verification": "Whether the TLS certificate and hostname are not verified when delivering mail for the domain.",},},+ "webhook_events": {+ "description": (+ "An event pushed by a Mailgun webhook (accepted, delivered, opened, clicked, failed, "+ "complained, unsubscribed). Same shape as an events row, but kept past Mailgun's "+ "retention window and without a sending domain, which webhook payloads don't carry."+ ),+ "docs_url": "https://documentation.mailgun.com/docs/mailgun/user-manual/events/",+ "columns": {+ "id": "Unique identifier for the event.",+ "event": "The event type (accepted, delivered, opened, clicked, failed, complained, unsubscribed).",+ "timestamp": "Time the event occurred.",+ "recipient": "The recipient email address the event relates to.",+ "recipient-domain": "The domain of the recipient email address.",+ "message": "Details about the message that generated the event.",+ "envelope": "The SMTP envelope the message was sent with.",+ "tags": "The tags associated with the message.",+ "campaigns": "The campaigns associated with the message.",+ "delivery-status": "Delivery status details, including SMTP response codes.",+ "severity": "Severity of a failure event (temporary or permanent).",+ "reason": "The reason a delivery failed, if applicable.",+ "client-info": "The client that generated an open or click (browser, OS, device type).",+ "geolocation": "The approximate location an open or click came from.",+ "url": "The link that was clicked, for click events.",+ "log-level": "Mailgun's log level for the event (info, warn, error).",+ "user-variables": "Custom variables attached to the message when it was sent.",+ },+ },"events": {"description": "An event in the Mailgun event log (delivered, opened, clicked, bounced, etc.) for a domain.","docs_url": "https://documentation.mailgun.com/docs/mailgun/api-reference/openapi-final/tag/Events/",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/mailgun.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/mailgun.pyindex 1aaf35ab788f..93834e21d18f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/mailgun.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/mailgun.py@@ -1,20 +1,34 @@import timeimport dataclasses-from collections.abc import Iterator+from collections.abc import AsyncIterable, Iterable, Iteratorfrom datetime import UTC, date, datetimefrom email.utils import parsedate_to_datetimefrom typing import Any, Optionalfrom urllib.parse import parse_qs, quote, urlencode, urlsplit, urlunsplit+import orjson+import pyarrow as paimport requests+import structlog+from asgiref.sync import async_to_syncfrom structlog.types import FilteringBoundLoggerfrom tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ WebhookCreationResult,+ WebhookDeletionResult,+ WebhookSyncResult,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.settings import (MAILGUN_ENDPOINTS,+ WEBHOOK_EVENTS_ENDPOINT,+ WEBHOOK_TYPES,MailgunEndpointConfig,)@@ -23,6 +37,15 @@ REGION_BASE_URLS = {"eu": "https://api.eu.mailgun.net",}REQUEST_TIMEOUT_SECONDS = 60+WEBHOOK_REQUEST_TIMEOUT_SECONDS = 30+# Mailgun rejects a fourth URL on a webhook type, so a domain already fanned out to three+# other consumers has to have one removed by hand before PostHog can be added.+MAX_WEBHOOK_URLS_PER_TYPE = 3+# Registration is one listing plus up to len(WEBHOOK_TYPES) writes per domain, so a very large+# account is bounded rather than left to issue thousands of calls inside one request.+MAX_WEBHOOK_DOMAINS = 100+# Webhook management runs outside a sync, so there is no per-job logger to thread through.+_WEBHOOK_LOGGER: FilteringBoundLogger = structlog.get_logger(__name__)MAX_RETRIES = 5MAX_RETRY_AFTER_SECONDS = 120# Mailgun events are eventually consistent — the docs recommend treating the trailing@@ -344,16 +367,295 @@ def get_rows()+# Mailgun posts `{"signature": {...}, "event-data": {...}}`; `event-data` is the same event+# object the Events API returns in its `items` array.+WEBHOOK_PAYLOAD_EVENT_KEY = "event-data"+++def _webhook_table_transformer(table: pa.Table) -> pa.Table:+ """Unwrap Mailgun's delivery envelope and keep one row per event id.++ Delta merge only dedupes across syncs, so a batch carrying Mailgun's retry of a delivery it+ already made would otherwise land the same event twice. The signature block is dropped: its+ timestamp and token are per-delivery values with no meaning on the stored event."""+ if WEBHOOK_PAYLOAD_EVENT_KEY not in table.column_names:+ return table_from_py_list([])++ best_by_id: dict[str, tuple[float, dict[str, Any]]] = {}+ for event_data in table.column(WEBHOOK_PAYLOAD_EVENT_KEY).to_pylist():+ if event_data is None:+ continue+ # Normally a pyarrow struct, but tolerate a JSON string if one is ever produced upstream.+ row = orjson.loads(event_data) if isinstance(event_data, str | bytes) else dict(event_data)+ event_id = row.get("id")+ if not event_id:+ continue++ raw_timestamp = row.get("timestamp")+ ordering = (+ float(raw_timestamp)+ if isinstance(raw_timestamp, int | float) and not isinstance(raw_timestamp, bool)+ else 0.0+ )+ row["timestamp"] = _epoch_to_datetime(raw_timestamp)++ existing = best_by_id.get(event_id)+ if existing is None or ordering >= existing[0]:+ best_by_id[event_id] = (ordering, row)++ return table_from_py_list([row for _, row in best_by_id.values()])+++def _webhook_collection_url(base_url: str, domain: str) -> str:+ return f"{base_url}/v3/domains/{quote(domain, safe='')}/webhooks"+++def _webhook_urls(entry: Any) -> list[str]:+ """Read the URLs off one webhook entry. Mailgun returns `urls` today and `url` on older+ single-URL webhooks, and can return both."""+ if not isinstance(entry, dict):+ return []+ urls = [url for url in (entry.get("urls") or []) if url]+ single = entry.get("url")+ if single and single not in urls:+ urls.append(single)+ return urls+++def _list_domain_webhooks(session: requests.Session, base_url: str, api_key: str, domain: str) -> dict[str, list[str]]:+ response = session.get(+ _webhook_collection_url(base_url, domain),+ auth=("api", api_key),+ headers={"Accept": "application/json"},+ timeout=WEBHOOK_REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ webhooks = (response.json() or {}).get("webhooks") or {}+ return {name: _webhook_urls(entry) for name, entry in webhooks.items()}+++def _put_webhook_urls(+ session: requests.Session, base_url: str, api_key: str, domain: str, webhook_type: str, urls: list[str]+) -> None:+ response = session.put(+ f"{_webhook_collection_url(base_url, domain)}/{webhook_type}",+ auth=("api", api_key),+ data=[("url", url) for url in urls],+ timeout=WEBHOOK_REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+++def _register_webhook(+ session: requests.Session,+ base_url: str,+ api_key: str,+ domain: str,+ webhook_type: str,+ webhook_url: str,+ existing_urls: list[str],+) -> None:+ """Add `webhook_url` to one webhook type on one domain, preserving any URLs already there."""+ if not existing_urls:+ response = session.post(+ _webhook_collection_url(base_url, domain),+ auth=("api", api_key),+ data={"id": webhook_type, "url": webhook_url},+ timeout=WEBHOOK_REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ return++ if len(existing_urls) >= MAX_WEBHOOK_URLS_PER_TYPE:+ raise ValueError(f"already has {MAX_WEBHOOK_URLS_PER_TYPE} URLs, remove one in Mailgun before adding PostHog")++ _put_webhook_urls(session, base_url, api_key, domain, webhook_type, [*existing_urls, webhook_url])+++def _webhook_domains(api_key: str, base_url: str) -> list[str]:+ return get_domain_names(api_key, base_url, _WEBHOOK_LOGGER)[:MAX_WEBHOOK_DOMAINS]+++def create_webhook(api_key: str, region: str, webhook_url: str) -> WebhookCreationResult:+ """Register PostHog on every Mailgun webhook type, on every sending domain of the account.++ Mailgun scopes webhooks per domain, so a source that syncs a whole account has to fan the+ registration out. Re-running is safe: a type already pointing at `webhook_url` is left alone."""+ base_url = base_url_for_region(region)+ session = make_tracked_session(redact_values=(api_key,))++ try:+ domains = _webhook_domains(api_key, base_url)+ except Exception as e:+ return WebhookCreationResult(+ success=False,+ error=f"Could not list your Mailgun sending domains: {e}. Please set the webhook up manually.",+ )++ if not domains:+ return WebhookCreationResult(+ success=False,+ error="This Mailgun account has no sending domains, so there is nothing to register a webhook on.",+ )++ registered = 0+ errors: list[str] = []++ for domain in domains:+ try:+ existing = _list_domain_webhooks(session, base_url, api_key, domain)+ except Exception as e:+ errors.append(f"{domain}: {e}")+ continue++ for webhook_type in WEBHOOK_TYPES:+ urls = existing.get(webhook_type, [])+ if webhook_url in urls:+ registered += 1+ continue+ try:+ _register_webhook(session, base_url, api_key, domain, webhook_type, webhook_url, urls)+ registered += 1+ except Exception as e:+ errors.append(f"{domain} / {webhook_type}: {e}")++ if registered == 0:+ return WebhookCreationResult(+ success=False,+ error=f"Mailgun refused every webhook registration: {'; '.join(errors[:5])}. "+ "Please set the webhook up manually.",+ )++ if errors:+ _WEBHOOK_LOGGER.warning(f"Mailgun: some webhook registrations failed: {'; '.join(errors[:10])}")++ # Mailgun never returns the account's HTTP webhook signing key over the API, so deliveries+ # can't be verified until the user pastes it in.+ return WebhookCreationResult(success=True, pending_inputs=["signing_secret"])+++def sync_webhook_events(api_key: str, region: str, webhook_url: str) -> WebhookSyncResult:+ """Re-run registration so domains added since setup, and any type that failed first time+ round, get picked up. Registration is idempotent."""+ result = create_webhook(api_key, region, webhook_url)+ return WebhookSyncResult(success=result.success, error=result.error)+++def get_external_webhook_info(api_key: str, region: str, webhook_url: str) -> ExternalWebhookInfo:+ base_url = base_url_for_region(region)+ session = make_tracked_session(redact_values=(api_key,))++ try:+ domains = _webhook_domains(api_key, base_url)+ enabled_types: set[str] = set()+ registered_domains = 0++ for domain in domains:+ types = [+ webhook_type+ for webhook_type, urls in _list_domain_webhooks(session, base_url, api_key, domain).items()+ if webhook_url in urls+ ]+ if types:+ registered_domains += 1+ enabled_types.update(types)++ if not enabled_types:+ return ExternalWebhookInfo(exists=False)++ return ExternalWebhookInfo(+ exists=True,+ url=webhook_url,+ enabled_events=sorted(enabled_types),+ status="enabled",+ description=f"Registered on {registered_domains} of {len(domains)} sending domains",+ )+ except Exception as e:+ return ExternalWebhookInfo(exists=False, error=str(e))+++def delete_webhook(api_key: str, region: str, webhook_url: str) -> WebhookDeletionResult:+ """Remove PostHog from every webhook type it was registered on, leaving other consumers'+ URLs in place."""+ base_url = base_url_for_region(region)+ session = make_tracked_session(redact_values=(api_key,))++ try:+ domains = _webhook_domains(api_key, base_url)+ except Exception as e:+ return WebhookDeletionResult(success=False, error=f"Could not list your Mailgun sending domains: {e}")++ errors: list[str] = []++ for domain in domains:+ try:+ existing = _list_domain_webhooks(session, base_url, api_key, domain)+ except Exception as e:+ errors.append(f"{domain}: {e}")+ continue++ for webhook_type, urls in existing.items():+ if webhook_url not in urls:+ continue+ remaining = [url for url in urls if url != webhook_url]+ try:+ if remaining:+ _put_webhook_urls(session, base_url, api_key, domain, webhook_type, remaining)+ else:+ response = session.delete(+ f"{_webhook_collection_url(base_url, domain)}/{webhook_type}",+ auth=("api", api_key),+ timeout=WEBHOOK_REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ except Exception as e:+ errors.append(f"{domain} / {webhook_type}: {e}")++ if errors:+ return WebhookDeletionResult(success=False, error="; ".join(errors[:5]))+ return WebhookDeletionResult(success=True)+++def mailgun_webhook_source(webhook_source_manager: WebhookSourceManager, endpoint: str) -> SourceResponse:+ """Webhook-only table: the poll has nothing to fetch, so it yields nothing and lets the+ webhook manager take over once the schema's first (empty) sync completes."""+ webhook_enabled = async_to_sync(webhook_source_manager.webhook_enabled)(webhook_only=True)++ def items() -> Iterable[Any] | AsyncIterable[Any]:+ if webhook_enabled:+ return webhook_source_manager.get_items(table_transformer=_webhook_table_transformer)+ return iter([])++ return SourceResponse(+ name=endpoint,+ items=items,+ # Mailgun event ids come from a single account-wide event store, so they are unique+ # without the sending-domain qualifier the polled `events` table needs.+ primary_keys=["id"],+ sort_mode="asc",+ webhook_only=True,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="day",+ partition_keys=["timestamp"],+ )++def mailgun_source(api_key: str,region: str,endpoint: str,logger: FilteringBoundLogger,resumable_source_manager: ResumableSourceManager[MailgunResumeConfig],+ webhook_source_manager: WebhookSourceManager,should_use_incremental_field: bool = False,db_incremental_field_last_value: Optional[Any] = None,incremental_field: str | None = None,) -> SourceResponse:+ if endpoint == WEBHOOK_EVENTS_ENDPOINT:+ return mailgun_webhook_source(webhook_source_manager, endpoint)+config = MAILGUN_ENDPOINTS[endpoint]return SourceResponse(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/settings.pyindex 8342240ad7e8..f59f85de6ce2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/settings.py@@ -112,3 +112,42 @@ ENDPOINTS = tuple(MAILGUN_ENDPOINTS.keys())INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: config.incremental_fields for name, config in MAILGUN_ENDPOINTS.items() if config.incremental_fields}++# Webhook-only table fed by Mailgun's pushed event stream. It deliberately does not feed the+# polled `events` table: that table's primary key is ["domain", "id"] and the sending domain is+# injected by our per-domain fan-out, not returned by Mailgun, so webhook rows could never merge+# against polled rows. The polled table also carries `rejected`, `stored` and list-upload events+# that Mailgun offers no webhook for, and a schema in webhook mode skips its poll entirely.+WEBHOOK_EVENTS_ENDPOINT = "webhook_events"++# Webhook type ids accepted by POST /v3/domains/{domain}/webhooks. Registered on every sending+# domain so the pushed stream covers the whole account. Note `unsubscribe` — the webhook id and+# the `event` value in its payload (`unsubscribed`) differ.+WEBHOOK_TYPES: tuple[str, ...] = (+ "accepted",+ "clicked",+ "complained",+ "delivered",+ "opened",+ "permanent_fail",+ "temporary_fail",+ "unsubscribe",+)++# Every webhook type lands in the one webhook-only table, so the hog template collapses the+# payload's `event` value to this resource key before looking up the schema id.+WEBHOOK_RESOURCE_KEY = "email_event"++SCHEMA_TO_WEBHOOK_RESOURCE: dict[str, str] = {WEBHOOK_EVENTS_ENDPOINT: WEBHOOK_RESOURCE_KEY}++# `event-data.event` values the webhook types above deliver. `permanent_fail` and+# `temporary_fail` both arrive as `failed`, told apart by the payload's `severity`.+WEBHOOK_EVENT_NAMES: tuple[str, ...] = (+ "accepted",+ "clicked",+ "complained",+ "delivered",+ "failed",+ "opened",+ "unsubscribed",+)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/source.pyindex 09db51041b5a..043aa5e092c8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/source.py@@ -1,4 +1,4 @@-from typing import Optional, cast+from typing import TYPE_CHECKING, Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,@@ -11,7 +11,15 @@ from posthog.schema import (SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ FieldType,+ ResumableSource,+ WebhookCreationResult,+ WebhookDeletionResult,+ WebhookSource,+ WebhookSyncResult,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)@@ -19,23 +27,39 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.regfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mailgun import (MailgunSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun import (MailgunResumeConfig,+ create_webhook as create_mailgun_webhook,+ delete_webhook as delete_mailgun_webhook,+ get_external_webhook_info as get_mailgun_webhook_info,mailgun_source,+ sync_webhook_events as sync_mailgun_webhook_events,validate_credentials as validate_mailgun_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.settings import (ENDPOINTS,INCREMENTAL_FIELDS,+ SCHEMA_TO_WEBHOOK_RESOURCE,+ WEBHOOK_EVENTS_ENDPOINT,+ WEBHOOK_TYPES,)from products.warehouse_sources.backend.types import ExternalDataSourceType+if TYPE_CHECKING:+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC++API_SECURITY_URL = "https://app.mailgun.com/settings/api_security"+@SourceRegistry.register-class MailgunSource(ResumableSource[MailgunSourceConfig, MailgunResumeConfig]):+class MailgunSource(+ ResumableSource[MailgunSourceConfig, MailgunResumeConfig],+ WebhookSource[MailgunSourceConfig],+):lists_tables_without_credentials = True # static endpoint catalog — safe for public docssupported_versions = ("v3",)@@ -46,6 +70,18 @@ class MailgunSource(ResumableSource[MailgunSourceConfig, MailgunResumeConfig]):def source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.MAILGUN+ @property+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:+ from products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.webhook_template import ( # noqa: PLC0415+ template,+ )++ return template++ @property+ def webhook_resource_map(self) -> dict[str, str]:+ return SCHEMA_TO_WEBHOOK_RESOURCE+def get_non_retryable_errors(self) -> dict[str, str | None]:return {"401 Client Error: Unauthorized for url: https://api.mailgun.net": "Mailgun authentication failed. Please check your private API key.",@@ -60,9 +96,9 @@ class MailgunSource(ResumableSource[MailgunSourceConfig, MailgunResumeConfig]):name=SchemaExternalDataSourceType.MAILGUN,category=DataWarehouseSourceCategory.MARKETING___EMAIL,label="Mailgun",- caption="""Enter your Mailgun private API key to pull your Mailgun data into the PostHog Data warehouse.+ caption=f"""Enter your Mailgun private API key to pull your Mailgun data into the PostHog Data warehouse.-You can find your private API key in the [Mailgun dashboard](https://app.mailgun.com/settings/api_security) under **Settings → API security**. Pick the region that matches where your Mailgun account is hosted.+You can find your private API key in the [Mailgun dashboard]({API_SECURITY_URL}) under **Settings → API security**. Pick the region that matches where your Mailgun account is hosted.Note: Mailgun only retains events for a limited period (1 day on free plans, up to 30 days on paid plans), so the initial events sync is bounded by your plan's retention.""",iconPath="/static/services/mailgun.png",@@ -91,6 +127,36 @@ Note: Mailgun only retains events for a limited period (1 day on free plans, up),],),+ webhookSetupCaption=(+ "PostHog registers a webhook on every sending domain of your account, for every "+ "Mailgun event type, using the API key above. Webhook events land in the "+ f"`{WEBHOOK_EVENTS_ENDPOINT}` table, which keeps history past the 1 to 30 days "+ "Mailgun retains events for.\n\n"+ "Mailgun doesn't return the signing key over the API, so copy it from "+ f"[Settings > API security]({API_SECURITY_URL}) (**HTTP webhook signing key**) into the "+ "field below. Deliveries are rejected until it's set.\n\n"+ "**Manual setup** (only needed if automatic registration failed):\n\n"+ "1. Go to **Send > Sending > Webhooks** in your Mailgun dashboard and pick a domain\n"+ "2. Add the URL shown below for each event type you want to sync\n"+ "3. Repeat for every sending domain you want covered"+ ),+ webhookFields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="signing_secret",+ label="HTTP webhook signing key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ caption=(+ f"From [Settings > API security]({API_SECURITY_URL}). PostHog uses it to verify "+ "the HMAC-SHA256 signature on every delivery."+ ),+ secret=True,+ ),+ ],+ ),)def get_canonical_descriptions(self) -> CanonicalDescriptions:@@ -118,6 +184,18 @@ Note: Mailgun only retains events for a limited period (1 day on free plans, up)for endpoint in ENDPOINTS]+ # The pushed event stream has no list endpoint of its own to poll, so append and+ # full-refresh don't apply to it.+ schemas.append(+ SourceSchema(+ name=WEBHOOK_EVENTS_ENDPOINT,+ supports_incremental=False,+ supports_append=False,+ supports_webhooks=True,+ webhook_only=True,+ incremental_fields=[],+ )+ )if names is not None:names_set = set(names)@@ -140,6 +218,43 @@ Note: Mailgun only retains events for a limited period (1 day on free plans, updef get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MailgunResumeConfig]:return ResumableSourceManager[MailgunResumeConfig](inputs, MailgunResumeConfig)+ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:+ return WebhookSourceManager(inputs, inputs.logger)++ def create_webhook(+ self, config: MailgunSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> WebhookCreationResult:+ return create_mailgun_webhook(config.api_key, config.region, webhook_url)++ def get_desired_webhook_events(+ self, config: MailgunSourceConfig, eligible_schema_names: list[str]+ ) -> list[str] | None:+ if WEBHOOK_EVENTS_ENDPOINT not in eligible_schema_names:+ return None+ return sorted(WEBHOOK_TYPES)++ def sync_webhook_events(+ self,+ config: MailgunSourceConfig,+ webhook_url: str,+ team_id: int,+ eligible_schema_names: list[str],+ api_version: str | None = None,+ ) -> WebhookSyncResult:+ if WEBHOOK_EVENTS_ENDPOINT not in eligible_schema_names:+ return WebhookSyncResult(success=True)+ return sync_mailgun_webhook_events(config.api_key, config.region, webhook_url)++ def get_external_webhook_info(+ self, config: MailgunSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> ExternalWebhookInfo | None:+ return get_mailgun_webhook_info(config.api_key, config.region, webhook_url)++ def delete_webhook(+ self, config: MailgunSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> WebhookDeletionResult:+ return delete_mailgun_webhook(config.api_key, config.region, webhook_url)+def source_for_pipeline(self,config: MailgunSourceConfig,@@ -152,6 +267,7 @@ Note: Mailgun only retains events for a limited period (1 day on free plans, upendpoint=inputs.schema_name,logger=inputs.logger,resumable_source_manager=resumable_source_manager,+ webhook_source_manager=self.get_webhook_source_manager(inputs),should_use_incremental_field=inputs.should_use_incremental_field,db_incremental_field_last_value=inputs.db_incremental_field_last_valueif inputs.should_use_incremental_fielddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun.pyindex c61490e4d4b2..e31f4e1b5f31 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun.py@@ -1,6 +1,7 @@import time+from collections.abc import Iterablefrom datetime import UTC, date, datetime, timedelta-from typing import Any+from typing import Any, castfrom urllib.parse import parse_qs, urlsplitimport pytest@@ -8,6 +9,8 @@ from unittest import mockimport requests+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import WebhookCreationResultfrom products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun import (MAX_RETRY_AFTER_SECONDS,MailgunResumeConfig,@@ -20,18 +23,27 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.ma_parse_retry_after,_retry_wait,_to_epoch,+ _webhook_table_transformer,base_url_for_region,+ create_webhook,+ delete_webhook,get_domain_names,+ get_external_webhook_info,get_rows,mailgun_source,+ sync_webhook_events,validate_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.settings import (ENDPOINTS,MAILGUN_ENDPOINTS,+ WEBHOOK_EVENTS_ENDPOINT,+ WEBHOOK_TYPES,)US_BASE = "https://api.mailgun.net"+EU_BASE = "https://api.eu.mailgun.net"+POSTHOG_URL = "https://us.posthog.com/public/webhooks/abc"def _make_manager(resume_state: MailgunResumeConfig | None = None) -> mock.MagicMock:@@ -555,7 +567,7 @@ class TestMailgunSourceResponse:@pytest.mark.parametrize("endpoint", list(ENDPOINTS))def test_response_metadata_per_endpoint(self, endpoint):config = MAILGUN_ENDPOINTS[endpoint]- response = mailgun_source("key", "us", endpoint, mock.MagicMock(), _make_manager())+ response = mailgun_source("key", "us", endpoint, mock.MagicMock(), _make_manager(), mock.MagicMock())assert response.name == endpointassert response.primary_keys == config.primary_keys@@ -578,3 +590,290 @@ class TestMailgunSourceResponse:def test_partition_keys_are_stable_creation_fields(self, config):if config.partition_key:assert config.partition_key in {"timestamp", "created_at"}++ def test_webhook_endpoint_returns_a_webhook_only_response(self):+ webhook_manager = mock.MagicMock()+ webhook_manager.webhook_enabled = mock.AsyncMock(return_value=False)++ response = mailgun_source(+ "key", "us", WEBHOOK_EVENTS_ENDPOINT, mock.MagicMock(), _make_manager(), webhook_manager+ )++ assert response.name == WEBHOOK_EVENTS_ENDPOINT+ assert response.webhook_only is True+ # Mailgun webhook payloads carry no sending domain, so the polled `events` table's+ # ["domain", "id"] key can't be reused here.+ assert response.primary_keys == ["id"]+ assert response.partition_keys == ["timestamp"]++ def test_webhook_endpoint_yields_nothing_until_the_webhook_is_live(self):+ webhook_manager = mock.MagicMock()+ webhook_manager.webhook_enabled = mock.AsyncMock(return_value=False)++ response = mailgun_source(+ "key", "us", WEBHOOK_EVENTS_ENDPOINT, mock.MagicMock(), _make_manager(), webhook_manager+ )++ assert list(cast(Iterable[Any], response.items())) == []+ webhook_manager.get_items.assert_not_called()++ def test_webhook_endpoint_reads_pushed_rows_once_enabled(self):+ webhook_manager = mock.MagicMock()+ webhook_manager.webhook_enabled = mock.AsyncMock(return_value=True)++ response = mailgun_source(+ "key", "us", WEBHOOK_EVENTS_ENDPOINT, mock.MagicMock(), _make_manager(), webhook_manager+ )+ response.items()++ webhook_manager.get_items.assert_called_once_with(table_transformer=_webhook_table_transformer)+++class TestWebhookTableTransformer:+ def test_unwraps_the_delivery_envelope_and_normalizes_the_timestamp(self):+ table = table_from_py_list(+ [+ {+ "signature": {"timestamp": "1700000000", "token": "tok", "signature": "sig"},+ "event-data": {"id": "evt_1", "event": "delivered", "timestamp": 1700000000.5},+ }+ ]+ )++ rows = _webhook_table_transformer(table).to_pylist()++ assert rows == [+ {+ "id": "evt_1",+ "event": "delivered",+ "timestamp": datetime.fromtimestamp(1700000000.5, tz=UTC),+ }+ ]++ def test_keeps_the_latest_row_per_event_id_within_one_batch(self):+ table = table_from_py_list(+ [+ {"event-data": {"id": "evt_1", "event": "delivered", "timestamp": 1700000000.0}},+ {"event-data": {"id": "evt_1", "event": "delivered", "timestamp": 1700000900.0}},+ {"event-data": {"id": "evt_2", "event": "opened", "timestamp": 1700000100.0}},+ ]+ )++ rows = {row["id"]: row for row in _webhook_table_transformer(table).to_pylist()}++ assert set(rows) == {"evt_1", "evt_2"}+ assert rows["evt_1"]["timestamp"] == datetime.fromtimestamp(1700000900.0, tz=UTC)++ @pytest.mark.parametrize(+ "payloads",+ [+ [{"event-data": {"event": "delivered", "timestamp": 1700000000.0}}],+ [{"event-data": None}],+ ],+ )+ def test_drops_rows_that_cannot_be_merged(self, payloads):+ assert _webhook_table_transformer(table_from_py_list(payloads)).num_rows == 0++ def test_returns_no_rows_when_the_envelope_key_is_absent(self):+ table = table_from_py_list([{"something": "else"}])++ assert _webhook_table_transformer(table).num_rows == 0+++def _webhook_list_response(webhooks: dict[str, Any]) -> mock.MagicMock:+ return _response({"webhooks": webhooks})+++class TestWebhookManagement:+ def _session(self, mock_session, list_payloads: list[mock.MagicMock]) -> mock.MagicMock:+ """Wire a session whose GETs answer the domain listing first, then one webhook listing+ per domain."""+ session = mock_session.return_value+ session.get.side_effect = [+ _response({"items": [{"name": "mg.example.com"}, {"name": "mg.other.com"}]}),+ *list_payloads,+ ]+ return session++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")+ def test_create_registers_every_event_type_on_every_domain(self, mock_session):+ session = self._session(mock_session, [_webhook_list_response({}), _webhook_list_response({})])+ session.post.return_value = _response({})++ result = create_webhook("key", "us", POSTHOG_URL)++ assert result.success is True+ # Mailgun never returns the signing key, so the user has to paste it before deliveries verify.+ assert result.pending_inputs == ["signing_secret"]+ posted = [(call.args[0], call.kwargs["data"]) for call in session.post.call_args_list]+ assert len(posted) == len(WEBHOOK_TYPES) * 2+ for domain in ("mg.example.com", "mg.other.com"):+ registered = {data["id"] for url, data in posted if url.endswith(f"/v3/domains/{domain}/webhooks")}+ assert registered == set(WEBHOOK_TYPES)+ assert {data["url"] for _, data in posted} == {POSTHOG_URL}++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")+ def test_create_uses_the_region_host(self, mock_session):+ session = self._session(mock_session, [_webhook_list_response({}), _webhook_list_response({})])+ session.post.return_value = _response({})++ create_webhook("key", "eu", POSTHOG_URL)++ assert all(call.args[0].startswith(EU_BASE) for call in session.post.call_args_list)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")+ def test_create_is_idempotent_for_types_already_pointing_at_us(self, mock_session):+ already = {webhook_type: {"urls": [POSTHOG_URL]} for webhook_type in WEBHOOK_TYPES}+ session = self._session(mock_session, [_webhook_list_response(already), _webhook_list_response(already)])++ result = create_webhook("key", "us", POSTHOG_URL)++ assert result.success is True+ session.post.assert_not_called()+ session.put.assert_not_called()++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")+ def test_create_preserves_a_third_partys_url_on_the_same_event_type(self, mock_session):+ session = self._session(+ mock_session,+ [+ _webhook_list_response({"delivered": {"urls": ["https://other.example/hook"]}}),+ _webhook_list_response({}),+ ],+ )+ session.post.return_value = _response({})+ session.put.return_value = _response({})++ create_webhook("key", "us", POSTHOG_URL)++ session.put.assert_called_once()+ assert session.put.call_args.args[0].endswith("/v3/domains/mg.example.com/webhooks/delivered")+ assert session.put.call_args.kwargs["data"] == [+ ("url", "https://other.example/hook"),+ ("url", POSTHOG_URL),+ ]++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")+ def test_create_leaves_a_full_event_type_alone_and_carries_on(self, mock_session):+ # Mailgun caps a webhook type at three URLs, so this one can't take PostHog as well.+ full = {"delivered": {"urls": ["https://a/1", "https://b/2", "https://c/3"]}}+ session = self._session(mock_session, [_webhook_list_response(full), _webhook_list_response({})])+ session.post.return_value = _response({})++ result = create_webhook("key", "us", POSTHOG_URL)++ # Every other type on that domain, and every type on the next one, still registers.+ assert result.success is True+ session.put.assert_not_called()+ posted = [(call.args[0], call.kwargs["data"]["id"]) for call in session.post.call_args_list]+ assert ("https://api.mailgun.net/v3/domains/mg.example.com/webhooks", "delivered") not in posted+ assert ("https://api.mailgun.net/v3/domains/mg.other.com/webhooks", "delivered") in posted+ assert len(posted) == len(WEBHOOK_TYPES) * 2 - 1++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")+ def test_create_fails_when_the_account_has_no_sending_domains(self, mock_session):+ mock_session.return_value.get.return_value = _response({"items": []})++ result = create_webhook("key", "us", POSTHOG_URL)++ assert result.success is False+ assert "no sending domains" in (result.error or "")++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")+ def test_create_fails_when_every_registration_is_refused(self, mock_session):+ session = self._session(mock_session, [_webhook_list_response({}), _webhook_list_response({})])+ session.post.return_value = _error_response(403, f"{US_BASE}/v3/domains/mg.example.com/webhooks")++ result = create_webhook("key", "us", POSTHOG_URL)++ assert result.success is False+ assert "manually" in (result.error or "")++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")+ def test_delete_removes_only_our_url_and_keeps_other_consumers(self, mock_session):+ session = self._session(+ mock_session,+ [+ _webhook_list_response(+ {+ "delivered": {"urls": [POSTHOG_URL, "https://other.example/hook"]},+ "opened": {"urls": [POSTHOG_URL]},+ "clicked": {"urls": ["https://other.example/hook"]},+ }+ ),+ _webhook_list_response({}),+ ],+ )+ session.put.return_value = _response({})+ session.delete.return_value = _response({})++ result = delete_webhook("key", "us", POSTHOG_URL)++ assert result.success is True+ assert session.put.call_args.kwargs["data"] == [("url", "https://other.example/hook")]+ assert session.delete.call_count == 1+ assert session.delete.call_args.args[0].endswith("/webhooks/opened")++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")+ def test_delete_surfaces_a_failure_rather_than_reporting_success(self, mock_session):+ session = self._session(+ mock_session,+ [_webhook_list_response({"opened": {"urls": [POSTHOG_URL]}}), _webhook_list_response({})],+ )+ session.delete.return_value = _error_response(403, f"{US_BASE}/v3/domains/mg.example.com/webhooks/opened")++ result = delete_webhook("key", "us", POSTHOG_URL)++ assert result.success is False+ assert "403" in (result.error or "")++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")+ def test_info_reports_the_registered_event_types(self, mock_session):+ self._session(+ mock_session,+ [+ _webhook_list_response(+ {"delivered": {"urls": [POSTHOG_URL]}, "opened": {"url": "https://other.example/hook"}}+ ),+ _webhook_list_response({"clicked": {"urls": [POSTHOG_URL]}}),+ ],+ )++ info = get_external_webhook_info("key", "us", POSTHOG_URL)++ assert info.exists is True+ # Must speak Mailgun's webhook type ids so the UI can diff them against+ # `get_desired_webhook_events`.+ assert info.enabled_events == ["clicked", "delivered"]++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")+ def test_info_reports_absent_when_no_domain_points_at_us(self, mock_session):+ self._session(+ mock_session,+ [+ _webhook_list_response({"delivered": {"urls": ["https://other.example/hook"]}}),+ _webhook_list_response({}),+ ],+ )++ info = get_external_webhook_info("key", "us", POSTHOG_URL)++ assert info.exists is False++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun.make_tracked_session")+ def test_info_reports_the_error_instead_of_raising(self, mock_session):+ mock_session.return_value.get.return_value = _error_response(401, f"{US_BASE}/v4/domains")++ info = get_external_webhook_info("key", "us", POSTHOG_URL)++ assert info.exists is False+ assert "401" in (info.error or "")++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mailgun.create_webhook")+ def test_sync_re_registers_so_new_domains_get_covered(self, mock_create):+ mock_create.return_value = WebhookCreationResult(success=True)++ result = sync_webhook_events("key", "us", POSTHOG_URL)++ assert result.success is True+ mock_create.assert_called_once_with("key", "us", POSTHOG_URL)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun_source.pyindex 3e2aa7f3439e..ceccfc590fd4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun_source.py@@ -3,6 +3,11 @@ from unittest import mockfrom posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ WebhookCreationResult,+ WebhookDeletionResult,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mailgun import (MailgunSourceConfig,@@ -11,10 +16,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.mafrom products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.settings import (ENDPOINTS,INCREMENTAL_FIELDS,+ WEBHOOK_EVENTS_ENDPOINT,+ WEBHOOK_RESOURCE_KEY,+ WEBHOOK_TYPES,)from products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.source import MailgunSourcefrom products.warehouse_sources.backend.types import ExternalDataSourceType+WEBHOOK_URL = "https://us.posthog.com/public/webhooks/abc"+class TestMailgunSource:def setup_method(self):@@ -79,7 +89,7 @@ class TestMailgunSource:def test_get_schemas(self):schemas = self.source.get_schemas(self.config, self.team_id)- assert {schema.name for schema in schemas} == set(ENDPOINTS)+ assert {schema.name for schema in schemas} == {*ENDPOINTS, WEBHOOK_EVENTS_ENDPOINT}incremental = {schema.name for schema in schemas if schema.supports_incremental}# Only the Events API exposes a server-side timestamp filter.assert incremental == {"events"}@@ -164,3 +174,95 @@ class TestMailgunSource:self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)assert mock_mailgun_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_only_the_webhook_table_is_webhook_capable(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ # A polled schema switched to webhook mode stops polling, and Mailgun has no webhook for+ # the `rejected`, `stored` and list-upload events the Events API returns, so turning+ # webhooks on for `events` would quietly stop collecting them.+ assert {name for name, schema in schemas.items() if schema.supports_webhooks} == {WEBHOOK_EVENTS_ENDPOINT}+ assert {name for name, schema in schemas.items() if schema.webhook_only} == {WEBHOOK_EVENTS_ENDPOINT}++ def test_webhook_table_advertises_no_polling_sync_methods(self):+ schema = next(+ s for s in self.source.get_schemas(self.config, self.team_id) if s.name == WEBHOOK_EVENTS_ENDPOINT+ )++ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_webhook_resource_map_matches_the_template_routing_key(self):+ assert self.source.webhook_resource_map == {WEBHOOK_EVENTS_ENDPOINT: WEBHOOK_RESOURCE_KEY}++ def test_webhook_template_is_wired_up(self):+ template = self.source.webhook_template++ # Routing and signature checks are exercised by running the template in+ # test_mailgun_webhook_template.py; this only guards the wiring.+ assert template is not None+ assert template.type == "warehouse_source_webhook"+ assert template.id == "template-warehouse-source-mailgun"++ def test_signing_secret_is_collected_as_a_webhook_field(self):+ config = self.source.get_source_config++ assert config.webhookFields is not None+ secret_field = next(+ f for f in config.webhookFields if isinstance(f, SourceFieldInputConfig) and f.name == "signing_secret"+ )+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD+ assert secret_field.secret is True+ assert secret_field.required is True++ @pytest.mark.parametrize(+ "eligible_schema_names, expected",+ [+ ([WEBHOOK_EVENTS_ENDPOINT], sorted(WEBHOOK_TYPES)),+ (["events"], None),+ ([], None),+ ],+ )+ def test_desired_webhook_events_speak_mailgun_type_ids(self, eligible_schema_names, expected):+ assert self.source.get_desired_webhook_events(self.config, eligible_schema_names) == expected++ @pytest.mark.parametrize(+ "method, patched, return_value",+ [+ ("create_webhook", "create_mailgun_webhook", WebhookCreationResult(success=True)),+ ("delete_webhook", "delete_mailgun_webhook", WebhookDeletionResult(success=True)),+ ("get_external_webhook_info", "get_mailgun_webhook_info", ExternalWebhookInfo(exists=True)),+ ],+ )+ def test_webhook_methods_target_the_configured_account_and_region(self, method, patched, return_value):+ config = MailgunSourceConfig(api_key="key-123", region="eu")++ with mock.patch(+ f"products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.source.{patched}"+ ) as mock_fn:+ mock_fn.return_value = return_value+ result = getattr(self.source, method)(config, WEBHOOK_URL, self.team_id)++ assert result is return_value+ mock_fn.assert_called_once_with("key-123", "eu", WEBHOOK_URL)++ @pytest.mark.parametrize(+ "eligible_schema_names, expect_call",+ [+ ([WEBHOOK_EVENTS_ENDPOINT], True),+ (["events"], False),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.source.sync_mailgun_webhook_events"+ )+ def test_sync_only_touches_mailgun_when_the_webhook_table_is_selected(+ self, mock_sync, eligible_schema_names, expect_call+ ):+ mock_sync.return_value = mock.MagicMock(success=True)++ result = self.source.sync_webhook_events(self.config, WEBHOOK_URL, self.team_id, eligible_schema_names)++ assert result.success is True+ assert mock_sync.called is expect_calldiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun_webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun_webhook_template.pynew file mode 100644index 000000000000..333ece2dcf17--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/tests/test_mailgun_webhook_template.py@@ -0,0 +1,176 @@+import hmac+import json+import time+import hashlib++from parameterized import parameterized++from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest++from products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.settings import (+ WEBHOOK_EVENT_NAMES,+ WEBHOOK_RESOURCE_KEY,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.mailgun.webhook_template import template++SOURCE_ID = "source_test_123"+SIGNING_KEY = "mailgun_http_webhook_signing_key"+SCHEMA_ID = "schema_webhook_events"+++def _event_data(event: str = "delivered") -> dict:+ return {+ "event": event,+ "id": "CPgfbmQMTCKtHW6uIWtuVe",+ "timestamp": 1699999999.123,+ "recipient": "[email protected]",+ "message": {"headers": {"message-id": "[email protected]"}},+ }+++class TestMailgunWarehouseWebhookTemplate(BaseHogFunctionTemplateTest):+ template = template++ def createHogGlobals(self, globals=None) -> dict:+ data: dict = {+ "request": {+ "method": "POST",+ "headers": {},+ "body": {},+ "query": {},+ "stringBody": "",+ "ip": "127.0.0.1",+ },+ }+ if globals and globals.get("request"):+ data["request"].update(globals["request"])+ return data++ def _make_signed_request(+ self,+ secret: str = SIGNING_KEY,+ event_data: dict | None = None,+ method: str = "POST",+ timestamp: int | None = None,+ token: str = "a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0",+ ) -> dict:+ ts_str = str(timestamp if timestamp is not None else int(time.time()))+ signature = hmac.new(secret.encode(), f"{ts_str}{token}".encode(), hashlib.sha256).hexdigest()+ body = {+ "signature": {"timestamp": ts_str, "token": token, "signature": signature},+ "event-data": _event_data() if event_data is None else event_data,+ }+ return {+ "request": {+ "method": method,+ "headers": {},+ "body": body,+ "stringBody": json.dumps(body),+ "query": {},+ }+ }++ def _inputs(self, **overrides) -> dict:+ return {+ "signing_secret": SIGNING_KEY,+ "bypass_signature_check": False,+ "schema_mapping": {WEBHOOK_RESOURCE_KEY: SCHEMA_ID},+ "source_id": SOURCE_ID,+ **overrides,+ }++ @parameterized.expand([(name,) for name in WEBHOOK_EVENT_NAMES])+ def test_every_subscribed_event_type_reaches_the_webhook_table(self, event_name):+ globals = self._make_signed_request(event_data=_event_data(event_name))++ self.run_function(self._inputs(), globals=globals)++ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(globals["request"]["body"], SCHEMA_ID)++ def test_non_post_request_returns_405(self):+ res = self.run_function(self._inputs(), globals=self._make_signed_request(method="GET"))++ assert res.result == {"httpResponse": {"status": 405, "body": "Method not allowed"}}++ def test_signature_from_a_different_key_is_rejected(self):+ globals = self._make_signed_request(secret="not_our_signing_key")++ res = self.run_function(self._inputs(), globals=globals)++ assert res.result == {"httpResponse": {"status": 400, "body": "Bad signature"}}+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_replayed_delivery_outside_the_time_window_is_rejected(self):+ globals = self._make_signed_request(timestamp=int(time.time()) - 400)++ res = self.run_function(self._inputs(), globals=globals)++ assert res.result == {"httpResponse": {"status": 400, "body": "Timestamp outside tolerance"}}+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ @parameterized.expand(+ [+ ("null", None),+ ("empty_string", ""),+ ]+ )+ def test_missing_signing_secret_returns_400(self, _name, signing_secret):+ globals = self._make_signed_request()++ res = self.run_function(self._inputs(signing_secret=signing_secret), globals=globals)++ assert res.result == {"httpResponse": {"status": 400, "body": "Signing secret not configured"}}+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ @parameterized.expand(+ [+ ("no_signature_block", {}),+ ("missing_signature", {"timestamp": "1699999999", "token": "abc"}),+ ("missing_timestamp", {"token": "abc", "signature": "deadbeef"}),+ ("missing_token", {"timestamp": "1699999999", "signature": "deadbeef"}),+ ]+ )+ def test_incomplete_signature_block_returns_400(self, _name, signature_block):+ body = {"signature": signature_block, "event-data": _event_data()}+ globals = {+ "request": {+ "method": "POST",+ "headers": {},+ "body": body,+ "stringBody": json.dumps(body),+ "query": {},+ }+ }++ res = self.run_function(self._inputs(), globals=globals)++ assert res.result == {"httpResponse": {"status": 400, "body": "Missing signature"}}+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_event_type_we_do_not_subscribe_to_is_skipped(self):+ globals = self._make_signed_request(event_data=_event_data("list_member_uploaded"))++ res = self.run_function(self._inputs(), globals=globals)++ assert res.result == {+ "httpResponse": {"status": 200, "body": "Unhandled event type: list_member_uploaded, skipping"}+ }+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_missing_event_name_is_skipped(self):+ globals = self._make_signed_request(event_data={"id": "evt_1", "timestamp": 1699999999.0})++ res = self.run_function(self._inputs(), globals=globals)++ assert res.result == {"httpResponse": {"status": 200, "body": "No event type found, skipping"}}+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_unmapped_resource_is_skipped(self):+ globals = self._make_signed_request()++ res = self.run_function(self._inputs(schema_mapping={}), globals=globals)++ assert res.result == {+ "httpResponse": {"status": 200, "body": "No schema mapping for event type: delivered, skipping"}+ }+ self.mock_produce_to_warehouse_webhooks.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/webhook_template.pynew file mode 100644index 000000000000..1c1df18120bf--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailgun/webhook_template.py@@ -0,0 +1,168 @@+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC++template: HogFunctionTemplateDC = HogFunctionTemplateDC(+ status="alpha",+ free=False,+ type="warehouse_source_webhook",+ id="template-warehouse-source-mailgun",+ name="Mailgun warehouse source webhook",+ description="Receive Mailgun webhook events for data warehouse ingestion",+ icon_url="/static/services/mailgun.png",+ category=["Data warehouse"],+ code_language="hog",+ code="""\+if (request.method != 'POST') {+ return {+ 'httpResponse': {+ 'status': 405,+ 'body': 'Method not allowed'+ }+ }+}++let signature := request.body.signature++if (not inputs.bypass_signature_check) {+ if (empty(inputs.signing_secret)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Signing secret not configured',+ }+ }+ }++ if (empty(signature) or empty(signature.timestamp) or empty(signature.token) or empty(signature.signature)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Missing signature',+ }+ }+ }++ // Mailgun signs the concatenation of the delivery's timestamp and token with the account's+ // HTTP webhook signing key, hex encoded. The request body itself is not part of the digest.+ let computedSignature := sha256HmacChainHex([inputs.signing_secret, concat(signature.timestamp, signature.token)])++ if (computedSignature != signature.signature) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Bad signature',+ }+ }+ }++ // The digest covers no body, so a captured delivery stays valid forever without a freshness+ // check. Mailgun recommends rejecting timestamps outside a few minutes of now.+ //+ // Because Mailgun's scheme signs only the timestamp and token, a signature proves the delivery+ // came from Mailgun but does not bind it to the payload it arrived with. Anyone holding a+ // captured triple can therefore re-post it with substituted event-data until it goes stale, and+ // that is a property of Mailgun's protocol rather than something this template can verify away.+ // Consuming each token once would close it, but a hog template has no atomic store to consume+ // against, so the window below is the control: it is the only thing bounding how long a captured+ // triple stays usable, so keep it tight. Downstream, the transformer keeps one row per event id+ // within a batch and the table delta-merges on that id, so a straight replay of an unmodified+ // delivery is idempotent; only substituted event-data lands new rows.+ let timestampDelta := toInt(toUnixTimestamp(now())) - toInt(signature.timestamp)+ if (timestampDelta > 300 or timestampDelta < -300) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Timestamp outside tolerance',+ }+ }+ }+}++let eventData := request.body['event-data']+let eventName := eventData.event++if (empty(eventName)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'No event type found, skipping'+ }+ }+}++// Every Mailgun event type feeds the one webhook-only table, so the event is collapsed to a+// resource key before the schema lookup. Keep in sync with WEBHOOK_EVENT_NAMES in settings.py.+let resourceByEvent := {+ 'accepted': 'email_event',+ 'clicked': 'email_event',+ 'complained': 'email_event',+ 'delivered': 'email_event',+ 'failed': 'email_event',+ 'opened': 'email_event',+ 'unsubscribed': 'email_event',+}++let resource := resourceByEvent?.[eventName]++if (empty(resource)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': f'Unhandled event type: {eventName}, skipping'+ }+ }+}++let schemaId := inputs.schema_mapping?.[resource]++if (empty(schemaId)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': f'No schema mapping for event type: {eventName}, skipping'+ }+ }+}++produceToWarehouseWebhooks(request.body, schemaId)""",+ inputs_schema=[+ {+ "type": "string",+ "key": "signing_secret",+ "label": "HTTP webhook signing key",+ "required": False,+ "secret": True,+ "hidden": False,+ "description": (+ "Your Mailgun account's HTTP webhook signing key, from Settings > API security. Used to "+ "verify the HMAC-SHA256 signature Mailgun sends on every delivery."+ ),+ },+ {+ "type": "boolean",+ "key": "bypass_signature_check",+ "label": "Bypass signature check",+ "description": "If set, the Mailgun signature will not be checked. This is not recommended.",+ "default": False,+ "required": False,+ "secret": False,+ },+ {+ "type": "json",+ "key": "schema_mapping",+ "label": "Schema mapping",+ "description": "Maps Mailgun resource keys to ExternalDataSchema IDs",+ "required": True,+ "secret": False,+ "hidden": True,+ },+ {+ "type": "string",+ "key": "source_id",+ "label": "Source ID",+ "description": "The ExternalDataSource ID this webhook is associated with",+ "required": True,+ "secret": False,+ "hidden": True,+ },+ ],+)