: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 Postmark webhook ingestion (#77466)
Tom Owersadccb9d009ba
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.mdindex 28cabe0b5a33..507778d3b896 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md@@ -640,7 +640,8 @@ Seventeen tables (10 API endpoints plus 7 webhook event streams) and one of our### Postmark — needs confirmation-Five tables. Delivery config is present, engagement is not.+Five tables. Delivery config is present, engagement is not. `bounces` also accepts pushed rows+through the Webhooks API (Bounce and SpamComplaint triggers).- [ ] Opens and clicks per message.- [ ] Outbound overview stats (sends, bounce rate, open rate, spam complaints).diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 1c81b247bae0..dcb0ceb4d739 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -495,7 +495,7 @@ the row lists both.| polar | HTTP | requests | ✅ || plaid | HTTP | requests | ✅ || postgres | DB protocol | psycopg | ➖ |-| postmark | HTTP | requests | ✅ |+| postmark | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || postscript | HTTP | requests + `rest_source.RESTClient` | ✅ || prefect_cloud | HTTP | requests | ✅ || pretix | HTTP | requests | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/postmark.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/postmark.pyindex 8bb9670a9cf9..953b73559093 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/postmark.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/postmark.py@@ -18,11 +18,22 @@ Two upstream constraints worth knowing about:"""import logging+import secretsimport dataclasses+from datetime import UTC, datetimefrom typing import Any, Optional-from requests import Response+import pyarrow as pa+from asgiref.sync import async_to_sync+from dateutil import parser as dateutil_parser+from requests import Response, 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,+)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,@@ -35,16 +46,29 @@ 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.postmark.settings import (POSTMARK_ENDPOINTS,POSTMARK_MAX_PAGE_SIZE,POSTMARK_MAX_WINDOW,+ WEBHOOK_MESSAGE_STREAM,+ WEBHOOK_ONLY_FIELDS,+ WEBHOOK_SCHEMA_NAMES,+ WEBHOOK_SECRET_HEADER,+ WEBHOOK_TRIGGERS,)logger = logging.getLogger(__name__)POSTMARK_BASE_URL = "https://api.postmarkapp.com"+REQUEST_TIMEOUT_SECONDS = 30++WEBHOOK_AUTH_ERROR = (+ "Your Postmark server API token can't manage webhooks. Webhooks are managed with a server "+ "token for the server you're syncing, so check the token and try again."+)+@dataclasses.dataclassclass PostmarkResumeConfig:@@ -104,6 +128,7 @@ def postmark_source(team_id: int,job_id: str,resumable_source_manager: ResumableSourceManager[PostmarkResumeConfig],+ webhook_source_manager: Optional[WebhookSourceManager] = None,) -> SourceResponse:config = POSTMARK_ENDPOINTS[endpoint]@@ -172,9 +197,20 @@ def postmark_source(initial_paginator_state=initial_paginator_state,)+ webhook_enabled = False+ if webhook_source_manager is not None and endpoint in WEBHOOK_SCHEMA_NAMES:+ webhook_enabled = async_to_sync(webhook_source_manager.webhook_enabled)(webhook_only=False)++ def items() -> Any:+ # Webhooks only take over once the backfill has completed, so the pull path stays the+ # way every table is first populated.+ if webhook_enabled and webhook_source_manager is not None:+ return webhook_source_manager.get_items(table_transformer=_webhook_table_transformer)+ return resource+return SourceResponse(name=endpoint,- items=lambda: resource,+ items=items,primary_keys=[config.primary_key],partition_count=1,partition_size=1,@@ -183,3 +219,158 @@ def postmark_source(partition_keys=[config.partition_key] if config.partition_key else None,column_hints=resource.column_hints,)+++def _parse_bounced_at(value: Any) -> Optional[datetime]:+ """Coerce a Postmark `BouncedAt` value to an aware UTC datetime.++ Postmark serializes .NET timestamps with up to seven fractional digits+ ("2019-11-05T16:33:54.9070259Z"), which `datetime.fromisoformat` rejects.+ """+ if isinstance(value, datetime):+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ if not isinstance(value, str) or not value:+ return None+ try:+ parsed = dateutil_parser.isoparse(value)+ except ValueError:+ return None+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)+++def _webhook_table_transformer(table: pa.Table) -> pa.Table:+ """Reshape raw webhook deliveries into rows matching the Bounce API table shape.++ Bounce and SpamComplaint deliveries carry the bounce record at the top level with the same+ field names the Bounce API returns, so the only reshaping needed is dropping the two+ webhook-only fields. Rows are then collapsed to the newest per `ID` — delta merge only+ dedupes across syncs, so a batch that carries the same record twice (a redelivery) has to+ collapse here.+ """+ latest_by_id: dict[Any, tuple[Optional[datetime], dict[str, Any]]] = {}+ for raw_row in table.to_pylist():+ row = {key: value for key, value in raw_row.items() if key not in WEBHOOK_ONLY_FIELDS}+ row_id = row.get("ID")+ if row_id is None:+ continue+ bounced_at = _parse_bounced_at(row.get("BouncedAt"))+ existing = latest_by_id.get(row_id)+ # Later rows win ties so batch arrival order breaks equal or missing timestamps.+ if existing is None or existing[0] is None or (bounced_at is not None and bounced_at >= existing[0]):+ latest_by_id[row_id] = (bounced_at, row)++ return table_from_py_list([row for _, row in latest_by_id.values()])+++def _webhook_management_session(server_token: str) -> Session:+ return make_tracked_session(+ headers={**_get_headers(server_token), "Content-Type": "application/json"},+ # Webhook objects echo back the HttpHeaders we set, which carry the shared secret, so+ # keep these responses out of HTTP sample capture.+ capture=False,+ redact_values=(server_token,),+ )+++def _postmark_error(response: Response) -> str | None:+ """Postmark reports API failures as a JSON body with a non-zero `ErrorCode`."""+ try:+ body = response.json()+ except ValueError:+ return None+ if not isinstance(body, dict) or not body.get("ErrorCode"):+ return None+ message = body.get("Message")+ return str(message) if message else f"Postmark error code {body['ErrorCode']}"+++def _list_webhooks(session: Session) -> list[dict[str, Any]]:+ # A server holds a handful of webhooks and the endpoint is not paginated.+ response = session.get(f"{POSTMARK_BASE_URL}/webhooks", timeout=REQUEST_TIMEOUT_SECONDS)+ response.raise_for_status()+ body = response.json()+ webhooks = body.get("Webhooks") if isinstance(body, dict) else None+ if not isinstance(webhooks, list):+ return []+ return [webhook for webhook in webhooks if isinstance(webhook, dict)]+++def _find_webhook_by_url(session: Session, webhook_url: str) -> dict[str, Any] | None:+ return next((webhook for webhook in _list_webhooks(session) if webhook.get("Url") == webhook_url), None)+++def create_webhook(server_token: str, webhook_url: str) -> WebhookCreationResult:+ try:+ session = _webhook_management_session(server_token)+ secret = secrets.token_urlsafe(32)+ body: dict[str, Any] = {+ "Url": webhook_url,+ "MessageStream": WEBHOOK_MESSAGE_STREAM,+ "HttpHeaders": [{"Name": WEBHOOK_SECRET_HEADER, "Value": secret}],+ "Triggers": WEBHOOK_TRIGGERS,+ }++ existing = _find_webhook_by_url(session, webhook_url)+ if existing is not None and existing.get("ID") is not None:+ # A webhook for this URL already exists (e.g. a partial earlier setup) — reconcile it+ # with a fresh secret instead of creating a duplicate.+ response = session.put(+ f"{POSTMARK_BASE_URL}/webhooks/{existing['ID']}", json=body, timeout=REQUEST_TIMEOUT_SECONDS+ )+ else:+ response = session.post(f"{POSTMARK_BASE_URL}/webhooks", json=body, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code in (401, 403):+ return WebhookCreationResult(success=False, error=WEBHOOK_AUTH_ERROR)+ error = _postmark_error(response)+ if not response.ok or error:+ raise Exception(error or f"Postmark webhook creation failed with HTTP {response.status_code}")+ return WebhookCreationResult(success=True, extra_inputs={"signing_secret": secret})+ except Exception as e:+ logger.exception(f"Postmark: failed to create webhook: {e}")+ return WebhookCreationResult(+ success=False, error=f"Failed to create the Postmark webhook: {e}. Please create it manually below."+ )+++def get_external_webhook_info(server_token: str, webhook_url: str) -> ExternalWebhookInfo:+ try:+ session = _webhook_management_session(server_token)+ existing = _find_webhook_by_url(session, webhook_url)+ if existing is None:+ return ExternalWebhookInfo(exists=False)++ raw_triggers = existing.get("Triggers")+ triggers: dict[str, Any] = raw_triggers if isinstance(raw_triggers, dict) else {}+ enabled_events = [+ name for name, trigger in triggers.items() if isinstance(trigger, dict) and trigger.get("Enabled")+ ]+ return ExternalWebhookInfo(+ exists=True,+ url=existing.get("Url"),+ enabled_events=enabled_events,+ status="enabled",+ description=f"Message stream: {existing.get('MessageStream')}" if existing.get("MessageStream") else None,+ )+ except Exception as e:+ return ExternalWebhookInfo(exists=False, error=f"Failed to check the Postmark webhook: {e}")+++def delete_webhook(server_token: str, webhook_url: str) -> WebhookDeletionResult:+ try:+ session = _webhook_management_session(server_token)+ existing = _find_webhook_by_url(session, webhook_url)+ if existing is None or existing.get("ID") is None:+ # Nothing to delete — the desired end state already holds.+ return WebhookDeletionResult(success=True)++ response = session.delete(f"{POSTMARK_BASE_URL}/webhooks/{existing['ID']}", timeout=REQUEST_TIMEOUT_SECONDS)+ if response.status_code in (401, 403):+ return WebhookDeletionResult(success=False, error=WEBHOOK_AUTH_ERROR)+ error = _postmark_error(response)+ if not response.ok or error:+ raise Exception(error or f"Postmark webhook deletion failed with HTTP {response.status_code}")+ return WebhookDeletionResult(success=True)+ except Exception as e:+ logger.exception(f"Postmark: failed to delete webhook: {e}")+ return WebhookDeletionResult(success=False, error=f"Failed to delete the Postmark webhook: {e}")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/settings.pyindex 362ab2a02565..1ca3be6e38e4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/settings.py@@ -66,3 +66,37 @@ POSTMARK_ENDPOINTS: dict[str, PostmarkEndpointConfig] = {ENDPOINTS = tuple(POSTMARK_ENDPOINTS.keys())+++# --- Webhook ingestion -------------------------------------------------------------------+#+# Postmark's Bounce and SpamComplaint webhooks serialize the same bounce record the Bounce API+# lists, field for field, so both feed the `bounces` table. The other triggers (Delivery, Open,+# Click, SubscriptionChange) describe message events we have no table for, and inbound webhooks+# are configured on the server rather than through the Webhooks API — neither is wired up.++# Schemas that can be fed by pushed rows as well as the backfill.+WEBHOOK_SCHEMA_NAMES = frozenset({"bounces"})++# Schema name -> the `schema_mapping` key incoming deliveries are routed by.+WEBHOOK_RESOURCE_MAP = {"bounces": "Bounce"}++# Triggers we subscribe to. `IncludeContent` stays off so pushed rows carry the same fields the+# Bounce API list response does (the raw dump is only available per-bounce).+WEBHOOK_TRIGGERS: dict[str, dict[str, bool]] = {+ "Bounce": {"Enabled": True, "IncludeContent": False},+ "SpamComplaint": {"Enabled": True, "IncludeContent": False},+}++# Webhooks are per message stream. The `bounces` backfill doesn't pass `messagestream`, which+# Postmark defaults to `outbound`, so subscribing the same stream keeps push and pull covering+# the same rows.+WEBHOOK_MESSAGE_STREAM = "outbound"++# Postmark doesn't sign deliveries, but the Webhooks API lets us pin static headers onto a+# webhook. `create_webhook` sets a generated secret here and the template requires it back.+WEBHOOK_SECRET_HEADER = "x-posthog-webhook-secret"++# Fields a webhook delivery carries that the Bounce API list response does not. `Metadata` holds+# arbitrary user-defined keys, so keeping it would evolve the table schema on every new key.+WEBHOOK_ONLY_FIELDS = ("Metadata", "Content")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/source.pyindex 08eb8af3c196..af28a770086d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/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,14 @@ 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,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)@@ -17,20 +24,34 @@ 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.postmark import (PostmarkSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.postmark.postmark import (PostmarkResumeConfig,+ create_webhook as create_postmark_webhook,+ delete_webhook as delete_postmark_webhook,+ get_external_webhook_info as get_postmark_webhook_info,postmark_source,validate_credentials as validate_postmark_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.postmark.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.postmark.settings import (+ ENDPOINTS,+ WEBHOOK_RESOURCE_MAP,+ 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 PostmarkSource(ResumableSource[PostmarkSourceConfig, PostmarkResumeConfig]):+class PostmarkSource(+ ResumableSource[PostmarkSourceConfig, PostmarkResumeConfig],+ WebhookSource[PostmarkSourceConfig],+):api_docs_url = "https://postmarkapp.com/developer"lists_tables_without_credentials = True # static endpoint catalog — safe for public docs@@ -72,6 +93,28 @@ The token grants read access to the following server-level resources:),],),+ webhookSetupCaption="""Postmark pushes bounces and spam complaints as they happen, so the bounces table stays current between syncs.++To set the webhook up manually:++1. In Postmark, go to **Servers → (your server) → Webhooks** and add a webhook+2. Set the URL to the webhook URL shown below, pick the **outbound** message stream, and enable the **Bounce** and **Spam complaint** triggers+3. Add a custom HTTP header named `x-posthog-webhook-secret` with a value of your choosing, and paste the same value into the webhook secret field below++Postmark doesn't sign deliveries, so the header is what proves a delivery came from your webhook. Deliveries without it are rejected.""",+ webhookFields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="signing_secret",+ label="Webhook secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),)def get_canonical_descriptions(self) -> CanonicalDescriptions:@@ -94,7 +137,13 @@ The token grants read access to the following server-level resources:# server-side filtering against a live token, so we sync full-refresh only. Within-sync# resumption is handled by ResumableSource.schemas = [- SourceSchema(name=endpoint, supports_incremental=False, supports_append=False, incremental_fields=[])+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ supports_webhooks=endpoint in WEBHOOK_SCHEMA_NAMES,+ )for endpoint in ENDPOINTS]if names is not None:@@ -138,6 +187,36 @@ The token grants read access to the following server-level resources:def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PostmarkResumeConfig]:return ResumableSourceManager[PostmarkResumeConfig](inputs, PostmarkResumeConfig)+ @property+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:+ from products.warehouse_sources.backend.temporal.data_imports.sources.postmark.webhook_template import ( # noqa: PLC0415+ template,+ )++ return template++ @property+ def webhook_resource_map(self) -> dict[str, str]:+ return dict(WEBHOOK_RESOURCE_MAP)++ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:+ return WebhookSourceManager(inputs, inputs.logger)++ def create_webhook(+ self, config: PostmarkSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> WebhookCreationResult:+ return create_postmark_webhook(config.server_token, webhook_url)++ def get_external_webhook_info(+ self, config: PostmarkSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> ExternalWebhookInfo:+ return get_postmark_webhook_info(config.server_token, webhook_url)++ def delete_webhook(+ self, config: PostmarkSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None+ ) -> WebhookDeletionResult:+ return delete_postmark_webhook(config.server_token, webhook_url)+def source_for_pipeline(self,config: PostmarkSourceConfig,@@ -150,4 +229,5 @@ The token grants read access to the following server-level resources:team_id=inputs.team_id,job_id=inputs.job_id,resumable_source_manager=resumable_source_manager,+ webhook_source_manager=self.get_webhook_source_manager(inputs),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/tests/test_postmark.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/tests/test_postmark.pyindex 0129b917e956..8359a9add876 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/tests/test_postmark.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/tests/test_postmark.py@@ -7,9 +7,15 @@ from unittest import mockfrom parameterized import parameterizedfrom requests import Response+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_listfrom products.warehouse_sources.backend.temporal.data_imports.sources.postmark.postmark import (POSTMARK_BASE_URL,+ WEBHOOK_AUTH_ERROR,PostmarkResumeConfig,+ _webhook_table_transformer,+ create_webhook,+ delete_webhook,+ get_external_webhook_info,postmark_source,validate_credentials,)@@ -17,6 +23,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postmark.sENDPOINTS,POSTMARK_ENDPOINTS,POSTMARK_MAX_WINDOW,+ WEBHOOK_MESSAGE_STREAM,+ WEBHOOK_SCHEMA_NAMES,+ WEBHOOK_SECRET_HEADER,)# RESTClient builds its session via make_tracked_session in the rest_client module.@@ -25,6 +34,8 @@ CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_importsPOSTMARK_SESSION_PATCH = ("products.warehouse_sources.backend.temporal.data_imports.sources.postmark.postmark.make_tracked_session")+# Webhook management builds its session through the same module-level helper.+WEBHOOK_SESSION_PATCH = POSTMARK_SESSION_PATCHdef _response(body: dict[str, Any], *, status: int = 200) -> Response:@@ -250,3 +261,275 @@ class TestRetryable:_rows(_source("message_streams", _make_manager()))assert session.send.call_count == 1+++def _bounce(bounce_id: int, **overrides: Any) -> dict[str, Any]:+ return {+ "RecordType": "Bounce",+ "ID": bounce_id,+ "Type": "HardBounce",+ "TypeCode": 1,+ "MessageID": "883953f4-6105-42a2-a16a-77a8eac79483",+ "Email": "[email protected]",+ "BouncedAt": "2026-01-01T00:00:00.0000000Z",+ "Inactive": True,+ **overrides,+ }+++class TestWebhookTableTransformer:+ def test_drops_webhook_only_fields_so_rows_match_the_pull_shape(self):+ # Metadata holds arbitrary user keys; keeping it would evolve the table schema on every+ # new key a customer sets, and neither field exists in the Bounce API list response.+ table = table_from_py_list([_bounce(1, Metadata={"plan": "pro"}, Content="<dump>")])++ rows = _webhook_table_transformer(table).to_pylist()++ assert len(rows) == 1+ assert "Metadata" not in rows[0]+ assert "Content" not in rows[0]+ assert rows[0]["ID"] == 1++ def test_keeps_the_latest_row_per_id_within_a_batch(self):+ # Delta merge only dedupes across syncs, so a redelivery inside one batch has to+ # collapse here or the merge multi-matches on ID.+ table = table_from_py_list(+ [+ _bounce(1, BouncedAt="2026-01-01T00:00:00.0000000Z", Inactive=True),+ _bounce(2, BouncedAt="2026-01-02T00:00:00.0000000Z"),+ _bounce(1, BouncedAt="2026-01-03T00:00:00.0000000Z", Inactive=False),+ ]+ )++ rows = {row["ID"]: row for row in _webhook_table_transformer(table).to_pylist()}++ assert len(rows) == 2+ assert rows[1]["Inactive"] is False+ assert rows[1]["BouncedAt"] == "2026-01-03T00:00:00.0000000Z"++ @parameterized.expand(+ [+ ("unparseable_timestamp", "not-a-date"),+ ("missing_timestamp", None),+ ]+ )+ def test_falls_back_to_arrival_order_when_the_timestamp_is_unusable(self, _name: str, bounced_at: Any):+ table = table_from_py_list(+ [+ _bounce(1, BouncedAt=bounced_at, Inactive=True),+ _bounce(1, BouncedAt=bounced_at, Inactive=False),+ ]+ )++ rows = _webhook_table_transformer(table).to_pylist()++ assert len(rows) == 1+ assert rows[0]["Inactive"] is False++ def test_drops_rows_without_an_id(self):+ # ID is the merge key, so a row without one would land unmergeable.+ table = table_from_py_list([_bounce(1), {**_bounce(2), "ID": None}])++ rows = _webhook_table_transformer(table).to_pylist()++ assert [row["ID"] for row in rows] == [1]+++class TestWebhookItemsWiring:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_bounces_reads_pushed_rows_once_the_webhook_is_live(self, MockSession):+ _wire(MockSession.return_value, [_response({"Bounces": [_bounce(1)], "TotalCount": 1})])+ webhook_manager = mock.MagicMock()+ webhook_manager.webhook_enabled = mock.AsyncMock(return_value=True)+ webhook_manager.get_items.return_value = iter([[_bounce(9)]])++ response = postmark_source(+ "test-token",+ "bounces",+ team_id=1,+ job_id="j",+ resumable_source_manager=_make_manager(),+ webhook_source_manager=webhook_manager,+ )+ rows = _rows(response)++ assert [row["ID"] for row in rows] == [9]+ assert MockSession.return_value.send.call_count == 0+ # Webhooks only take over after the backfill has completed.+ assert webhook_manager.webhook_enabled.await_args.kwargs == {"webhook_only": False}+ assert webhook_manager.get_items.call_args.kwargs["table_transformer"] is _webhook_table_transformer++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_bounces_falls_back_to_the_pull_api_when_no_webhook_is_live(self, MockSession):+ _wire(MockSession.return_value, [_response({"Bounces": [_bounce(1)], "TotalCount": 1})])+ webhook_manager = mock.MagicMock()+ webhook_manager.webhook_enabled = mock.AsyncMock(return_value=False)++ rows = _rows(+ postmark_source(+ "test-token",+ "bounces",+ team_id=1,+ job_id="j",+ resumable_source_manager=_make_manager(),+ webhook_source_manager=webhook_manager,+ )+ )++ assert [row["ID"] for row in rows] == [1]+ webhook_manager.get_items.assert_not_called()++ @parameterized.expand([(name,) for name in ENDPOINTS if name not in WEBHOOK_SCHEMA_NAMES])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_non_webhook_endpoints_never_consult_the_webhook_manager(self, endpoint: str, MockSession):+ # Only bounces has a matching Postmark trigger; the rest must keep polling regardless+ # of whether a webhook function exists for the source.+ _wire(MockSession.return_value, lambda *a, **k: _response({POSTMARK_ENDPOINTS[endpoint].data_key: []}))+ webhook_manager = mock.MagicMock()+ webhook_manager.webhook_enabled = mock.AsyncMock(return_value=True)++ _rows(+ postmark_source(+ "test-token",+ endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=_make_manager(),+ webhook_source_manager=webhook_manager,+ )+ )++ webhook_manager.webhook_enabled.assert_not_awaited()+ webhook_manager.get_items.assert_not_called()+++class TestWebhookManagement:+ @mock.patch(WEBHOOK_SESSION_PATCH)+ def test_create_webhook_subscribes_bounce_triggers_with_a_secret_header(self, mock_session):+ session = mock_session.return_value+ session.get.return_value = _response({"Webhooks": []})+ session.post.return_value = _response({"ID": 42, "Url": "https://ph.example/webhook"})++ result = create_webhook("test-token", "https://ph.example/webhook")++ assert result.success is True+ secret = result.extra_inputs["signing_secret"]+ assert secret+ body = session.post.call_args.kwargs["json"]+ assert body["Url"] == "https://ph.example/webhook"+ assert body["MessageStream"] == WEBHOOK_MESSAGE_STREAM+ # Postmark signs nothing, so the shared secret header is the only proof of origin.+ assert body["HttpHeaders"] == [{"Name": WEBHOOK_SECRET_HEADER, "Value": secret}]+ # Bounce alone would leave spam complaints unsynced once webhooks take over polling.+ assert {name for name, trigger in body["Triggers"].items() if trigger["Enabled"]} == {+ "Bounce",+ "SpamComplaint",+ }+ assert all(not trigger["IncludeContent"] for trigger in body["Triggers"].values())+ # Webhook objects echo the secret back, so they stay out of HTTP sample capture.+ assert mock_session.call_args.kwargs["capture"] is False+ assert mock_session.call_args.kwargs["redact_values"] == ("test-token",)++ @mock.patch(WEBHOOK_SESSION_PATCH)+ def test_create_webhook_updates_an_existing_url_instead_of_duplicating(self, mock_session):+ session = mock_session.return_value+ session.get.return_value = _response({"Webhooks": [{"ID": 7, "Url": "https://ph.example/webhook"}]})+ session.put.return_value = _response({"ID": 7, "Url": "https://ph.example/webhook"})++ result = create_webhook("test-token", "https://ph.example/webhook")++ assert result.success is True+ session.post.assert_not_called()+ assert session.put.call_args.args[0] == f"{POSTMARK_BASE_URL}/webhooks/7"++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])+ @mock.patch(WEBHOOK_SESSION_PATCH)+ def test_create_webhook_surfaces_a_token_problem(self, _name: str, status: int, mock_session):+ session = mock_session.return_value+ session.get.return_value = _response({"Webhooks": []})+ session.post.return_value = _response({}, status=status)++ result = create_webhook("test-token", "https://ph.example/webhook")++ assert result.success is False+ assert result.error == WEBHOOK_AUTH_ERROR++ @mock.patch(WEBHOOK_SESSION_PATCH)+ def test_create_webhook_treats_a_200_with_an_error_code_as_a_failure(self, mock_session):+ # Postmark reports API failures in the body, so response.ok alone would report success.+ session = mock_session.return_value+ session.get.return_value = _response({"Webhooks": []})+ session.post.return_value = _response({"ErrorCode": 401, "Message": "Not allowed"})++ result = create_webhook("test-token", "https://ph.example/webhook")++ assert result.success is False+ assert "Not allowed" in (result.error or "")++ @mock.patch(WEBHOOK_SESSION_PATCH)+ def test_get_external_webhook_info_reports_enabled_triggers(self, mock_session):+ mock_session.return_value.get.return_value = _response(+ {+ "Webhooks": [+ {+ "ID": 7,+ "Url": "https://ph.example/webhook",+ "MessageStream": "outbound",+ "Triggers": {+ "Bounce": {"Enabled": True},+ "SpamComplaint": {"Enabled": True},+ "Open": {"Enabled": False},+ },+ }+ ]+ }+ )++ info = get_external_webhook_info("test-token", "https://ph.example/webhook")++ assert info.exists is True+ assert info.url == "https://ph.example/webhook"+ assert set(info.enabled_events or []) == {"Bounce", "SpamComplaint"}++ @mock.patch(WEBHOOK_SESSION_PATCH)+ def test_get_external_webhook_info_ignores_other_urls(self, mock_session):+ mock_session.return_value.get.return_value = _response(+ {"Webhooks": [{"ID": 7, "Url": "https://someone-else.example/hook"}]}+ )++ info = get_external_webhook_info("test-token", "https://ph.example/webhook")++ assert info.exists is False+ assert info.error is None++ @mock.patch(WEBHOOK_SESSION_PATCH)+ def test_delete_webhook_removes_the_matching_webhook(self, mock_session):+ session = mock_session.return_value+ session.get.return_value = _response({"Webhooks": [{"ID": 7, "Url": "https://ph.example/webhook"}]})+ session.delete.return_value = _response({"ErrorCode": 0, "Message": "Webhook 7 removed."})++ result = delete_webhook("test-token", "https://ph.example/webhook")++ assert result.success is True+ assert session.delete.call_args.args[0] == f"{POSTMARK_BASE_URL}/webhooks/7"++ @mock.patch(WEBHOOK_SESSION_PATCH)+ def test_delete_webhook_is_idempotent_when_already_gone(self, mock_session):+ session = mock_session.return_value+ session.get.return_value = _response({"Webhooks": []})++ result = delete_webhook("test-token", "https://ph.example/webhook")++ assert result.success is True+ session.delete.assert_not_called()++ @mock.patch(WEBHOOK_SESSION_PATCH)+ def test_delete_webhook_reports_a_failure(self, mock_session):+ session = mock_session.return_value+ session.get.return_value = _response({"Webhooks": [{"ID": 7, "Url": "https://ph.example/webhook"}]})+ session.delete.return_value = _response({"ErrorCode": 501, "Message": "Webhook not found."}, status=422)++ result = delete_webhook("test-token", "https://ph.example/webhook")++ assert result.success is False+ assert "Webhook not found." in (result.error or "")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/tests/test_postmark_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/tests/test_postmark_source.pyindex d1023a3a0ccd..c56d4244660b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/tests/test_postmark_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/tests/test_postmark_source.py@@ -5,6 +5,7 @@ from parameterized import parameterizedfrom posthog.schema import 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.postmark import (PostmarkSourceConfig,)@@ -115,10 +116,66 @@ class TestPostmarkSource:self.source.source_for_pipeline(self.config, manager, inputs)- mock_postmark_source.assert_called_once_with(- server_token=self.config.server_token,- endpoint="messages_outbound",- team_id=inputs.team_id,- job_id=inputs.job_id,- resumable_source_manager=manager,- )+ call_kwargs = mock_postmark_source.call_args.kwargs+ assert call_kwargs["server_token"] == self.config.server_token+ assert call_kwargs["endpoint"] == "messages_outbound"+ assert call_kwargs["team_id"] == inputs.team_id+ assert call_kwargs["job_id"] == inputs.job_id+ assert call_kwargs["resumable_source_manager"] is manager+ # The webhook manager rides alongside the pull iterator so one sync covers both.+ assert isinstance(call_kwargs["webhook_source_manager"], WebhookSourceManager)++ def test_get_schemas_marks_only_bounces_webhook_capable(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ webhook_capable = {schema.name for schema in schemas if schema.supports_webhooks}+ # Only bounces has a Postmark trigger whose payload matches a table we already sync.+ assert webhook_capable == {"bounces"}+ assert not any(schema.webhook_only for schema in schemas)++ def test_webhook_resource_map_routes_bounces(self):+ assert self.source.webhook_resource_map == {"bounces": "Bounce"}+ # The template looks the schema id up under this key, so a rename breaks routing.+ assert self.source.webhook_mapping_key("bounces") == "Bounce"++ def test_webhook_template_requires_a_secret(self):+ template = self.source.webhook_template++ assert template is not None+ assert template.type == "warehouse_source_webhook"+ inputs_by_key = {item["key"]: item for item in template.inputs_schema}+ assert set(inputs_by_key) == {"signing_secret", "schema_mapping", "source_id"}+ # No bypass input exists, so an unauthenticated delivery can never be accepted.+ assert inputs_by_key["signing_secret"]["required"] is True+ assert inputs_by_key["signing_secret"]["secret"] is True++ def test_webhook_fields_ask_for_the_shared_secret(self):+ webhook_fields = self.source.get_source_config.webhookFields++ assert webhook_fields is not None+ assert len(webhook_fields) == 1+ secret_field = webhook_fields[0]+ assert isinstance(secret_field, SourceFieldInputConfig)+ assert secret_field.name == "signing_secret"+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD+ assert secret_field.secret is True++ def test_get_webhook_source_manager(self):+ inputs = mock.MagicMock()+ assert isinstance(self.source.get_webhook_source_manager(inputs), WebhookSourceManager)++ @parameterized.expand(+ [+ ("create_webhook", "create_postmark_webhook"),+ ("get_external_webhook_info", "get_postmark_webhook_info"),+ ("delete_webhook", "delete_postmark_webhook"),+ ]+ )+ def test_webhook_management_delegates_with_the_server_token(self, method_name, patched_name):+ with mock.patch(+ f"products.warehouse_sources.backend.temporal.data_imports.sources.postmark.source.{patched_name}"+ ) as mock_fn:+ result = getattr(self.source, method_name)(self.config, "https://ph.example/webhook", self.team_id)++ mock_fn.assert_called_once_with(self.config.server_token, "https://ph.example/webhook")+ assert result is mock_fn.return_valuediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/tests/test_postmark_webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/tests/test_postmark_webhook_template.pynew file mode 100644index 000000000000..640af994ae47--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/tests/test_postmark_webhook_template.py@@ -0,0 +1,122 @@+import json++from parameterized import parameterized++from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest++from products.warehouse_sources.backend.temporal.data_imports.sources.postmark.settings import WEBHOOK_SECRET_HEADER+from products.warehouse_sources.backend.temporal.data_imports.sources.postmark.webhook_template import template++SOURCE_ID = "source_test_123"+WEBHOOK_SECRET = "0Pm2Yb8bJ0Yl7vGQ9m1Z2xTn5cRk4dWq"+SCHEMA_MAPPING = {"Bounce": "schema_bounces"}+++class TestPostmarkWarehouseWebhookTemplate(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 _bounce(self, record_type: str = "Bounce") -> dict:+ return {+ "RecordType": record_type,+ "MessageStream": "outbound",+ "ID": 4323372036854775807,+ "Type": "HardBounce",+ "TypeCode": 1,+ "Email": "[email protected]",+ "BouncedAt": "2026-01-05T16:33:54.9070259Z",+ }++ def _request(self, body: dict, headers: dict | None = None, method: str = "POST") -> dict:+ payload = json.dumps(body)+ return {+ "request": {+ "method": method,+ "headers": {WEBHOOK_SECRET_HEADER: WEBHOOK_SECRET} if headers is None else headers,+ "body": json.loads(payload),+ "stringBody": payload,+ "query": {},+ }+ }++ def _inputs(self, **overrides) -> dict:+ return {+ "signing_secret": WEBHOOK_SECRET,+ "schema_mapping": SCHEMA_MAPPING,+ "source_id": SOURCE_ID,+ **overrides,+ }++ @parameterized.expand([("Bounce",), ("SpamComplaint",)])+ def test_routes_bounce_records_to_the_bounces_table(self, record_type):+ # Spam complaints are bounce records too, and the Bounce API lists them alongside the+ # rest — routing them elsewhere (or dropping them) would lose rows once webhooks take+ # over from polling.+ globals = self._request(self._bounce(record_type))++ self.run_function(self._inputs(), globals=globals)++ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(globals["request"]["body"], "schema_bounces")++ @parameterized.expand([("Delivery",), ("Open",), ("SubscriptionChange",)])+ def test_other_record_types_are_acknowledged_and_dropped(self, record_type):+ # A manually broadened webhook can deliver triggers we have no table for; a 5xx here+ # would put Postmark into a retry storm.+ globals = self._request(self._bounce(record_type))++ 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_bounce_is_dropped_when_the_table_is_not_enabled(self):+ globals = self._request(self._bounce())++ 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()++ @parameterized.expand(+ [+ ("wrong_secret", {WEBHOOK_SECRET_HEADER: "not-the-secret"}, {}, "Bad webhook secret"),+ ("missing_header", {}, {}, "Bad webhook secret"),+ (+ "secret_not_configured",+ {WEBHOOK_SECRET_HEADER: WEBHOOK_SECRET},+ {"signing_secret": ""},+ "Webhook secret not configured",+ ),+ ]+ )+ def test_unauthenticated_deliveries_are_rejected(self, _name, headers, input_overrides, expected_body):+ # Postmark signs nothing, so this header is the only proof of origin. There is no bypass+ # input, so no configuration can accept an unauthenticated delivery.+ globals = self._request(self._bounce(), headers=headers)++ res = self.run_function(self._inputs(**input_overrides), globals=globals)++ assert res.result == {"httpResponse": {"status": 400, "body": expected_body}}+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_non_post_is_rejected(self):+ globals = self._request(self._bounce(), method="GET")++ res = self.run_function(self._inputs(), globals=globals)++ assert res.result["httpResponse"]["status"] == 405+ self.mock_produce_to_warehouse_webhooks.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/webhook_template.pynew file mode 100644index 000000000000..1590bbe9917d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postmark/webhook_template.py@@ -0,0 +1,102 @@+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC++# Postmark does not sign webhook deliveries, but the Webhooks API pins static headers onto a+# webhook. `create_webhook` attaches a generated secret in the x-posthog-webhook-secret header,+# which this template requires on every delivery. A manually created webhook has to configure+# the same header (via the Webhooks API or the webhook editor) — there is no bypass, so an+# unauthenticated delivery is always rejected.+template: HogFunctionTemplateDC = HogFunctionTemplateDC(+ status="alpha",+ free=False,+ type="warehouse_source_webhook",+ id="template-warehouse-source-postmark",+ name="Postmark warehouse source webhook",+ description="Receive Postmark webhook events for data warehouse ingestion",+ icon_url="/static/services/postmark.png",+ category=["Data warehouse"],+ code_language="hog",+ code="""\+if (request.method != 'POST') {+ return {+ 'httpResponse': {+ 'status': 405,+ 'body': 'Method not allowed'+ }+ }+}++if (empty(inputs.signing_secret)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Webhook secret not configured',+ }+ }+}++let providedSecret := request.headers['x-posthog-webhook-secret']++if (empty(providedSecret) or providedSecret != inputs.signing_secret) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Bad webhook secret',+ }+ }+}++let recordType := request.body.RecordType++// Spam complaints are bounce records too, so both land in the bounces table. Anything else is+// acknowledged and dropped rather than errored, so an over-broad webhook can't retry-storm us.+if (recordType != 'Bounce' and recordType != 'SpamComplaint') {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'Unhandled record type, skipping'+ }+ }+}++let schemaId := inputs.schema_mapping?.['Bounce']++if (empty(schemaId)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'No schema mapping for bounces, skipping'+ }+ }+}++produceToWarehouseWebhooks(request.body, schemaId)""",+ inputs_schema=[+ {+ "type": "string",+ "key": "signing_secret",+ "label": "Webhook secret",+ "required": True,+ "secret": True,+ "hidden": False,+ "description": "Shared secret sent by Postmark in the x-posthog-webhook-secret header, used to verify the delivery came from your webhook",+ },+ {+ "type": "json",+ "key": "schema_mapping",+ "label": "Schema mapping",+ "description": "Maps Postmark webhook record types 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,+ },+ ],+)