: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 Mailjet webhook ingestion (#77492)
Tom Owers9e64159bf219
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 660a5a2fa1fd..0ed72bb5d161 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -397,7 +397,7 @@ the row lists both.| mailerlite | HTTP | requests | ✅ || mailersend | HTTP | requests | ✅ || mailgun | HTTP | requests | ✅ |-| mailjet | HTTP | requests | ✅ |+| mailjet | HTTP + Webhook | `rest_source.RESTClient` + requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || mailosaur | HTTP | requests | ✅ || mailtrap | HTTP | requests | ✅ || marketstack | HTTP | requests | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/canonical_descriptions.pyindex ee47b85a9ca9..d08d3b9d83a9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/canonical_descriptions.py@@ -148,4 +148,38 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"UserAgent": "The user agent of the device that clicked the link.",},},+ "messageevent": {+ "description": (+ "A delivery or engagement event pushed by the Mailjet Event API: sent, open, click, "+ "bounce, blocked, spam or unsub. Mailjet has no list endpoint for this stream, so the "+ "table is populated by webhook deliveries only."+ ),+ "docs_url": "https://dev.mailjet.com/email/guides/webhooks/",+ "columns": {+ "event_id": "Identifier PostHog derives from the delivery body so repeated deliveries of the same event collapse onto one row.",+ "event": "The event type: sent, open, click, bounce, blocked, spam or unsub.",+ "time": "Unix timestamp of the event.",+ "email": "Email address of the recipient that triggered the event.",+ "mj_campaign_id": "The internal Mailjet campaign identifier for the message.",+ "mj_contact_id": "The internal Mailjet contact identifier for the recipient.",+ "customcampaign": "Value of the X-Mailjet-Campaign header, when one was provided at send time.",+ "MessageID": "The unique message identifier.",+ "Message_GUID": "The globally unique identifier for the message.",+ "CustomID": "The custom identifier provided at send time, if any.",+ "Payload": "The event payload provided at send time, if any.",+ "mj_message_id": "The unique message identifier as a string. Deprecated in favor of MessageID.",+ "smtp_reply": "The raw SMTP response message. Sent events only.",+ "ip": "IP address that triggered the event. Open, click and unsub events only.",+ "geo": "Country code of the IP address that triggered the event.",+ "agent": "User agent of the device that triggered the event.",+ "url": "The link that was clicked. Click events only.",+ "blocked": "Whether the bounce led to the recipient being blocked.",+ "hard_bounce": "Whether the delivery error was permanent.",+ "error_related_to": "The category the delivery error belongs to, such as recipient, domain or content.",+ "error": "The delivery error, such as user unknown or invalid domain.",+ "comment": "The raw SMTP error, including the reason for the bounce.",+ "source": "The feedback loop program that reported the spam complaint. Spam events only.",+ "mj_list_id": "The internal Mailjet contact list identifier. Unsub events only.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/mailjet.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/mailjet.pyindex 9c643b94a4ab..4407da4c16c3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/mailjet.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/mailjet.py@@ -1,8 +1,22 @@import base64+import secretsimport dataclassesfrom datetime import UTC, date, datetimefrom typing import Any, Optional+from urllib.parse import urlsplit, urlunsplit+import pyarrow as pa+import structlog+from asgiref.sync import async_to_sync+from requests import Session++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.rest_source import (RESTAPIConfig,@@ -14,12 +28,26 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom 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.mailjet.settings import (MAILJET_ENDPOINTS,+ MAILJET_WEBHOOK_EVENTS,+ WEBHOOK_PRIMARY_KEY,+ WEBHOOK_TABLE_NAME,MailjetEndpointConfig,)MAILJET_BASE_URL = "https://api.mailjet.com/v3/REST"+WEBHOOK_PATH = "/eventcallbackurl"+REQUEST_TIMEOUT_SECONDS = 30++# Mailjet does not sign deliveries. Its documented way to prove a delivery came from Mailjet is+# HTTP basic credentials embedded in the registered callback URL, which Mailjet then sends as an+# `Authorization` header on every POST. PostHog generates the password, registers the URL with it+# and stores the expected header on the webhook function.+WEBHOOK_BASIC_AUTH_USERNAME = "posthog"++LOGGER = structlog.get_logger(__name__)@dataclasses.dataclass@@ -83,6 +111,49 @@ def validate_credentials(api_key: str, secret_key: str) -> bool:return ok+def _webhook_table_transformer(table: pa.Table) -> pa.Table:+ """Keep one row per ``event_id`` within a batch.++ Delta merge only dedupes across syncs, so a batch that picked up the same delivery twice+ (Mailjet retries until it gets a 200) would otherwise seed duplicate rows. Rows are+ otherwise passed through untouched — Mailjet's event payload is already the row shape.+ """+ rows: dict[str, dict[str, Any]] = {}+ extras: list[dict[str, Any]] = []+ for row in table.to_pylist():+ event_id = row.get(WEBHOOK_PRIMARY_KEY)+ if isinstance(event_id, str) and event_id:+ rows[event_id] = row+ else:+ # Shouldn't happen — the Hog template always sets it — but dropping rows silently+ # would be worse than letting the merge deal with a missing key.+ extras.append(row)++ return table_from_py_list([*rows.values(), *extras])+++def _webhook_source(endpoint: str, webhook_source_manager: WebhookSourceManager) -> SourceResponse:+ """The `messageevent` table: fed only by the Event API, never by a poll.++ ``webhook_only`` tells the pipeline the poll does no backfill, so a requested reset keeps the+ Delta table and resumes webhook ingestion instead of wiping rows nothing could rebuild.+ """+ webhook_enabled = async_to_sync(webhook_source_manager.webhook_enabled)(webhook_only=True)++ def items() -> Any:+ if not webhook_enabled:+ return []+ return webhook_source_manager.get_items(table_transformer=_webhook_table_transformer)++ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=[WEBHOOK_PRIMARY_KEY],+ webhook_only=True,+ sort_mode="asc",+ )++def mailjet_source(api_key: str,secret_key: str,@@ -90,9 +161,13 @@ def mailjet_source(team_id: int,job_id: str,resumable_source_manager: ResumableSourceManager[MailjetResumeConfig],+ webhook_source_manager: WebhookSourceManager,should_use_incremental_field: bool = False,db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:+ if endpoint == WEBHOOK_TABLE_NAME:+ return _webhook_source(endpoint, webhook_source_manager)+config = MAILJET_ENDPOINTS[endpoint]limit = config.page_size@@ -161,3 +236,167 @@ def mailjet_source(sort_mode="asc",column_hints=resource.column_hints,)+++def _webhook_session(api_key: str, secret_key: str, *redact: str) -> Session:+ return make_tracked_session(+ headers=_get_headers(api_key, secret_key),+ redact_values=(secret_key, *redact),+ # Callback URLs carry the basic-auth password we generated, so keep these responses out+ # of sample capture.+ capture=False,+ )+++def _authenticated_callback_url(webhook_url: str, password: str) -> str:+ parts = urlsplit(webhook_url)+ return urlunsplit(+ (parts.scheme, f"{WEBHOOK_BASIC_AUTH_USERNAME}:{password}@{parts.netloc}", parts.path, parts.query, "")+ )+++def _without_credentials(url: str) -> str:+ """Strip any `user:password@` prefix so a stored callback URL can be matched against ours."""+ parts = urlsplit(url)+ return urlunsplit((parts.scheme, parts.netloc.rpartition("@")[2], parts.path, parts.query, ""))+++def expected_authorization_header(password: str) -> str:+ token = base64.b64encode(f"{WEBHOOK_BASIC_AUTH_USERNAME}:{password}".encode()).decode()+ return f"Basic {token}"+++def _list_callback_urls(session: Session) -> list[dict[str, Any]]:+ response = session.get(+ f"{MAILJET_BASE_URL}{WEBHOOK_PATH}",+ # Mailjet defaults this list to 10 rows, which an account with its own callbacks can+ # exceed — ours would then be invisible to matching, so ask for the maximum page.+ params={"Limit": 1000},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ return [item for item in response.json().get("Data") or [] if isinstance(item, dict)]+++def _matching_callback_urls(session: Session, webhook_url: str) -> list[dict[str, Any]]:+ return [+ item for item in _list_callback_urls(session) if _without_credentials(str(item.get("Url", ""))) == webhook_url+ ]+++def _register_event(session: Session, callback_url: str, event: str) -> None:+ response = session.post(+ f"{MAILJET_BASE_URL}{WEBHOOK_PATH}",+ json={+ "EventType": event,+ "Url": callback_url,+ "Status": "alive",+ "IsBackup": False,+ # Version 1 posts one event per request. Version 2 batches events into a JSON array,+ # which the warehouse webhook pipeline cannot unpack into rows.+ "Version": 1,+ },+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+++def create_webhook(api_key: str, secret_key: str, webhook_url: str) -> WebhookCreationResult:+ """Register one callback URL per Mailjet event type, all pointing at `webhook_url`.++ The registered URL carries generated basic-auth credentials, which Mailjet replays as an+ `Authorization` header on every delivery. The expected header value goes back on the webhook+ function via `extra_inputs` so the Hog template can reject anything else.+ """+ password = secrets.token_urlsafe(32)+ callback_url = _authenticated_callback_url(webhook_url, password)+ session = _webhook_session(api_key, secret_key, password, callback_url)++ registered: list[str] = []+ failures: list[str] = []+ for event in MAILJET_WEBHOOK_EVENTS:+ try:+ _register_event(session, callback_url, event)+ registered.append(event)+ except Exception as e:+ LOGGER.warning("Failed to register Mailjet callback URL", event_type=event, error=str(e))+ failures.append(event)++ if not registered:+ return WebhookCreationResult(+ success=False,+ error="Mailjet refused to register the callback URL. Check that the API key can manage webhooks.",+ )++ if failures:+ # Partial success still has to persist the password: the registrations that landed can+ # only be verified with it, and `sync_webhook_events` reuses the stored URL to fill gaps.+ LOGGER.warning("Registered Mailjet callback URL for some events only", missing=failures)++ return WebhookCreationResult(+ success=True, extra_inputs={"authorization_header": expected_authorization_header(password)}+ )+++def sync_webhook_events(+ api_key: str, secret_key: str, webhook_url: str, desired_events: list[str]+) -> WebhookSyncResult:+ """Register any `desired_events` that have no callback URL yet, reusing the credentials+ already on the existing registrations. Never removes an event — a user may have added one."""+ if not desired_events:+ return WebhookSyncResult(success=True)++ try:+ session = _webhook_session(api_key, secret_key)+ matching = _matching_callback_urls(session, webhook_url)+ if not matching:+ # Nothing registered yet; `create_webhook` owns that path.+ return WebhookSyncResult(success=True)++ existing = {str(item.get("EventType")) for item in matching}+ missing = [event for event in desired_events if event not in existing]+ if not missing:+ return WebhookSyncResult(success=True)++ callback_url = str(matching[0].get("Url"))+ for event in missing:+ _register_event(session, callback_url, event)+ return WebhookSyncResult(success=True)+ except Exception as e:+ return WebhookSyncResult(success=False, error=f"Failed to update Mailjet callback URLs: {e}")+++def get_external_webhook_info(api_key: str, secret_key: str, webhook_url: str) -> ExternalWebhookInfo:+ try:+ matching = _matching_callback_urls(_webhook_session(api_key, secret_key), webhook_url)+ except Exception as e:+ return ExternalWebhookInfo(exists=False, error=str(e))++ if not matching:+ return ExternalWebhookInfo(exists=False)++ statuses = {str(item.get("Status")) for item in matching}+ return ExternalWebhookInfo(+ exists=True,+ # Deliberately the credential-free URL — the registered one embeds the shared password.+ url=webhook_url,+ enabled_events=sorted({str(item.get("EventType")) for item in matching}),+ status="alive" if statuses == {"alive"} else ", ".join(sorted(statuses)),+ )+++def delete_webhook(api_key: str, secret_key: str, webhook_url: str) -> WebhookDeletionResult:+ try:+ session = _webhook_session(api_key, secret_key)+ errors: list[str] = []+ for item in _matching_callback_urls(session, webhook_url):+ response = session.delete(+ f"{MAILJET_BASE_URL}{WEBHOOK_PATH}/{item.get('ID')}", timeout=REQUEST_TIMEOUT_SECONDS+ )+ if response.status_code not in (200, 204):+ errors.append(f"{item.get('EventType')}: HTTP {response.status_code}")+ if errors:+ return WebhookDeletionResult(success=False, error="; ".join(errors))+ return WebhookDeletionResult(success=True)+ except Exception as e:+ return WebhookDeletionResult(success=False, error=str(e))diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/settings.pyindex aa047467217a..c161b3364c4e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/settings.py@@ -96,8 +96,32 @@ MAILJET_ENDPOINTS: dict[str, MailjetEndpointConfig] = {),}-ENDPOINTS = tuple(MAILJET_ENDPOINTS.keys())+# The Event API pushes per-recipient engagement and delivery events. Mailjet exposes no list+# endpoint for that stream — `/openinformation` and `/clickstatistics` cover opens and clicks+# only, under different field names — so these rows can only ever arrive by webhook, and they+# land in their own table rather than merging into a polled one.+WEBHOOK_TABLE_NAME = "messageevent"++# Every event type Mailjet's Event API can push. Each one is a separate `eventcallbackurl`+# registration; all of them feed the single `messageevent` table.+MAILJET_WEBHOOK_EVENTS: tuple[str, ...] = ("sent", "open", "click", "bounce", "blocked", "spam", "unsub")++WEBHOOK_SCHEMA_NAMES: frozenset[str] = frozenset({WEBHOOK_TABLE_NAME})++# Schema name -> the `schema_mapping` key the Hog template routes incoming events by.+SCHEMA_TO_WEBHOOK_RESOURCE: dict[str, str] = {WEBHOOK_TABLE_NAME: WEBHOOK_TABLE_NAME}++# Mailjet event payloads carry no event identifier, so the Hog template derives one by hashing+# the raw delivery body. Retries (Mailjet re-POSTs every 30s for up to 24h until it gets a 200)+# repeat the same body, so they collapse onto the same row.+WEBHOOK_PRIMARY_KEY = "event_id"++POLL_ENDPOINTS = tuple(MAILJET_ENDPOINTS.keys())++ENDPOINTS = (*POLL_ENDPOINTS, WEBHOOK_TABLE_NAME)INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: config.incremental_fields for name, config in MAILJET_ENDPOINTS.items()}+# Webhook rows arrive as they happen, so there is no cursor to advance.+INCREMENTAL_FIELDS[WEBHOOK_TABLE_NAME] = []diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/source.pyindex b540206a1b03..6ee4215af03b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/source.py@@ -1,4 +1,4 @@-from typing import Optional, cast+from typing import TYPE_CHECKING, Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,@@ -9,7 +9,15 @@ from posthog.schema import (SourceFieldInputConfigType,)-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,)@@ -20,9 +28,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.schbuild_endpoint_schemas,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mailjet import (MailjetSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.mailjet import mailjet as api_clientfrom products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.mailjet import (MailjetResumeConfig,mailjet_source,@@ -31,12 +41,21 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.mafrom products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.settings import (ENDPOINTS,INCREMENTAL_FIELDS,+ MAILJET_WEBHOOK_EVENTS,+ SCHEMA_TO_WEBHOOK_RESOURCE,+ WEBHOOK_SCHEMA_NAMES,)from products.warehouse_sources.backend.types import ExternalDataSourceType+if TYPE_CHECKING:+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC+@SourceRegistry.register-class MailJetSource(ResumableSource[MailjetSourceConfig, MailjetResumeConfig]):+class MailJetSource(+ ResumableSource[MailjetSourceConfig, MailjetResumeConfig],+ WebhookSource[MailjetSourceConfig],+):lists_tables_without_credentials = True # static endpoint catalog — safe for public docssupported_versions = ("v3",)@@ -81,6 +100,15 @@ You can find your API key and secret key in your [Mailjet API key management pag),],),+ webhookSetupCaption=(+ "PostHog registers one Mailjet event callback URL per event type using the API key above, "+ "covering sent, open, click, bounce, blocked, spam and unsub.\n\n"+ "Mailjet does not sign its deliveries, so PostHog embeds generated basic-auth credentials in "+ "the callback URL it registers. Mailjet sends those back as an Authorization header on every "+ "delivery, and PostHog rejects anything that doesn't match.\n\n"+ "The sent event fires once for every message you send, so this table can grow quickly on high "+ "volume accounts."+ ),)def get_canonical_descriptions(self) -> CanonicalDescriptions:@@ -103,7 +131,11 @@ You can find your API key and secret key in your [Mailjet API key management pag# The statistics endpoints support Mailjet's FromTS window, so they sync incrementally# (they're exactly the endpoints carrying incremental fields). Within-sync resumption is# handled by ResumableSource for all endpoints.- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ schemas = build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, supports_webhooks=WEBHOOK_SCHEMA_NAMES)+ for schema in schemas:+ # `messageevent` has no list endpoint behind it, so the UI must offer webhook sync only.+ schema.webhook_only = schema.name in WEBHOOK_SCHEMA_NAMES+ return schemasdef validate_credentials(self,@@ -128,6 +160,54 @@ You can find your API key and secret key in your [Mailjet API key management pagdef get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MailjetResumeConfig]:return ResumableSourceManager[MailjetResumeConfig](inputs, MailjetResumeConfig)+ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:+ return WebhookSourceManager(inputs, inputs.logger)++ @property+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:+ from products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.webhook_template import ( # noqa: PLC0415+ template,+ )++ return template++ @property+ def webhook_resource_map(self) -> dict[str, str]:+ return SCHEMA_TO_WEBHOOK_RESOURCE++ def get_desired_webhook_events(+ self, config: MailjetSourceConfig, eligible_schema_names: list[str]+ ) -> list[str] | None:+ if not any(name in WEBHOOK_SCHEMA_NAMES for name in eligible_schema_names):+ return []+ return list(MAILJET_WEBHOOK_EVENTS)++ def create_webhook(+ self, config: MailjetSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> WebhookCreationResult:+ return api_client.create_webhook(config.api_key, config.secret_key, webhook_url)++ def sync_webhook_events(+ self,+ config: MailjetSourceConfig,+ webhook_url: str,+ team_id: int,+ eligible_schema_names: list[str],+ api_version: str | None = None,+ ) -> WebhookSyncResult:+ desired_events = self.get_desired_webhook_events(config, eligible_schema_names) or []+ return api_client.sync_webhook_events(config.api_key, config.secret_key, webhook_url, desired_events)++ def get_external_webhook_info(+ self, config: MailjetSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> ExternalWebhookInfo | None:+ return api_client.get_external_webhook_info(config.api_key, config.secret_key, webhook_url)++ def delete_webhook(+ self, config: MailjetSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> WebhookDeletionResult:+ return api_client.delete_webhook(config.api_key, config.secret_key, webhook_url)+def source_for_pipeline(self,config: MailjetSourceConfig,@@ -141,6 +221,7 @@ You can find your API key and secret key in your [Mailjet API key management pagteam_id=inputs.team_id,job_id=inputs.job_id,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/mailjet/tests/test_mailjet.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/tests/test_mailjet.pyindex 8ff62da46b46..bb0cfb045615 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/tests/test_mailjet.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/tests/test_mailjet.py@@ -11,14 +11,24 @@ from requests import Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.mailjet import (MAILJET_BASE_URL,+ WEBHOOK_PATH,MailjetResumeConfig,+ _authenticated_callback_url,_to_unix_ts,+ _webhook_table_transformer,+ _without_credentials,+ create_webhook,+ delete_webhook,+ expected_authorization_header,+ get_external_webhook_info,mailjet_source,+ sync_webhook_events,validate_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.settings import (- ENDPOINTS,MAILJET_ENDPOINTS,+ MAILJET_WEBHOOK_EVENTS,+ WEBHOOK_TABLE_NAME,)# RESTClient builds its session via make_tracked_session in the rest_client module.@@ -75,6 +85,7 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> tuple[list[dictdef _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):+ kwargs.setdefault("webhook_source_manager", mock.MagicMock())return mailjet_source("key", "secret", endpoint, team_id=1, job_id="j", resumable_source_manager=manager, **kwargs)@@ -175,7 +186,7 @@ class TestOffsetPagination:assert _rows(source) == []assert session.send.call_count == 1- @parameterized.expand([(name,) for name in ENDPOINTS])+ @parameterized.expand([(name,) for name in MAILJET_ENDPOINTS])@mock.patch(CLIENT_SESSION_PATCH)def test_sort_param_sent(self, endpoint: str, MockSession) -> None:session = MockSession.return_value@@ -292,7 +303,7 @@ class TestIncremental:class TestSourceResponseShape:- @parameterized.expand([(name,) for name in ENDPOINTS])+ @parameterized.expand([(name,) for name in MAILJET_ENDPOINTS])def test_source_response_shape(self, endpoint: str) -> None:response = _source(endpoint, _make_manager())config = MAILJET_ENDPOINTS[endpoint]@@ -361,3 +372,245 @@ class TestValidateCredentials:def test_validate_credentials_network_error_returns_false(self, mock_session) -> None:mock_session.return_value.get.side_effect = Exception("boom")assert validate_credentials("key", "secret") is False+++WEBHOOK_URL = "https://webhooks.us.posthog.com/public/webhooks/dwh/hog-fn-1"+++def _callback_row(event: str, url: str, row_id: int = 1, status: str = "alive") -> dict[str, Any]:+ return {"ID": row_id, "EventType": event, "Url": url, "Status": status, "Version": 1, "IsBackup": False}+++def _json_response(body: dict[str, Any], status_code: int = 200) -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.json.return_value = body+ return response+++class TestWebhookCallbackUrl:+ def test_credentials_round_trip(self) -> None:+ authed = _authenticated_callback_url(WEBHOOK_URL, "p@ss")+ # The password rides in the URL's userinfo, which is what Mailjet replays as basic auth.+ assert authed.startswith("https://posthog:p@[email protected]/")+ assert _without_credentials(authed) == WEBHOOK_URL++ def test_url_without_credentials_is_unchanged(self) -> None:+ assert _without_credentials(WEBHOOK_URL) == WEBHOOK_URL++ def test_expected_header_matches_the_registered_credentials(self) -> None:+ header = expected_authorization_header("p@ss")+ assert base64.b64decode(header.removeprefix("Basic ")).decode() == "posthog:p@ss"+++class TestCreateWebhook:+ @mock.patch(MAILJET_SESSION_PATCH)+ def test_registers_every_event_type_with_authenticated_url(self, mock_session) -> None:+ session = mock_session.return_value+ session.post.return_value = _json_response({"Data": []}, 201)++ result = create_webhook("key", "secret", WEBHOOK_URL)++ assert result.success is True+ posted = [call.kwargs["json"] for call in session.post.call_args_list]+ assert [body["EventType"] for body in posted] == list(MAILJET_WEBHOOK_EVENTS)+ # Version 1 delivers one event per request; Version 2 would batch them into an array the+ # warehouse webhook pipeline cannot unpack.+ assert {body["Version"] for body in posted} == {1}++ registered_url = posted[0]["Url"]+ assert _without_credentials(registered_url) == WEBHOOK_URL+ password = registered_url.split("posthog:", 1)[1].rsplit("@", 1)[0]+ assert result.extra_inputs == {"authorization_header": expected_authorization_header(password)}++ @mock.patch(MAILJET_SESSION_PATCH)+ def test_partial_failure_still_persists_the_credentials(self, mock_session) -> None:+ # Losing the password would leave the registrations that did land unverifiable forever.+ session = mock_session.return_value+ ok = _json_response({"Data": []}, 201)+ bad = _json_response({}, 400)+ bad.raise_for_status.side_effect = Exception("bad request")+ session.post.side_effect = [ok, bad, ok, ok, ok, ok, ok]++ result = create_webhook("key", "secret", WEBHOOK_URL)++ assert result.success is True+ assert "authorization_header" in result.extra_inputs++ @mock.patch(MAILJET_SESSION_PATCH)+ def test_total_failure_reports_an_error(self, mock_session) -> None:+ session = mock_session.return_value+ response = _json_response({}, 403)+ response.raise_for_status.side_effect = Exception("forbidden")+ session.post.return_value = response++ result = create_webhook("key", "secret", WEBHOOK_URL)++ assert result.success is False+ assert result.error is not None+ assert result.extra_inputs == {}+++class TestSyncWebhookEvents:+ @mock.patch(MAILJET_SESSION_PATCH)+ def test_registers_only_the_missing_events_reusing_stored_credentials(self, mock_session) -> None:+ session = mock_session.return_value+ authed = _authenticated_callback_url(WEBHOOK_URL, "stored-password")+ session.get.return_value = _json_response({"Data": [_callback_row("open", authed)]})+ session.post.return_value = _json_response({"Data": []}, 201)++ result = sync_webhook_events("key", "secret", WEBHOOK_URL, ["open", "click"])++ assert result.success is True+ posted = [call.kwargs["json"] for call in session.post.call_args_list]+ assert [body["EventType"] for body in posted] == ["click"]+ # The password only exists on the stored registration, so it has to be carried over.+ assert posted[0]["Url"] == authed++ @mock.patch(MAILJET_SESSION_PATCH)+ def test_no_op_when_every_event_is_registered(self, mock_session) -> None:+ session = mock_session.return_value+ authed = _authenticated_callback_url(WEBHOOK_URL, "stored-password")+ session.get.return_value = _json_response(+ {"Data": [_callback_row(event, authed, row_id=i) for i, event in enumerate(MAILJET_WEBHOOK_EVENTS)]}+ )++ assert sync_webhook_events("key", "secret", WEBHOOK_URL, list(MAILJET_WEBHOOK_EVENTS)).success is True+ session.post.assert_not_called()++ @mock.patch(MAILJET_SESSION_PATCH)+ def test_ignores_callback_urls_belonging_to_other_destinations(self, mock_session) -> None:+ session = mock_session.return_value+ session.get.return_value = _json_response({"Data": [_callback_row("open", "https://example.com/hook")]})++ assert sync_webhook_events("key", "secret", WEBHOOK_URL, ["open"]).success is True+ session.post.assert_not_called()++ @mock.patch(MAILJET_SESSION_PATCH)+ def test_api_failure_is_reported_not_raised(self, mock_session) -> None:+ session = mock_session.return_value+ session.get.side_effect = Exception("boom")++ result = sync_webhook_events("key", "secret", WEBHOOK_URL, ["open"])++ assert result.success is False+ assert result.error is not None+++class TestExternalWebhookInfo:+ @mock.patch(MAILJET_SESSION_PATCH)+ def test_reports_registered_events_without_leaking_the_password(self, mock_session) -> None:+ session = mock_session.return_value+ authed = _authenticated_callback_url(WEBHOOK_URL, "stored-password")+ session.get.return_value = _json_response(+ {"Data": [_callback_row("open", authed, 1), _callback_row("click", authed, 2)]}+ )++ info = get_external_webhook_info("key", "secret", WEBHOOK_URL)++ assert info.exists is True+ assert info.enabled_events == ["click", "open"]+ assert info.url == WEBHOOK_URL+ assert "stored-password" not in (info.url or "")++ @mock.patch(MAILJET_SESSION_PATCH)+ def test_asks_for_more_than_mailjets_default_page(self, mock_session) -> None:+ # Mailjet returns 10 callback URLs by default. An account with its own callbacks would+ # push ours off that page and every match would come back empty.+ session = mock_session.return_value+ session.get.return_value = _json_response({"Data": []})++ get_external_webhook_info("key", "secret", WEBHOOK_URL)++ assert session.get.call_args.kwargs["params"]["Limit"] > 10++ @mock.patch(MAILJET_SESSION_PATCH)+ def test_reports_missing_when_nothing_points_at_us(self, mock_session) -> None:+ session = mock_session.return_value+ session.get.return_value = _json_response({"Data": [_callback_row("open", "https://example.com/hook")]})++ assert get_external_webhook_info("key", "secret", WEBHOOK_URL).exists is False+++class TestDeleteWebhook:+ @mock.patch(MAILJET_SESSION_PATCH)+ def test_deletes_only_our_callback_urls(self, mock_session) -> None:+ session = mock_session.return_value+ authed = _authenticated_callback_url(WEBHOOK_URL, "stored-password")+ session.get.return_value = _json_response(+ {"Data": [_callback_row("open", authed, 1), _callback_row("click", "https://example.com/hook", 2)]}+ )+ session.delete.return_value = _json_response({}, 200)++ result = delete_webhook("key", "secret", WEBHOOK_URL)++ assert result.success is True+ deleted = [call.args[0] for call in session.delete.call_args_list]+ assert deleted == [f"{MAILJET_BASE_URL}{WEBHOOK_PATH}/1"]++ @mock.patch(MAILJET_SESSION_PATCH)+ def test_reports_a_refused_delete(self, mock_session) -> None:+ session = mock_session.return_value+ authed = _authenticated_callback_url(WEBHOOK_URL, "stored-password")+ session.get.return_value = _json_response({"Data": [_callback_row("open", authed, 1)]})+ session.delete.return_value = _json_response({}, 403)++ result = delete_webhook("key", "secret", WEBHOOK_URL)++ assert result.success is False+ assert result.error is not None+++class TestWebhookTableTransformer:+ def test_keeps_the_last_row_per_event_id(self) -> None:+ # Delta merge only dedupes across syncs, so a batch carrying the same delivery twice+ # would otherwise seed duplicate rows on the very first sync.+ import pyarrow as pa++ table = pa.Table.from_pylist(+ [+ {"event_id": "a", "event": "open", "time": 1},+ {"event_id": "b", "event": "click", "time": 2},+ {"event_id": "a", "event": "open", "time": 1},+ ]+ )++ result = _webhook_table_transformer(table).to_pylist()++ assert sorted(row["event_id"] for row in result) == ["a", "b"]++ def test_rows_without_an_event_id_are_kept(self) -> None:+ import pyarrow as pa++ table = pa.Table.from_pylist([{"event_id": None, "event": "open"}, {"event_id": "a", "event": "click"}])++ assert len(_webhook_table_transformer(table).to_pylist()) == 2+++class TestWebhookOnlySource:+ def _manager(self, enabled: bool) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.webhook_enabled = mock.AsyncMock(return_value=enabled)+ return manager++ def test_reads_webhook_rows_with_the_dedupe_transformer(self) -> None:+ manager = self._manager(enabled=True)++ response = _source(WEBHOOK_TABLE_NAME, _make_manager(), webhook_source_manager=manager)+ response.items()++ assert response.name == WEBHOOK_TABLE_NAME+ assert response.primary_keys == ["event_id"]+ # Marks the poll as backfill-free, so a reset resumes ingestion rather than wiping rows+ # that no poll could rebuild.+ assert response.webhook_only is True+ manager.webhook_enabled.assert_awaited_once_with(webhook_only=True)+ assert manager.get_items.call_args.kwargs["table_transformer"] is _webhook_table_transformer++ def test_yields_nothing_until_the_webhook_is_registered(self) -> None:+ manager = self._manager(enabled=False)++ response = _source(WEBHOOK_TABLE_NAME, _make_manager(), webhook_source_manager=manager)++ assert list(response.items()) == []+ manager.get_items.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/tests/test_mailjet_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/tests/test_mailjet_source.pyindex f93b5bb0cc61..33ad7d67a66e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/tests/test_mailjet_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/tests/test_mailjet_source.py@@ -3,15 +3,25 @@ from unittest import mockfrom posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigTypefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mailjet import (MailjetSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.mailjet import MailjetResumeConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.settings import (+ ENDPOINTS,+ MAILJET_WEBHOOK_EVENTS,+ SCHEMA_TO_WEBHOOK_RESOURCE,+ WEBHOOK_SCHEMA_NAMES,+ WEBHOOK_TABLE_NAME,+)from products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.source import MailJetSource+from products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.webhook_template import templatefrom products.warehouse_sources.backend.types import ExternalDataSourceType_STATISTICS_ENDPOINTS = {"openinformation", "clickstatistics"}+WEBHOOK_URL = "https://webhooks.us.posthog.com/public/webhooks/dwh/hog-fn-1"+API_CLIENT_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.source.api_client"class TestMailJetSource:@@ -56,6 +66,62 @@ class TestMailJetSource:else:assert schema.incremental_fields == []+ def test_webhook_capable_schemas(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert {name for name, schema in schemas.items() if schema.supports_webhooks} == set(WEBHOOK_SCHEMA_NAMES)+ # The message event stream has no list endpoint behind it, so polling can never rebuild it+ # and the UI must offer webhook sync only.+ assert schemas[WEBHOOK_TABLE_NAME].webhook_only is True+ assert all(not schema.webhook_only for name, schema in schemas.items() if name != WEBHOOK_TABLE_NAME)++ def test_polled_schemas_never_gain_webhooks(self):+ # Mailjet's event payloads name their fields differently to /openinformation and+ # /clickstatistics (mj_contact_id vs ContactID, time vs OpenedAt, no ID at all), so routing+ # them into those tables would break the merge and disable their poll.+ schemas = self.source.get_schemas(self.config, self.team_id)+ polled_with_webhooks = {+ schema.name for schema in schemas if schema.supports_webhooks and schema.name != WEBHOOK_TABLE_NAME+ }+ assert polled_with_webhooks == set()++ def test_webhook_resource_map_covers_the_webhook_schema(self):+ assert self.source.webhook_resource_map == SCHEMA_TO_WEBHOOK_RESOURCE+ assert set(SCHEMA_TO_WEBHOOK_RESOURCE) == set(WEBHOOK_SCHEMA_NAMES)++ def test_webhook_template_routes_every_subscribed_event(self):+ assert template.type == "warehouse_source_webhook"+ # An event we register but never route would be acknowledged and silently dropped.+ for event in MAILJET_WEBHOOK_EVENTS:+ assert f"'{event}': '{WEBHOOK_TABLE_NAME}'" in template.code++ def test_get_desired_webhook_events_only_fires_for_the_webhook_schema(self):+ assert self.source.get_desired_webhook_events(self.config, [WEBHOOK_TABLE_NAME]) == list(MAILJET_WEBHOOK_EVENTS)+ assert self.source.get_desired_webhook_events(self.config, ["contact"]) == []++ def test_get_webhook_source_manager(self):+ assert isinstance(self.source.get_webhook_source_manager(mock.MagicMock()), WebhookSourceManager)++ @mock.patch(f"{API_CLIENT_PATCH}.create_webhook")+ def test_create_webhook_delegates(self, mock_create):+ self.source.create_webhook(self.config, WEBHOOK_URL, self.team_id)+ mock_create.assert_called_once_with("key", "secret", WEBHOOK_URL)++ @mock.patch(f"{API_CLIENT_PATCH}.delete_webhook")+ def test_delete_webhook_delegates(self, mock_delete):+ self.source.delete_webhook(self.config, WEBHOOK_URL, self.team_id)+ mock_delete.assert_called_once_with("key", "secret", WEBHOOK_URL)++ @mock.patch(f"{API_CLIENT_PATCH}.get_external_webhook_info")+ def test_get_external_webhook_info_delegates(self, mock_info):+ self.source.get_external_webhook_info(self.config, WEBHOOK_URL, self.team_id)+ mock_info.assert_called_once_with("key", "secret", WEBHOOK_URL)++ @mock.patch(f"{API_CLIENT_PATCH}.sync_webhook_events")+ def test_sync_webhook_events_passes_the_desired_events(self, mock_sync):+ self.source.sync_webhook_events(self.config, WEBHOOK_URL, self.team_id, [WEBHOOK_TABLE_NAME])+ mock_sync.assert_called_once_with("key", "secret", WEBHOOK_URL, list(MAILJET_WEBHOOK_EVENTS))+def test_get_schemas_filtered_by_names(self):schemas = self.source.get_schemas(self.config, self.team_id, names=["contact"])@@ -109,13 +175,15 @@ class TestMailJetSource:self.source.source_for_pipeline(self.config, manager, inputs)- mock_mailjet_source.assert_called_once_with(- api_key=self.config.api_key,- secret_key=self.config.secret_key,- endpoint="contact",- team_id=123,- job_id="job-1",- resumable_source_manager=manager,- should_use_incremental_field=False,- db_incremental_field_last_value=None,- )+ kwargs = mock_mailjet_source.call_args.kwargs+ assert kwargs["api_key"] == self.config.api_key+ assert kwargs["secret_key"] == self.config.secret_key+ assert kwargs["endpoint"] == "contact"+ assert kwargs["team_id"] == 123+ assert kwargs["job_id"] == "job-1"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is False+ assert kwargs["db_incremental_field_last_value"] is None+ # One sync covers both paths: the poll for the REST tables, the webhook manager for the+ # pushed message events.+ assert isinstance(kwargs["webhook_source_manager"], WebhookSourceManager)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/tests/test_mailjet_webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/tests/test_mailjet_webhook_template.pynew file mode 100644index 000000000000..6b921964cfdc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/tests/test_mailjet_webhook_template.py@@ -0,0 +1,149 @@+import json+import base64+import hashlib++from parameterized import parameterized++from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest++from products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.settings import MAILJET_WEBHOOK_EVENTS+from products.warehouse_sources.backend.temporal.data_imports.sources.mailjet.webhook_template import template++SOURCE_ID = "source_test_123"+AUTHORIZATION_HEADER = "Basic " + base64.b64encode(b"posthog:s3cr3t").decode()+SCHEMA_MAPPING = {"messageevent": "schema_message_events"}+++class TestMailjetWarehouseWebhookTemplate(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 _event(self, event_type: str = "open") -> dict:+ return {+ "event": event_type,+ "time": 1433103519,+ "MessageID": 19421777396190490,+ "Message_GUID": "1ab23cd4-e567-8901-2345-6789f0gh1i2j",+ "email": "[email protected]",+ "mj_campaign_id": 7173,+ "mj_contact_id": 320,+ "customcampaign": "",+ }++ def _request(self, body: dict, *, header: str | None = AUTHORIZATION_HEADER, method: str = "POST") -> dict:+ payload = json.dumps(body)+ return {+ "request": {+ "method": method,+ "headers": {} if header is None else {"authorization": header},+ "body": json.loads(payload),+ "stringBody": payload,+ "query": {},+ }+ }++ def _inputs(self, **overrides) -> dict:+ return {+ "authorization_header": AUTHORIZATION_HEADER,+ "bypass_authorization_check": False,+ "schema_mapping": SCHEMA_MAPPING,+ "source_id": SOURCE_ID,+ **overrides,+ }++ @parameterized.expand([(event,) for event in MAILJET_WEBHOOK_EVENTS])+ def test_every_registered_event_type_routes_to_the_message_event_table(self, event_type):+ # Every event type PostHog subscribes to in settings.py must have a route in the template,+ # or those deliveries would be acknowledged and silently dropped.+ globals = self._request(self._event(event_type))++ self.run_function(self._inputs(), globals=globals)++ self.mock_produce_to_warehouse_webhooks.assert_called_once()+ row, schema_id = self.mock_produce_to_warehouse_webhooks.call_args.args+ assert schema_id == "schema_message_events"+ assert row["event"] == event_type++ def test_event_id_is_the_hash_of_the_delivered_body(self):+ # Mailjet events carry no identifier, so the merge key is derived here. A retry replays the+ # same body and must land on the same row rather than duplicating it.+ globals = self._request(self._event())++ self.run_function(self._inputs(), globals=globals)++ row = self.mock_produce_to_warehouse_webhooks.call_args.args[0]+ assert row["event_id"] == hashlib.sha256(globals["request"]["stringBody"].encode()).hexdigest()++ def test_unknown_event_type_is_acknowledged_and_dropped(self):+ # A non-200 makes Mailjet retry every 30s for 24h, so an event we do not handle still 200s.+ globals = self._request(self._event("parse"))++ res = self.run_function(self._inputs(), globals=globals)++ assert res.result["httpResponse"]["status"] == 200+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_event_for_a_table_the_user_did_not_enable_is_dropped(self):+ globals = self._request(self._event())++ res = self.run_function(self._inputs(schema_mapping={}), globals=globals)++ assert res.result["httpResponse"]["status"] == 200+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_grouped_delivery_is_acknowledged_and_dropped(self):+ # Mailjet's Version 2 callbacks post a JSON array. PostHog registers Version 1, but a+ # hand-configured grouped callback must not be mistaken for a single event.+ globals = self._request(self._event())+ globals["request"]["body"] = [self._event(), self._event("click")]++ res = self.run_function(self._inputs(), globals=globals)++ assert res.result["httpResponse"]["status"] == 200+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ @parameterized.expand(+ [+ ("wrong_credentials", "Basic " + base64.b64encode(b"posthog:wrong").decode(), {}, 401),+ ("missing_header", None, {}, 401),+ ("no_expected_header_configured", AUTHORIZATION_HEADER, {"authorization_header": ""}, 400),+ ]+ )+ def test_unauthenticated_delivery_is_rejected(self, _name, header, input_overrides, expected_status):+ globals = self._request(self._event(), header=header)++ res = self.run_function(self._inputs(**input_overrides), globals=globals)++ assert res.result["httpResponse"]["status"] == expected_status+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_non_post_request_returns_405(self):+ globals = self._request(self._event(), method="GET")++ res = self.run_function(self._inputs(), globals=globals)++ assert res.result == {"httpResponse": {"status": 405, "body": "Method not allowed"}}++ def test_bypass_authorization_check_still_routes(self):+ globals = self._request(self._event(), header=None)++ self.run_function(+ self._inputs(authorization_header="", bypass_authorization_check=True),+ globals=globals,+ )++ self.mock_produce_to_warehouse_webhooks.assert_called_once()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/webhook_template.pynew file mode 100644index 000000000000..aec319c32350--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailjet/webhook_template.py@@ -0,0 +1,159 @@+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC++template: HogFunctionTemplateDC = HogFunctionTemplateDC(+ status="alpha",+ free=False,+ type="warehouse_source_webhook",+ id="template-warehouse-source-mailjet",+ name="Mailjet warehouse source webhook",+ description="Receive Mailjet Event API events for data warehouse ingestion",+ icon_url="/static/services/mailjet.png",+ category=["Data warehouse"],+ code_language="hog",+ code="""\+if (request.method != 'POST') {+ return {+ 'httpResponse': {+ 'status': 405,+ 'body': 'Method not allowed'+ }+ }+}++if (not inputs.bypass_authorization_check) {+ if (empty(inputs.authorization_header)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Authorization header value not configured',+ }+ }+ }++ // Mailjet signs nothing. It authenticates deliveries with the basic-auth credentials embedded+ // in the registered callback URL, which arrive here as an Authorization header.+ let providedHeader := request.headers['authorization']++ if (empty(providedHeader)) {+ return {+ 'httpResponse': {+ 'status': 401,+ 'body': 'Missing authorization header',+ }+ }+ }++ if (providedHeader != inputs.authorization_header) {+ return {+ 'httpResponse': {+ 'status': 401,+ 'body': 'Bad authorization header',+ }+ }+ }+}++// Version 1 callbacks post one event object. Version 2 posts an array of them, which the+// warehouse webhook pipeline can't unpack into rows — acknowledge and drop rather than error.+if (typeof(request.body) != 'object') {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'Expected a single event object, skipping'+ }+ }+}++let eventType := request.body?.event++if (empty(eventType)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'No event type found, skipping'+ }+ }+}++// Every Mailjet event type feeds the one messageevent table. Keep this in sync with+// MAILJET_WEBHOOK_EVENTS and SCHEMA_TO_WEBHOOK_RESOURCE in settings.py.+let resourceByEvent := {+ 'sent': 'messageevent',+ 'open': 'messageevent',+ 'click': 'messageevent',+ 'bounce': 'messageevent',+ 'blocked': 'messageevent',+ 'spam': 'messageevent',+ 'unsub': 'messageevent',+}++let resource := resourceByEvent?.[eventType]++if (empty(resource)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': f'Unhandled event type: {eventType}, skipping'+ }+ }+}++let schemaId := inputs.schema_mapping?.[resource]++if (empty(schemaId)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': f'No schema mapping for event type: {eventType}, skipping'+ }+ }+}++// Mailjet events carry no identifier of their own, so the raw body's hash is the row key.+// Mailjet re-POSTs the same body until it gets a 200, so retries land on the same row.+let row := request.body+row.event_id := sha256Hex(request.stringBody)++produceToWarehouseWebhooks(row, schemaId)""",+ inputs_schema=[+ {+ "type": "string",+ "key": "authorization_header",+ "label": "Authorization header",+ "required": False,+ "secret": True,+ "hidden": False,+ "description": (+ "The Authorization header PostHog expects on every Mailjet delivery. PostHog generates it "+ "and registers the matching basic-auth credentials on the Mailjet callback URL."+ ),+ },+ {+ "type": "boolean",+ "key": "bypass_authorization_check",+ "label": "Bypass authorization check",+ "description": "If set, the Authorization header will not be checked. This is not recommended.",+ "default": False,+ "required": False,+ "secret": False,+ },+ {+ "type": "json",+ "key": "schema_mapping",+ "label": "Schema mapping",+ "description": "Maps Mailjet 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,+ },+ ],+)